Support for CPU binding in Solaris
[fio.git] / fio.c
1 /*
2  * fio - the flexible io tester
3  *
4  * Copyright (C) 2005 Jens Axboe <axboe@suse.de>
5  * Copyright (C) 2006 Jens Axboe <axboe@kernel.dk>
6  *
7  * The license below covers all files distributed with fio unless otherwise
8  * noted in the file itself.
9  *
10  *  This program is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License version 2 as
12  *  published by the Free Software Foundation.
13  *
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License
20  *  along with this program; if not, write to the Free Software
21  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  *
23  */
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <string.h>
27 #include <signal.h>
28 #include <time.h>
29 #include <locale.h>
30 #include <assert.h>
31 #include <sys/stat.h>
32 #include <sys/wait.h>
33 #include <sys/ipc.h>
34 #include <sys/shm.h>
35 #include <sys/mman.h>
36
37 #include "fio.h"
38 #include "hash.h"
39 #include "smalloc.h"
40
41 unsigned long page_mask;
42 unsigned long page_size;
43 #define ALIGN(buf)      \
44         (char *) (((unsigned long) (buf) + page_mask) & ~page_mask)
45
46 int groupid = 0;
47 int thread_number = 0;
48 int nr_process = 0;
49 int nr_thread = 0;
50 int shm_id = 0;
51 int temp_stall_ts;
52 unsigned long done_secs = 0;
53
54 static struct fio_mutex *startup_mutex;
55 static volatile int fio_abort;
56 static int exit_value;
57 static struct itimerval itimer;
58 static pthread_t gtod_thread;
59
60 struct io_log *agg_io_log[2];
61
62 #define TERMINATE_ALL           (-1)
63 #define JOB_START_TIMEOUT       (5 * 1000)
64
65 void td_set_runstate(struct thread_data *td, int runstate)
66 {
67         if (td->runstate == runstate)
68                 return;
69
70         dprint(FD_PROCESS, "pid=%d: runstate %d -> %d\n", (int) td->pid,
71                                                 td->runstate, runstate);
72         td->runstate = runstate;
73 }
74
75 static void terminate_threads(int group_id)
76 {
77         struct thread_data *td;
78         int i;
79
80         dprint(FD_PROCESS, "terminate group_id=%d\n", group_id);
81
82         for_each_td(td, i) {
83                 if (group_id == TERMINATE_ALL || groupid == td->groupid) {
84                         dprint(FD_PROCESS, "setting terminate on %s/%d\n",
85                                                 td->o.name, (int) td->pid);
86                         td->terminate = 1;
87                         td->o.start_delay = 0;
88
89                         /*
90                          * if the thread is running, just let it exit
91                          */
92                         if (td->runstate < TD_RUNNING)
93                                 kill(td->pid, SIGQUIT);
94                         else {
95                                 struct ioengine_ops *ops = td->io_ops;
96
97                                 if (ops && (ops->flags & FIO_SIGQUIT))
98                                         kill(td->pid, SIGQUIT);
99                         }
100                 }
101         }
102 }
103
104 static void status_timer_arm(void)
105 {
106         itimer.it_value.tv_sec = 0;
107         itimer.it_value.tv_usec = DISK_UTIL_MSEC * 1000;
108         setitimer(ITIMER_REAL, &itimer, NULL);
109 }
110
111 static void sig_alrm(int fio_unused sig)
112 {
113         if (threads) {
114                 update_io_ticks();
115                 print_thread_status();
116                 status_timer_arm();
117         }
118 }
119
120 /*
121  * Happens on thread runs with ctrl-c, ignore our own SIGQUIT
122  */
123 static void sig_quit(int sig)
124 {
125 }
126
127 static void sig_int(int sig)
128 {
129         if (threads) {
130                 printf("\nfio: terminating on signal %d\n", sig);
131                 fflush(stdout);
132                 terminate_threads(TERMINATE_ALL);
133         }
134 }
135
136 static void sig_ill(int fio_unused sig)
137 {
138         if (!threads)
139                 return;
140
141         log_err("fio: illegal instruction. your cpu does not support "
142                 "the sse4.2 instruction for crc32c\n");
143         terminate_threads(TERMINATE_ALL);
144         exit(4);
145 }
146
147 static void set_sig_handlers(void)
148 {
149         struct sigaction act;
150
151         memset(&act, 0, sizeof(act));
152         act.sa_handler = sig_alrm;
153         act.sa_flags = SA_RESTART;
154         sigaction(SIGALRM, &act, NULL);
155
156         memset(&act, 0, sizeof(act));
157         act.sa_handler = sig_int;
158         act.sa_flags = SA_RESTART;
159         sigaction(SIGINT, &act, NULL);
160
161         memset(&act, 0, sizeof(act));
162         act.sa_handler = sig_ill;
163         act.sa_flags = SA_RESTART;
164         sigaction(SIGILL, &act, NULL);
165
166         memset(&act, 0, sizeof(act));
167         act.sa_handler = sig_quit;
168         act.sa_flags = SA_RESTART;
169         sigaction(SIGQUIT, &act, NULL);
170 }
171
172 static inline int should_check_rate(struct thread_data *td)
173 {
174         /*
175          * No minimum rate set, always ok
176          */
177         if (!td->o.ratemin && !td->o.rate_iops_min)
178                 return 0;
179
180         return 1;
181 }
182
183 /*
184  * Check if we are above the minimum rate given.
185  */
186 static int check_min_rate(struct thread_data *td, struct timeval *now)
187 {
188         unsigned long long bytes = 0;
189         unsigned long iops = 0;
190         unsigned long spent;
191         unsigned long rate;
192
193         /*
194          * allow a 2 second settle period in the beginning
195          */
196         if (mtime_since(&td->start, now) < 2000)
197                 return 0;
198
199         if (td_read(td)) {
200                 iops += td->io_blocks[DDIR_READ];
201                 bytes += td->this_io_bytes[DDIR_READ];
202         }
203         if (td_write(td)) {
204                 iops += td->io_blocks[DDIR_WRITE];
205                 bytes += td->this_io_bytes[DDIR_WRITE];
206         }
207
208         /*
209          * if rate blocks is set, sample is running
210          */
211         if (td->rate_bytes || td->rate_blocks) {
212                 spent = mtime_since(&td->lastrate, now);
213                 if (spent < td->o.ratecycle)
214                         return 0;
215
216                 if (td->o.rate) {
217                         /*
218                          * check bandwidth specified rate
219                          */
220                         if (bytes < td->rate_bytes) {
221                                 log_err("%s: min rate %u not met\n", td->o.name,
222                                                                 td->o.ratemin);
223                                 return 1;
224                         } else {
225                                 rate = (bytes - td->rate_bytes) / spent;
226                                 if (rate < td->o.ratemin ||
227                                     bytes < td->rate_bytes) {
228                                         log_err("%s: min rate %u not met, got"
229                                                 " %luKiB/sec\n", td->o.name,
230                                                         td->o.ratemin, rate);
231                                         return 1;
232                                 }
233                         }
234                 } else {
235                         /*
236                          * checks iops specified rate
237                          */
238                         if (iops < td->o.rate_iops) {
239                                 log_err("%s: min iops rate %u not met\n",
240                                                 td->o.name, td->o.rate_iops);
241                                 return 1;
242                         } else {
243                                 rate = (iops - td->rate_blocks) / spent;
244                                 if (rate < td->o.rate_iops_min ||
245                                     iops < td->rate_blocks) {
246                                         log_err("%s: min iops rate %u not met,"
247                                                 " got %lu\n", td->o.name,
248                                                         td->o.rate_iops_min,
249                                                         rate);
250                                 }
251                         }
252                 }
253         }
254
255         td->rate_bytes = bytes;
256         td->rate_blocks = iops;
257         memcpy(&td->lastrate, now, sizeof(*now));
258         return 0;
259 }
260
261 static inline int runtime_exceeded(struct thread_data *td, struct timeval *t)
262 {
263         if (!td->o.timeout)
264                 return 0;
265         if (mtime_since(&td->epoch, t) >= td->o.timeout * 1000)
266                 return 1;
267
268         return 0;
269 }
270
271 /*
272  * When job exits, we can cancel the in-flight IO if we are using async
273  * io. Attempt to do so.
274  */
275 static void cleanup_pending_aio(struct thread_data *td)
276 {
277         struct flist_head *entry, *n;
278         struct io_u *io_u;
279         int r;
280
281         /*
282          * get immediately available events, if any
283          */
284         r = io_u_queued_complete(td, 0);
285         if (r < 0)
286                 return;
287
288         /*
289          * now cancel remaining active events
290          */
291         if (td->io_ops->cancel) {
292                 flist_for_each_safe(entry, n, &td->io_u_busylist) {
293                         io_u = flist_entry(entry, struct io_u, list);
294
295                         /*
296                          * if the io_u isn't in flight, then that generally
297                          * means someone leaked an io_u. complain but fix
298                          * it up, so we don't stall here.
299                          */
300                         if ((io_u->flags & IO_U_F_FLIGHT) == 0) {
301                                 log_err("fio: non-busy IO on busy list\n");
302                                 put_io_u(td, io_u);
303                         } else {
304                                 r = td->io_ops->cancel(td, io_u);
305                                 if (!r)
306                                         put_io_u(td, io_u);
307                         }
308                 }
309         }
310
311         if (td->cur_depth)
312                 r = io_u_queued_complete(td, td->cur_depth);
313 }
314
315 /*
316  * Helper to handle the final sync of a file. Works just like the normal
317  * io path, just does everything sync.
318  */
319 static int fio_io_sync(struct thread_data *td, struct fio_file *f)
320 {
321         struct io_u *io_u = __get_io_u(td);
322         int ret;
323
324         if (!io_u)
325                 return 1;
326
327         io_u->ddir = DDIR_SYNC;
328         io_u->file = f;
329
330         if (td_io_prep(td, io_u)) {
331                 put_io_u(td, io_u);
332                 return 1;
333         }
334
335 requeue:
336         ret = td_io_queue(td, io_u);
337         if (ret < 0) {
338                 td_verror(td, io_u->error, "td_io_queue");
339                 put_io_u(td, io_u);
340                 return 1;
341         } else if (ret == FIO_Q_QUEUED) {
342                 if (io_u_queued_complete(td, 1) < 0)
343                         return 1;
344         } else if (ret == FIO_Q_COMPLETED) {
345                 if (io_u->error) {
346                         td_verror(td, io_u->error, "td_io_queue");
347                         return 1;
348                 }
349
350                 if (io_u_sync_complete(td, io_u) < 0)
351                         return 1;
352         } else if (ret == FIO_Q_BUSY) {
353                 if (td_io_commit(td))
354                         return 1;
355                 goto requeue;
356         }
357
358         return 0;
359 }
360
361 static inline void update_tv_cache(struct thread_data *td)
362 {
363         if ((++td->tv_cache_nr & td->tv_cache_mask) == td->tv_cache_mask)
364                 fio_gettime(&td->tv_cache, NULL);
365 }
366
367 /*
368  * The main verify engine. Runs over the writes we previously submitted,
369  * reads the blocks back in, and checks the crc/md5 of the data.
370  */
371 static void do_verify(struct thread_data *td)
372 {
373         struct fio_file *f;
374         struct io_u *io_u;
375         int ret, min_events;
376         unsigned int i;
377
378         /*
379          * sync io first and invalidate cache, to make sure we really
380          * read from disk.
381          */
382         for_each_file(td, f, i) {
383                 if (!(f->flags & FIO_FILE_OPEN))
384                         continue;
385                 if (fio_io_sync(td, f))
386                         break;
387                 if (file_invalidate_cache(td, f))
388                         break;
389         }
390
391         if (td->error)
392                 return;
393
394         td_set_runstate(td, TD_VERIFYING);
395
396         io_u = NULL;
397         while (!td->terminate) {
398                 int ret2, full;
399
400                 io_u = __get_io_u(td);
401                 if (!io_u)
402                         break;
403
404                 update_tv_cache(td);
405
406                 if (runtime_exceeded(td, &td->tv_cache)) {
407                         put_io_u(td, io_u);
408                         td->terminate = 1;
409                         break;
410                 }
411
412                 if (get_next_verify(td, io_u)) {
413                         put_io_u(td, io_u);
414                         break;
415                 }
416
417                 if (td_io_prep(td, io_u)) {
418                         put_io_u(td, io_u);
419                         break;
420                 }
421
422                 io_u->end_io = verify_io_u;
423
424                 ret = td_io_queue(td, io_u);
425                 switch (ret) {
426                 case FIO_Q_COMPLETED:
427                         if (io_u->error)
428                                 ret = -io_u->error;
429                         else if (io_u->resid) {
430                                 int bytes = io_u->xfer_buflen - io_u->resid;
431                                 struct fio_file *f = io_u->file;
432
433                                 /*
434                                  * zero read, fail
435                                  */
436                                 if (!bytes) {
437                                         td_verror(td, EIO, "full resid");
438                                         put_io_u(td, io_u);
439                                         break;
440                                 }
441
442                                 io_u->xfer_buflen = io_u->resid;
443                                 io_u->xfer_buf += bytes;
444                                 io_u->offset += bytes;
445
446                                 td->ts.short_io_u[io_u->ddir]++;
447
448                                 if (io_u->offset == f->real_file_size)
449                                         goto sync_done;
450
451                                 requeue_io_u(td, &io_u);
452                         } else {
453 sync_done:
454                                 ret = io_u_sync_complete(td, io_u);
455                                 if (ret < 0)
456                                         break;
457                         }
458                         continue;
459                 case FIO_Q_QUEUED:
460                         break;
461                 case FIO_Q_BUSY:
462                         requeue_io_u(td, &io_u);
463                         ret2 = td_io_commit(td);
464                         if (ret2 < 0)
465                                 ret = ret2;
466                         break;
467                 default:
468                         assert(ret < 0);
469                         td_verror(td, -ret, "td_io_queue");
470                         break;
471                 }
472
473                 if (ret < 0 || td->error)
474                         break;
475
476                 /*
477                  * if we can queue more, do so. but check if there are
478                  * completed io_u's first.
479                  */
480                 full = queue_full(td) || ret == FIO_Q_BUSY;
481                 if (full || !td->o.iodepth_batch_complete) {
482                         min_events = td->o.iodepth_batch_complete;
483                         if (full && !min_events)
484                                 min_events = 1;
485
486                         do {
487                                 /*
488                                  * Reap required number of io units, if any,
489                                  * and do the verification on them through
490                                  * the callback handler
491                                  */
492                                 if (io_u_queued_complete(td, min_events) < 0) {
493                                         ret = -1;
494                                         break;
495                                 }
496                         } while (full && (td->cur_depth > td->o.iodepth_low));
497                 }
498                 if (ret < 0)
499                         break;
500         }
501
502         if (!td->error) {
503                 min_events = td->cur_depth;
504
505                 if (min_events)
506                         ret = io_u_queued_complete(td, min_events);
507         } else
508                 cleanup_pending_aio(td);
509
510         td_set_runstate(td, TD_RUNNING);
511 }
512
513 /*
514  * Main IO worker function. It retrieves io_u's to process and queues
515  * and reaps them, checking for rate and errors along the way.
516  */
517 static void do_io(struct thread_data *td)
518 {
519         unsigned long usec;
520         unsigned int i;
521         int ret = 0;
522
523         if (in_ramp_time(td))
524                 td_set_runstate(td, TD_RAMP);
525         else
526                 td_set_runstate(td, TD_RUNNING);
527
528         while ((td->this_io_bytes[0] + td->this_io_bytes[1]) < td->o.size) {
529                 struct timeval comp_time;
530                 long bytes_done = 0;
531                 int min_evts = 0;
532                 struct io_u *io_u;
533                 int ret2, full;
534
535                 if (td->terminate)
536                         break;
537
538                 io_u = get_io_u(td);
539                 if (!io_u)
540                         break;
541
542                 update_tv_cache(td);
543
544                 if (runtime_exceeded(td, &td->tv_cache)) {
545                         put_io_u(td, io_u);
546                         td->terminate = 1;
547                         break;
548                 }
549
550                 /*
551                  * Add verification end_io handler, if asked to verify
552                  * a previously written file.
553                  */
554                 if (td->o.verify != VERIFY_NONE && io_u->ddir == DDIR_READ) {
555                         io_u->end_io = verify_io_u;
556                         td_set_runstate(td, TD_VERIFYING);
557                 } else if (in_ramp_time(td))
558                         td_set_runstate(td, TD_RAMP);
559                 else
560                         td_set_runstate(td, TD_RUNNING);
561
562                 ret = td_io_queue(td, io_u);
563                 switch (ret) {
564                 case FIO_Q_COMPLETED:
565                         if (io_u->error)
566                                 ret = -io_u->error;
567                         else if (io_u->resid) {
568                                 int bytes = io_u->xfer_buflen - io_u->resid;
569                                 struct fio_file *f = io_u->file;
570
571                                 /*
572                                  * zero read, fail
573                                  */
574                                 if (!bytes) {
575                                         td_verror(td, EIO, "full resid");
576                                         put_io_u(td, io_u);
577                                         break;
578                                 }
579
580                                 io_u->xfer_buflen = io_u->resid;
581                                 io_u->xfer_buf += bytes;
582                                 io_u->offset += bytes;
583
584                                 td->ts.short_io_u[io_u->ddir]++;
585
586                                 if (io_u->offset == f->real_file_size)
587                                         goto sync_done;
588
589                                 requeue_io_u(td, &io_u);
590                         } else {
591 sync_done:
592                                 if (should_check_rate(td))
593                                         fio_gettime(&comp_time, NULL);
594
595                                 bytes_done = io_u_sync_complete(td, io_u);
596                                 if (bytes_done < 0)
597                                         ret = bytes_done;
598                         }
599                         break;
600                 case FIO_Q_QUEUED:
601                         /*
602                          * if the engine doesn't have a commit hook,
603                          * the io_u is really queued. if it does have such
604                          * a hook, it has to call io_u_queued() itself.
605                          */
606                         if (td->io_ops->commit == NULL)
607                                 io_u_queued(td, io_u);
608                         break;
609                 case FIO_Q_BUSY:
610                         requeue_io_u(td, &io_u);
611                         ret2 = td_io_commit(td);
612                         if (ret2 < 0)
613                                 ret = ret2;
614                         break;
615                 default:
616                         assert(ret < 0);
617                         put_io_u(td, io_u);
618                         break;
619                 }
620
621                 if (ret < 0 || td->error)
622                         break;
623
624                 /*
625                  * See if we need to complete some commands
626                  */
627                 full = queue_full(td) || ret == FIO_Q_BUSY;
628                 if (full || !td->o.iodepth_batch_complete) {
629                         min_evts = td->o.iodepth_batch_complete;
630                         if (full && !min_evts)
631                                 min_evts = 1;
632
633                         if (should_check_rate(td))
634                                 fio_gettime(&comp_time, NULL);
635
636                         do {
637                                 ret = io_u_queued_complete(td, min_evts);
638                                 if (ret <= 0)
639                                         break;
640
641                                 bytes_done += ret;
642                         } while (full && (td->cur_depth > td->o.iodepth_low));
643                 }
644
645                 if (ret < 0)
646                         break;
647                 if (!bytes_done)
648                         continue;
649
650                 /*
651                  * the rate is batched for now, it should work for batches
652                  * of completions except the very first one which may look
653                  * a little bursty
654                  */
655                 if (!in_ramp_time(td) && should_check_rate(td)) {
656                         usec = utime_since(&td->tv_cache, &comp_time);
657
658                         rate_throttle(td, usec, bytes_done);
659
660                         if (check_min_rate(td, &comp_time)) {
661                                 if (exitall_on_terminate)
662                                         terminate_threads(td->groupid);
663                                 td_verror(td, EIO, "check_min_rate");
664                                 break;
665                         }
666                 }
667
668                 if (td->o.thinktime) {
669                         unsigned long long b;
670
671                         b = td->io_blocks[0] + td->io_blocks[1];
672                         if (!(b % td->o.thinktime_blocks)) {
673                                 int left;
674
675                                 if (td->o.thinktime_spin)
676                                         usec_spin(td->o.thinktime_spin);
677
678                                 left = td->o.thinktime - td->o.thinktime_spin;
679                                 if (left)
680                                         usec_sleep(td, left);
681                         }
682                 }
683         }
684
685         if (td->o.fill_device && td->error == ENOSPC) {
686                 td->error = 0;
687                 td->terminate = 1;
688         }
689         if (!td->error) {
690                 struct fio_file *f;
691
692                 i = td->cur_depth;
693                 if (i)
694                         ret = io_u_queued_complete(td, i);
695
696                 if (should_fsync(td) && td->o.end_fsync) {
697                         td_set_runstate(td, TD_FSYNCING);
698
699                         for_each_file(td, f, i) {
700                                 if (!(f->flags & FIO_FILE_OPEN))
701                                         continue;
702                                 fio_io_sync(td, f);
703                         }
704                 }
705         } else
706                 cleanup_pending_aio(td);
707
708         /*
709          * stop job if we failed doing any IO
710          */
711         if ((td->this_io_bytes[0] + td->this_io_bytes[1]) == 0)
712                 td->done = 1;
713 }
714
715 static void cleanup_io_u(struct thread_data *td)
716 {
717         struct flist_head *entry, *n;
718         struct io_u *io_u;
719
720         flist_for_each_safe(entry, n, &td->io_u_freelist) {
721                 io_u = flist_entry(entry, struct io_u, list);
722
723                 flist_del(&io_u->list);
724                 free(io_u);
725         }
726
727         free_io_mem(td);
728 }
729
730 static int init_io_u(struct thread_data *td)
731 {
732         struct io_u *io_u;
733         unsigned int max_bs;
734         int i, max_units;
735         char *p;
736
737         max_units = td->o.iodepth;
738         max_bs = max(td->o.max_bs[DDIR_READ], td->o.max_bs[DDIR_WRITE]);
739         td->orig_buffer_size = (unsigned long long) max_bs
740                                         * (unsigned long long) max_units;
741
742         if (td->o.mem_type == MEM_SHMHUGE || td->o.mem_type == MEM_MMAPHUGE) {
743                 unsigned long bs;
744
745                 bs = td->orig_buffer_size + td->o.hugepage_size - 1;
746                 td->orig_buffer_size = bs & ~(td->o.hugepage_size - 1);
747         }
748
749         if (td->orig_buffer_size != (size_t) td->orig_buffer_size) {
750                 log_err("fio: IO memory too large. Reduce max_bs or iodepth\n");
751                 return 1;
752         }
753
754         if (allocate_io_mem(td))
755                 return 1;
756
757         if (td->o.odirect)
758                 p = ALIGN(td->orig_buffer);
759         else
760                 p = td->orig_buffer;
761
762         for (i = 0; i < max_units; i++) {
763                 if (td->terminate)
764                         return 1;
765                 io_u = malloc(sizeof(*io_u));
766                 memset(io_u, 0, sizeof(*io_u));
767                 INIT_FLIST_HEAD(&io_u->list);
768
769                 if (!(td->io_ops->flags & FIO_NOIO)) {
770                         io_u->buf = p + max_bs * i;
771
772                         if (td_write(td) && !td->o.refill_buffers)
773                                 io_u_fill_buffer(td, io_u, max_bs);
774                 }
775
776                 io_u->index = i;
777                 io_u->flags = IO_U_F_FREE;
778                 flist_add(&io_u->list, &td->io_u_freelist);
779         }
780
781         return 0;
782 }
783
784 static int switch_ioscheduler(struct thread_data *td)
785 {
786         char tmp[256], tmp2[128];
787         FILE *f;
788         int ret;
789
790         if (td->io_ops->flags & FIO_DISKLESSIO)
791                 return 0;
792
793         sprintf(tmp, "%s/queue/scheduler", td->sysfs_root);
794
795         f = fopen(tmp, "r+");
796         if (!f) {
797                 if (errno == ENOENT) {
798                         log_err("fio: os or kernel doesn't support IO scheduler"
799                                 " switching\n");
800                         return 0;
801                 }
802                 td_verror(td, errno, "fopen iosched");
803                 return 1;
804         }
805
806         /*
807          * Set io scheduler.
808          */
809         ret = fwrite(td->o.ioscheduler, strlen(td->o.ioscheduler), 1, f);
810         if (ferror(f) || ret != 1) {
811                 td_verror(td, errno, "fwrite");
812                 fclose(f);
813                 return 1;
814         }
815
816         rewind(f);
817
818         /*
819          * Read back and check that the selected scheduler is now the default.
820          */
821         ret = fread(tmp, 1, sizeof(tmp), f);
822         if (ferror(f) || ret < 0) {
823                 td_verror(td, errno, "fread");
824                 fclose(f);
825                 return 1;
826         }
827
828         sprintf(tmp2, "[%s]", td->o.ioscheduler);
829         if (!strstr(tmp, tmp2)) {
830                 log_err("fio: io scheduler %s not found\n", td->o.ioscheduler);
831                 td_verror(td, EINVAL, "iosched_switch");
832                 fclose(f);
833                 return 1;
834         }
835
836         fclose(f);
837         return 0;
838 }
839
840 static int keep_running(struct thread_data *td)
841 {
842         unsigned long long io_done;
843
844         if (td->done)
845                 return 0;
846         if (td->o.time_based)
847                 return 1;
848         if (td->o.loops) {
849                 td->o.loops--;
850                 return 1;
851         }
852
853         io_done = td->io_bytes[DDIR_READ] + td->io_bytes[DDIR_WRITE]
854                         + td->io_skip_bytes;
855         if (io_done < td->o.size)
856                 return 1;
857
858         return 0;
859 }
860
861 static void reset_io_counters(struct thread_data *td)
862 {
863         td->ts.stat_io_bytes[0] = td->ts.stat_io_bytes[1] = 0;
864         td->this_io_bytes[0] = td->this_io_bytes[1] = 0;
865         td->zone_bytes = 0;
866         td->rate_bytes = 0;
867         td->rate_blocks = 0;
868         td->rw_end_set[0] = td->rw_end_set[1] = 0;
869
870         td->last_was_sync = 0;
871
872         /*
873          * reset file done count if we are to start over
874          */
875         if (td->o.time_based || td->o.loops)
876                 td->nr_done_files = 0;
877 }
878
879 void reset_all_stats(struct thread_data *td)
880 {
881         struct timeval tv;
882         int i;
883
884         reset_io_counters(td);
885
886         for (i = 0; i < 2; i++) {
887                 td->io_bytes[i] = 0;
888                 td->io_blocks[i] = 0;
889                 td->io_issues[i] = 0;
890                 td->ts.total_io_u[i] = 0;
891         }
892         
893         fio_gettime(&tv, NULL);
894         memcpy(&td->epoch, &tv, sizeof(tv));
895         memcpy(&td->start, &tv, sizeof(tv));
896 }
897
898 static int clear_io_state(struct thread_data *td)
899 {
900         struct fio_file *f;
901         unsigned int i;
902         int ret;
903
904         reset_io_counters(td);
905
906         close_files(td);
907
908         ret = 0;
909         for_each_file(td, f, i) {
910                 f->flags &= ~FIO_FILE_DONE;
911                 ret = td_io_open_file(td, f);
912                 if (ret)
913                         break;
914         }
915
916         return ret;
917 }
918
919 /*
920  * Entry point for the thread based jobs. The process based jobs end up
921  * here as well, after a little setup.
922  */
923 static void *thread_main(void *data)
924 {
925         unsigned long long runtime[2], elapsed;
926         struct thread_data *td = data;
927         int clear_state;
928
929         if (!td->o.use_thread)
930                 setsid();
931
932         td->pid = getpid();
933
934         dprint(FD_PROCESS, "jobs pid=%d started\n", (int) td->pid);
935
936         INIT_FLIST_HEAD(&td->io_u_freelist);
937         INIT_FLIST_HEAD(&td->io_u_busylist);
938         INIT_FLIST_HEAD(&td->io_u_requeues);
939         INIT_FLIST_HEAD(&td->io_log_list);
940         INIT_FLIST_HEAD(&td->io_hist_list);
941         td->io_hist_tree = RB_ROOT;
942
943         td_set_runstate(td, TD_INITIALIZED);
944         fio_mutex_up(startup_mutex);
945         fio_mutex_down(td->mutex);
946
947         /*
948          * the ->mutex mutex is now no longer used, close it to avoid
949          * eating a file descriptor
950          */
951         fio_mutex_remove(td->mutex);
952
953         /*
954          * May alter parameters that init_io_u() will use, so we need to
955          * do this first.
956          */
957         if (init_iolog(td))
958                 goto err;
959
960         if (init_io_u(td))
961                 goto err;
962
963         if (td->o.cpumask_set && fio_setaffinity(td) == -1) {
964                 td_verror(td, errno, "cpu_set_affinity");
965                 goto err;
966         }
967
968         /*
969          * If we have a gettimeofday() thread, make sure we exclude that
970          * thread from this job
971          */
972         if (td->o.gtod_cpu) {
973                 fio_cpu_clear(&td->o.cpumask, td->o.gtod_cpu);
974                 if (fio_setaffinity(td) == -1) {
975                         td_verror(td, errno, "cpu_set_affinity");
976                         goto err;
977                 }
978         }
979
980         if (td->ioprio_set) {
981                 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, td->ioprio) == -1) {
982                         td_verror(td, errno, "ioprio_set");
983                         goto err;
984                 }
985         }
986
987         if (nice(td->o.nice) == -1) {
988                 td_verror(td, errno, "nice");
989                 goto err;
990         }
991
992         if (td->o.ioscheduler && switch_ioscheduler(td))
993                 goto err;
994
995         if (!td->o.create_serialize && setup_files(td))
996                 goto err;
997
998         if (td_io_init(td))
999                 goto err;
1000
1001         if (open_files(td))
1002                 goto err;
1003
1004         if (init_random_map(td))
1005                 goto err;
1006
1007         if (td->o.exec_prerun) {
1008                 if (system(td->o.exec_prerun) < 0)
1009                         goto err;
1010         }
1011
1012         fio_gettime(&td->epoch, NULL);
1013         getrusage(RUSAGE_SELF, &td->ts.ru_start);
1014
1015         runtime[0] = runtime[1] = 0;
1016         clear_state = 0;
1017         while (keep_running(td)) {
1018                 fio_gettime(&td->start, NULL);
1019                 memcpy(&td->ts.stat_sample_time, &td->start, sizeof(td->start));
1020                 memcpy(&td->tv_cache, &td->start, sizeof(td->start));
1021
1022                 if (td->o.ratemin)
1023                         memcpy(&td->lastrate, &td->ts.stat_sample_time,
1024                                                         sizeof(td->lastrate));
1025
1026                 if (clear_state && clear_io_state(td))
1027                         break;
1028
1029                 prune_io_piece_log(td);
1030
1031                 do_io(td);
1032
1033                 clear_state = 1;
1034
1035                 if (td_read(td) && td->io_bytes[DDIR_READ]) {
1036                         if (td->rw_end_set[DDIR_READ])
1037                                 elapsed = utime_since(&td->start,
1038                                                       &td->rw_end[DDIR_READ]);
1039                         else
1040                                 elapsed = utime_since_now(&td->start);
1041
1042                         runtime[DDIR_READ] += elapsed;
1043                 }
1044                 if (td_write(td) && td->io_bytes[DDIR_WRITE]) {
1045                         if (td->rw_end_set[DDIR_WRITE])
1046                                 elapsed = utime_since(&td->start,
1047                                                       &td->rw_end[DDIR_WRITE]);
1048                         else
1049                                 elapsed = utime_since_now(&td->start);
1050
1051                         runtime[DDIR_WRITE] += elapsed;
1052                 }
1053
1054                 if (td->error || td->terminate)
1055                         break;
1056
1057                 if (!td->o.do_verify ||
1058                     td->o.verify == VERIFY_NONE ||
1059                     (td->io_ops->flags & FIO_UNIDIR))
1060                         continue;
1061
1062                 if (clear_io_state(td))
1063                         break;
1064
1065                 fio_gettime(&td->start, NULL);
1066
1067                 do_verify(td);
1068
1069                 runtime[DDIR_READ] += utime_since_now(&td->start);
1070
1071                 if (td->error || td->terminate)
1072                         break;
1073         }
1074
1075         update_rusage_stat(td);
1076         td->ts.runtime[0] = (runtime[0] + 999) / 1000;
1077         td->ts.runtime[1] = (runtime[1] + 999) / 1000;
1078         td->ts.total_run_time = mtime_since_now(&td->epoch);
1079         td->ts.io_bytes[0] = td->io_bytes[0];
1080         td->ts.io_bytes[1] = td->io_bytes[1];
1081
1082         if (td->ts.bw_log) {
1083                 if (td->o.bw_log_file) {
1084                         finish_log_named(td, td->ts.bw_log,
1085                                                 td->o.bw_log_file, "bw");
1086                 } else
1087                         finish_log(td, td->ts.bw_log, "bw");
1088         }
1089         if (td->ts.slat_log) {
1090                 if (td->o.lat_log_file) {
1091                         finish_log_named(td, td->ts.slat_log,
1092                                                 td->o.lat_log_file, "clat");
1093                 } else
1094                         finish_log(td, td->ts.slat_log, "slat");
1095         }
1096         if (td->ts.clat_log) {
1097                 if (td->o.lat_log_file) {
1098                         finish_log_named(td, td->ts.clat_log,
1099                                                 td->o.lat_log_file, "clat");
1100                 } else
1101                         finish_log(td, td->ts.clat_log, "clat");
1102         }
1103         if (td->o.exec_postrun) {
1104                 if (system(td->o.exec_postrun) < 0)
1105                         log_err("fio: postrun %s failed\n", td->o.exec_postrun);
1106         }
1107
1108         if (exitall_on_terminate)
1109                 terminate_threads(td->groupid);
1110
1111 err:
1112         if (td->error)
1113                 printf("fio: pid=%d, err=%d/%s\n", (int) td->pid, td->error,
1114                                                         td->verror);
1115         close_and_free_files(td);
1116         close_ioengine(td);
1117         cleanup_io_u(td);
1118
1119         if (td->o.cpumask_set)
1120                 fio_cpuset_exit(td);
1121
1122         /*
1123          * do this very late, it will log file closing as well
1124          */
1125         if (td->o.write_iolog_file)
1126                 write_iolog_close(td);
1127
1128         options_mem_free(td);
1129         td_set_runstate(td, TD_EXITED);
1130         return (void *) (unsigned long) td->error;
1131 }
1132
1133 /*
1134  * We cannot pass the td data into a forked process, so attach the td and
1135  * pass it to the thread worker.
1136  */
1137 static int fork_main(int shmid, int offset)
1138 {
1139         struct thread_data *td;
1140         void *data, *ret;
1141
1142         data = shmat(shmid, NULL, 0);
1143         if (data == (void *) -1) {
1144                 int __err = errno;
1145
1146                 perror("shmat");
1147                 return __err;
1148         }
1149
1150         td = data + offset * sizeof(struct thread_data);
1151         ret = thread_main(td);
1152         shmdt(data);
1153         return (int) (unsigned long) ret;
1154 }
1155
1156 /*
1157  * Run over the job map and reap the threads that have exited, if any.
1158  */
1159 static void reap_threads(int *nr_running, int *t_rate, int *m_rate)
1160 {
1161         struct thread_data *td;
1162         int i, cputhreads, realthreads, pending, status, ret;
1163
1164         /*
1165          * reap exited threads (TD_EXITED -> TD_REAPED)
1166          */
1167         realthreads = pending = cputhreads = 0;
1168         for_each_td(td, i) {
1169                 int flags = 0;
1170
1171                 /*
1172                  * ->io_ops is NULL for a thread that has closed its
1173                  * io engine
1174                  */
1175                 if (td->io_ops && !strcmp(td->io_ops->name, "cpuio"))
1176                         cputhreads++;
1177                 else
1178                         realthreads++;
1179
1180                 if (!td->pid) {
1181                         pending++;
1182                         continue;
1183                 }
1184                 if (td->runstate == TD_REAPED)
1185                         continue;
1186                 if (td->o.use_thread) {
1187                         if (td->runstate == TD_EXITED) {
1188                                 td_set_runstate(td, TD_REAPED);
1189                                 goto reaped;
1190                         }
1191                         continue;
1192                 }
1193
1194                 flags = WNOHANG;
1195                 if (td->runstate == TD_EXITED)
1196                         flags = 0;
1197
1198                 /*
1199                  * check if someone quit or got killed in an unusual way
1200                  */
1201                 ret = waitpid(td->pid, &status, flags);
1202                 if (ret < 0) {
1203                         if (errno == ECHILD) {
1204                                 log_err("fio: pid=%d disappeared %d\n",
1205                                                 (int) td->pid, td->runstate);
1206                                 td_set_runstate(td, TD_REAPED);
1207                                 goto reaped;
1208                         }
1209                         perror("waitpid");
1210                 } else if (ret == td->pid) {
1211                         if (WIFSIGNALED(status)) {
1212                                 int sig = WTERMSIG(status);
1213
1214                                 if (sig != SIGQUIT)
1215                                         log_err("fio: pid=%d, got signal=%d\n",
1216                                                         (int) td->pid, sig);
1217                                 td_set_runstate(td, TD_REAPED);
1218                                 goto reaped;
1219                         }
1220                         if (WIFEXITED(status)) {
1221                                 if (WEXITSTATUS(status) && !td->error)
1222                                         td->error = WEXITSTATUS(status);
1223
1224                                 td_set_runstate(td, TD_REAPED);
1225                                 goto reaped;
1226                         }
1227                 }
1228
1229                 /*
1230                  * thread is not dead, continue
1231                  */
1232                 pending++;
1233                 continue;
1234 reaped:
1235                 (*nr_running)--;
1236                 (*m_rate) -= td->o.ratemin;
1237                 (*t_rate) -= td->o.rate;
1238                 if (!td->pid)
1239                         pending--;
1240
1241                 if (td->error)
1242                         exit_value++;
1243
1244                 done_secs += mtime_since_now(&td->epoch) / 1000;
1245         }
1246
1247         if (*nr_running == cputhreads && !pending && realthreads)
1248                 terminate_threads(TERMINATE_ALL);
1249 }
1250
1251 static void *gtod_thread_main(void *data)
1252 {
1253         fio_mutex_up(startup_mutex);
1254
1255         /*
1256          * As long as we have jobs around, update the clock. It would be nice
1257          * to have some way of NOT hammering that CPU with gettimeofday(),
1258          * but I'm not sure what to use outside of a simple CPU nop to relax
1259          * it - we don't want to lose precision.
1260          */
1261         while (threads) {
1262                 fio_gtod_update();
1263                 nop;
1264         }
1265
1266         return NULL;
1267 }
1268
1269 static int fio_start_gtod_thread(void)
1270 {
1271         if (pthread_create(&gtod_thread, NULL, gtod_thread_main, NULL)) {
1272                 perror("Can't create gtod thread");
1273                 return 1;
1274         }
1275         if (pthread_detach(gtod_thread) < 0) {
1276                 perror("Can't detatch gtod thread");
1277                 return 1;
1278         }
1279
1280         fio_mutex_down(startup_mutex);
1281         return 0;
1282 }
1283
1284 /*
1285  * Main function for kicking off and reaping jobs, as needed.
1286  */
1287 static void run_threads(void)
1288 {
1289         struct thread_data *td;
1290         unsigned long spent;
1291         int i, todo, nr_running, m_rate, t_rate, nr_started;
1292
1293         if (fio_pin_memory())
1294                 return;
1295
1296         if (fio_gtod_offload && fio_start_gtod_thread())
1297                 return;
1298
1299         if (!terse_output) {
1300                 printf("Starting ");
1301                 if (nr_thread)
1302                         printf("%d thread%s", nr_thread,
1303                                                 nr_thread > 1 ? "s" : "");
1304                 if (nr_process) {
1305                         if (nr_thread)
1306                                 printf(" and ");
1307                         printf("%d process%s", nr_process,
1308                                                 nr_process > 1 ? "es" : "");
1309                 }
1310                 printf("\n");
1311                 fflush(stdout);
1312         }
1313
1314         set_sig_handlers();
1315
1316         todo = thread_number;
1317         nr_running = 0;
1318         nr_started = 0;
1319         m_rate = t_rate = 0;
1320
1321         for_each_td(td, i) {
1322                 print_status_init(td->thread_number - 1);
1323
1324                 if (!td->o.create_serialize) {
1325                         init_disk_util(td);
1326                         continue;
1327                 }
1328
1329                 /*
1330                  * do file setup here so it happens sequentially,
1331                  * we don't want X number of threads getting their
1332                  * client data interspersed on disk
1333                  */
1334                 if (setup_files(td)) {
1335                         exit_value++;
1336                         if (td->error)
1337                                 log_err("fio: pid=%d, err=%d/%s\n",
1338                                         (int) td->pid, td->error, td->verror);
1339                         td_set_runstate(td, TD_REAPED);
1340                         todo--;
1341                 } else {
1342                         struct fio_file *f;
1343                         unsigned int i;
1344
1345                         /*
1346                          * for sharing to work, each job must always open
1347                          * its own files. so close them, if we opened them
1348                          * for creation
1349                          */
1350                         for_each_file(td, f, i)
1351                                 td_io_close_file(td, f);
1352                 }
1353
1354                 init_disk_util(td);
1355         }
1356
1357         set_genesis_time();
1358
1359         while (todo) {
1360                 struct thread_data *map[MAX_JOBS];
1361                 struct timeval this_start;
1362                 int this_jobs = 0, left;
1363
1364                 /*
1365                  * create threads (TD_NOT_CREATED -> TD_CREATED)
1366                  */
1367                 for_each_td(td, i) {
1368                         if (td->runstate != TD_NOT_CREATED)
1369                                 continue;
1370
1371                         /*
1372                          * never got a chance to start, killed by other
1373                          * thread for some reason
1374                          */
1375                         if (td->terminate) {
1376                                 todo--;
1377                                 continue;
1378                         }
1379
1380                         if (td->o.start_delay) {
1381                                 spent = mtime_since_genesis();
1382
1383                                 if (td->o.start_delay * 1000 > spent)
1384                                         continue;
1385                         }
1386
1387                         if (td->o.stonewall && (nr_started || nr_running)) {
1388                                 dprint(FD_PROCESS, "%s: stonewall wait\n",
1389                                                         td->o.name);
1390                                 break;
1391                         }
1392
1393                         /*
1394                          * Set state to created. Thread will transition
1395                          * to TD_INITIALIZED when it's done setting up.
1396                          */
1397                         td_set_runstate(td, TD_CREATED);
1398                         map[this_jobs++] = td;
1399                         nr_started++;
1400
1401                         if (td->o.use_thread) {
1402                                 dprint(FD_PROCESS, "will pthread_create\n");
1403                                 if (pthread_create(&td->thread, NULL,
1404                                                    thread_main, td)) {
1405                                         perror("pthread_create");
1406                                         nr_started--;
1407                                         break;
1408                                 }
1409                                 if (pthread_detach(td->thread) < 0)
1410                                         perror("pthread_detach");
1411                         } else {
1412                                 pid_t pid;
1413                                 dprint(FD_PROCESS, "will fork\n");
1414                                 pid = fork();
1415                                 if (!pid) {
1416                                         int ret = fork_main(shm_id, i);
1417
1418                                         _exit(ret);
1419                                 } else if (i == fio_debug_jobno)
1420                                         *fio_debug_jobp = pid;
1421                         }
1422                         fio_mutex_down(startup_mutex);
1423                 }
1424
1425                 /*
1426                  * Wait for the started threads to transition to
1427                  * TD_INITIALIZED.
1428                  */
1429                 fio_gettime(&this_start, NULL);
1430                 left = this_jobs;
1431                 while (left && !fio_abort) {
1432                         if (mtime_since_now(&this_start) > JOB_START_TIMEOUT)
1433                                 break;
1434
1435                         usleep(100000);
1436
1437                         for (i = 0; i < this_jobs; i++) {
1438                                 td = map[i];
1439                                 if (!td)
1440                                         continue;
1441                                 if (td->runstate == TD_INITIALIZED) {
1442                                         map[i] = NULL;
1443                                         left--;
1444                                 } else if (td->runstate >= TD_EXITED) {
1445                                         map[i] = NULL;
1446                                         left--;
1447                                         todo--;
1448                                         nr_running++; /* work-around... */
1449                                 }
1450                         }
1451                 }
1452
1453                 if (left) {
1454                         log_err("fio: %d jobs failed to start\n", left);
1455                         for (i = 0; i < this_jobs; i++) {
1456                                 td = map[i];
1457                                 if (!td)
1458                                         continue;
1459                                 kill(td->pid, SIGTERM);
1460                         }
1461                         break;
1462                 }
1463
1464                 /*
1465                  * start created threads (TD_INITIALIZED -> TD_RUNNING).
1466                  */
1467                 for_each_td(td, i) {
1468                         if (td->runstate != TD_INITIALIZED)
1469                                 continue;
1470
1471                         if (in_ramp_time(td))
1472                                 td_set_runstate(td, TD_RAMP);
1473                         else
1474                                 td_set_runstate(td, TD_RUNNING);
1475                         nr_running++;
1476                         nr_started--;
1477                         m_rate += td->o.ratemin;
1478                         t_rate += td->o.rate;
1479                         todo--;
1480                         fio_mutex_up(td->mutex);
1481                 }
1482
1483                 reap_threads(&nr_running, &t_rate, &m_rate);
1484
1485                 if (todo)
1486                         usleep(100000);
1487         }
1488
1489         while (nr_running) {
1490                 reap_threads(&nr_running, &t_rate, &m_rate);
1491                 usleep(10000);
1492         }
1493
1494         update_io_ticks();
1495         fio_unpin_memory();
1496 }
1497
1498 int main(int argc, char *argv[])
1499 {
1500         long ps;
1501
1502         sinit();
1503
1504         /*
1505          * We need locale for number printing, if it isn't set then just
1506          * go with the US format.
1507          */
1508         if (!getenv("LC_NUMERIC"))
1509                 setlocale(LC_NUMERIC, "en_US");
1510
1511         if (parse_options(argc, argv))
1512                 return 1;
1513
1514         if (!thread_number)
1515                 return 0;
1516
1517         ps = sysconf(_SC_PAGESIZE);
1518         if (ps < 0) {
1519                 log_err("Failed to get page size\n");
1520                 return 1;
1521         }
1522
1523         page_size = ps;
1524         page_mask = ps - 1;
1525
1526         if (write_bw_log) {
1527                 setup_log(&agg_io_log[DDIR_READ]);
1528                 setup_log(&agg_io_log[DDIR_WRITE]);
1529         }
1530
1531         startup_mutex = fio_mutex_init(0);
1532
1533         set_genesis_time();
1534
1535         status_timer_arm();
1536
1537         run_threads();
1538
1539         if (!fio_abort) {
1540                 show_run_stats();
1541                 if (write_bw_log) {
1542                         __finish_log(agg_io_log[DDIR_READ], "agg-read_bw.log");
1543                         __finish_log(agg_io_log[DDIR_WRITE],
1544                                         "agg-write_bw.log");
1545                 }
1546         }
1547
1548         fio_mutex_remove(startup_mutex);
1549         return exit_value;
1550 }