Add verify trim support
[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 #include "verify.h"
41 #include "diskutil.h"
42 #include "cgroup.h"
43 #include "profile.h"
44 #include "lib/rand.h"
45
46 unsigned long page_mask;
47 unsigned long page_size;
48
49 #define PAGE_ALIGN(buf) \
50         (char *) (((unsigned long) (buf) + page_mask) & ~page_mask)
51
52 int groupid = 0;
53 int thread_number = 0;
54 int nr_process = 0;
55 int nr_thread = 0;
56 int shm_id = 0;
57 int temp_stall_ts;
58 unsigned long done_secs = 0;
59
60 static struct fio_mutex *startup_mutex;
61 static struct fio_mutex *writeout_mutex;
62 static volatile int fio_abort;
63 static int exit_value;
64 static struct itimerval itimer;
65 static pthread_t gtod_thread;
66 static struct flist_head *cgroup_list;
67 static char *cgroup_mnt;
68
69 struct io_log *agg_io_log[2];
70
71 #define TERMINATE_ALL           (-1)
72 #define JOB_START_TIMEOUT       (5 * 1000)
73
74 void td_set_runstate(struct thread_data *td, int runstate)
75 {
76         if (td->runstate == runstate)
77                 return;
78
79         dprint(FD_PROCESS, "pid=%d: runstate %d -> %d\n", (int) td->pid,
80                                                 td->runstate, runstate);
81         td->runstate = runstate;
82 }
83
84 static void terminate_threads(int group_id)
85 {
86         struct thread_data *td;
87         int i;
88
89         dprint(FD_PROCESS, "terminate group_id=%d\n", group_id);
90
91         for_each_td(td, i) {
92                 if (group_id == TERMINATE_ALL || groupid == td->groupid) {
93                         dprint(FD_PROCESS, "setting terminate on %s/%d\n",
94                                                 td->o.name, (int) td->pid);
95                         td->terminate = 1;
96                         td->o.start_delay = 0;
97
98                         /*
99                          * if the thread is running, just let it exit
100                          */
101                         if (td->runstate < TD_RUNNING)
102                                 kill(td->pid, SIGQUIT);
103                         else {
104                                 struct ioengine_ops *ops = td->io_ops;
105
106                                 if (ops && (ops->flags & FIO_SIGQUIT))
107                                         kill(td->pid, SIGQUIT);
108                         }
109                 }
110         }
111 }
112
113 static void status_timer_arm(void)
114 {
115         itimer.it_value.tv_sec = 0;
116         itimer.it_value.tv_usec = DISK_UTIL_MSEC * 1000;
117         setitimer(ITIMER_REAL, &itimer, NULL);
118 }
119
120 static void sig_alrm(int fio_unused sig)
121 {
122         if (threads) {
123                 update_io_ticks();
124                 print_thread_status();
125                 status_timer_arm();
126         }
127 }
128
129 /*
130  * Happens on thread runs with ctrl-c, ignore our own SIGQUIT
131  */
132 static void sig_quit(int sig)
133 {
134 }
135
136 static void sig_int(int sig)
137 {
138         if (threads) {
139                 log_info("\nfio: terminating on signal %d\n", sig);
140                 fflush(stdout);
141                 terminate_threads(TERMINATE_ALL);
142         }
143 }
144
145 static void set_sig_handlers(void)
146 {
147         struct sigaction act;
148
149         memset(&act, 0, sizeof(act));
150         act.sa_handler = sig_alrm;
151         act.sa_flags = SA_RESTART;
152         sigaction(SIGALRM, &act, NULL);
153
154         memset(&act, 0, sizeof(act));
155         act.sa_handler = sig_int;
156         act.sa_flags = SA_RESTART;
157         sigaction(SIGINT, &act, NULL);
158
159         memset(&act, 0, sizeof(act));
160         act.sa_handler = sig_quit;
161         act.sa_flags = SA_RESTART;
162         sigaction(SIGQUIT, &act, NULL);
163 }
164
165 /*
166  * Check if we are above the minimum rate given.
167  */
168 static int __check_min_rate(struct thread_data *td, struct timeval *now,
169                             enum td_ddir ddir)
170 {
171         unsigned long long bytes = 0;
172         unsigned long iops = 0;
173         unsigned long spent;
174         unsigned long rate;
175         unsigned int ratemin = 0;
176         unsigned int rate_iops = 0;
177         unsigned int rate_iops_min = 0;
178
179         assert(ddir_rw(ddir));
180
181         if (!td->o.ratemin[ddir] && !td->o.rate_iops_min[ddir])
182                 return 0;
183
184         /*
185          * allow a 2 second settle period in the beginning
186          */
187         if (mtime_since(&td->start, now) < 2000)
188                 return 0;
189
190         iops += td->io_blocks[ddir];
191         bytes += td->this_io_bytes[ddir];
192         ratemin += td->o.ratemin[ddir];
193         rate_iops += td->o.rate_iops[ddir];
194         rate_iops_min += td->o.rate_iops_min[ddir];
195
196         /*
197          * if rate blocks is set, sample is running
198          */
199         if (td->rate_bytes[ddir] || td->rate_blocks[ddir]) {
200                 spent = mtime_since(&td->lastrate[ddir], now);
201                 if (spent < td->o.ratecycle)
202                         return 0;
203
204                 if (td->o.rate[ddir]) {
205                         /*
206                          * check bandwidth specified rate
207                          */
208                         if (bytes < td->rate_bytes[ddir]) {
209                                 log_err("%s: min rate %u not met\n", td->o.name,
210                                                                 ratemin);
211                                 return 1;
212                         } else {
213                                 rate = ((bytes - td->rate_bytes[ddir]) * 1000) / spent;
214                                 if (rate < ratemin ||
215                                     bytes < td->rate_bytes[ddir]) {
216                                         log_err("%s: min rate %u not met, got"
217                                                 " %luKB/sec\n", td->o.name,
218                                                         ratemin, rate);
219                                         return 1;
220                                 }
221                         }
222                 } else {
223                         /*
224                          * checks iops specified rate
225                          */
226                         if (iops < rate_iops) {
227                                 log_err("%s: min iops rate %u not met\n",
228                                                 td->o.name, rate_iops);
229                                 return 1;
230                         } else {
231                                 rate = ((iops - td->rate_blocks[ddir]) * 1000) / spent;
232                                 if (rate < rate_iops_min ||
233                                     iops < td->rate_blocks[ddir]) {
234                                         log_err("%s: min iops rate %u not met,"
235                                                 " got %lu\n", td->o.name,
236                                                         rate_iops_min, rate);
237                                 }
238                         }
239                 }
240         }
241
242         td->rate_bytes[ddir] = bytes;
243         td->rate_blocks[ddir] = iops;
244         memcpy(&td->lastrate[ddir], now, sizeof(*now));
245         return 0;
246 }
247
248 static int check_min_rate(struct thread_data *td, struct timeval *now,
249                           unsigned long *bytes_done)
250 {
251         int ret = 0;
252
253         if (bytes_done[0])
254                 ret |= __check_min_rate(td, now, 0);
255         if (bytes_done[1])
256                 ret |= __check_min_rate(td, now, 1);
257
258         return ret;
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, NULL);
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, NULL);
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, NULL) < 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, NULL) < 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 static int break_on_this_error(struct thread_data *td, int *retptr)
368 {
369         int ret = *retptr;
370
371         if (ret < 0 || td->error) {
372                 int err;
373
374                 if (!td->o.continue_on_error)
375                         return 1;
376
377                 if (ret < 0)
378                         err = -ret;
379                 else
380                         err = td->error;
381
382                 if (td_non_fatal_error(err)) {
383                         /*
384                          * Continue with the I/Os in case of
385                          * a non fatal error.
386                          */
387                         update_error_count(td, err);
388                         td_clear_error(td);
389                         *retptr = 0;
390                         return 0;
391                 } else if (td->o.fill_device && err == ENOSPC) {
392                         /*
393                          * We expect to hit this error if
394                          * fill_device option is set.
395                          */
396                         td_clear_error(td);
397                         td->terminate = 1;
398                         return 1;
399                 } else {
400                         /*
401                          * Stop the I/O in case of a fatal
402                          * error.
403                          */
404                         update_error_count(td, err);
405                         return 1;
406                 }
407         }
408
409         return 0;
410 }
411
412 /*
413  * The main verify engine. Runs over the writes we previously submitted,
414  * reads the blocks back in, and checks the crc/md5 of the data.
415  */
416 static void do_verify(struct thread_data *td)
417 {
418         struct fio_file *f;
419         struct io_u *io_u;
420         int ret, min_events;
421         unsigned int i;
422
423         dprint(FD_VERIFY, "starting loop\n");
424
425         /*
426          * sync io first and invalidate cache, to make sure we really
427          * read from disk.
428          */
429         for_each_file(td, f, i) {
430                 if (!fio_file_open(f))
431                         continue;
432                 if (fio_io_sync(td, f))
433                         break;
434                 if (file_invalidate_cache(td, f))
435                         break;
436         }
437
438         if (td->error)
439                 return;
440
441         td_set_runstate(td, TD_VERIFYING);
442
443         io_u = NULL;
444         while (!td->terminate) {
445                 int ret2, full;
446
447                 update_tv_cache(td);
448
449                 if (runtime_exceeded(td, &td->tv_cache)) {
450                         td->terminate = 1;
451                         break;
452                 }
453
454                 io_u = __get_io_u(td);
455                 if (!io_u)
456                         break;
457
458                 if (get_next_verify(td, io_u)) {
459                         put_io_u(td, io_u);
460                         break;
461                 }
462
463                 if (td_io_prep(td, io_u)) {
464                         put_io_u(td, io_u);
465                         break;
466                 }
467
468                 if (td->o.verify_async)
469                         io_u->end_io = verify_io_u_async;
470                 else
471                         io_u->end_io = verify_io_u;
472
473                 ret = td_io_queue(td, io_u);
474                 switch (ret) {
475                 case FIO_Q_COMPLETED:
476                         if (io_u->error) {
477                                 ret = -io_u->error;
478                                 clear_io_u(td, io_u);
479                         } else if (io_u->resid) {
480                                 int bytes = io_u->xfer_buflen - io_u->resid;
481                                 struct fio_file *f = io_u->file;
482
483                                 /*
484                                  * zero read, fail
485                                  */
486                                 if (!bytes) {
487                                         td_verror(td, EIO, "full resid");
488                                         put_io_u(td, io_u);
489                                         break;
490                                 }
491
492                                 io_u->xfer_buflen = io_u->resid;
493                                 io_u->xfer_buf += bytes;
494                                 io_u->offset += bytes;
495
496                                 if (ddir_rw(io_u->ddir))
497                                         td->ts.short_io_u[io_u->ddir]++;
498
499                                 if (io_u->offset == f->real_file_size)
500                                         goto sync_done;
501
502                                 requeue_io_u(td, &io_u);
503                         } else {
504 sync_done:
505                                 ret = io_u_sync_complete(td, io_u, NULL);
506                                 if (ret < 0)
507                                         break;
508                         }
509                         continue;
510                 case FIO_Q_QUEUED:
511                         break;
512                 case FIO_Q_BUSY:
513                         requeue_io_u(td, &io_u);
514                         ret2 = td_io_commit(td);
515                         if (ret2 < 0)
516                                 ret = ret2;
517                         break;
518                 default:
519                         assert(ret < 0);
520                         td_verror(td, -ret, "td_io_queue");
521                         break;
522                 }
523
524                 if (break_on_this_error(td, &ret))
525                         break;
526
527                 /*
528                  * if we can queue more, do so. but check if there are
529                  * completed io_u's first.
530                  */
531                 full = queue_full(td) || ret == FIO_Q_BUSY;
532                 if (full || !td->o.iodepth_batch_complete) {
533                         min_events = min(td->o.iodepth_batch_complete,
534                                          td->cur_depth);
535                         if (full && !min_events)
536                                 min_events = 1;
537
538                         do {
539                                 /*
540                                  * Reap required number of io units, if any,
541                                  * and do the verification on them through
542                                  * the callback handler
543                                  */
544                                 if (io_u_queued_complete(td, min_events, NULL) < 0) {
545                                         ret = -1;
546                                         break;
547                                 }
548                         } while (full && (td->cur_depth > td->o.iodepth_low));
549                 }
550                 if (ret < 0)
551                         break;
552         }
553
554         if (!td->error) {
555                 min_events = td->cur_depth;
556
557                 if (min_events)
558                         ret = io_u_queued_complete(td, min_events, NULL);
559         } else
560                 cleanup_pending_aio(td);
561
562         td_set_runstate(td, TD_RUNNING);
563
564         dprint(FD_VERIFY, "exiting loop\n");
565 }
566
567 /*
568  * Main IO worker function. It retrieves io_u's to process and queues
569  * and reaps them, checking for rate and errors along the way.
570  */
571 static void do_io(struct thread_data *td)
572 {
573         unsigned int i;
574         int ret = 0;
575
576         if (in_ramp_time(td))
577                 td_set_runstate(td, TD_RAMP);
578         else
579                 td_set_runstate(td, TD_RUNNING);
580
581         while ( (td->o.read_iolog_file && !flist_empty(&td->io_log_list)) ||
582                 ((td->this_io_bytes[0] + td->this_io_bytes[1]) < td->o.size) ) {
583                 struct timeval comp_time;
584                 unsigned long bytes_done[2] = { 0, 0 };
585                 int min_evts = 0;
586                 struct io_u *io_u;
587                 int ret2, full;
588
589                 if (td->terminate)
590                         break;
591
592                 update_tv_cache(td);
593
594                 if (runtime_exceeded(td, &td->tv_cache)) {
595                         td->terminate = 1;
596                         break;
597                 }
598
599                 io_u = get_io_u(td);
600                 if (!io_u)
601                         break;
602
603                 /*
604                  * Add verification end_io handler, if asked to verify
605                  * a previously written file.
606                  */
607                 if (td->o.verify != VERIFY_NONE && io_u->ddir == DDIR_READ &&
608                     !td_rw(td)) {
609                         if (td->o.verify_async)
610                                 io_u->end_io = verify_io_u_async;
611                         else
612                                 io_u->end_io = verify_io_u;
613                         td_set_runstate(td, TD_VERIFYING);
614                 } else if (in_ramp_time(td))
615                         td_set_runstate(td, TD_RAMP);
616                 else
617                         td_set_runstate(td, TD_RUNNING);
618
619                 ret = td_io_queue(td, io_u);
620                 switch (ret) {
621                 case FIO_Q_COMPLETED:
622                         if (io_u->error) {
623                                 ret = -io_u->error;
624                                 clear_io_u(td, io_u);
625                         } else if (io_u->resid) {
626                                 int bytes = io_u->xfer_buflen - io_u->resid;
627                                 struct fio_file *f = io_u->file;
628
629                                 /*
630                                  * zero read, fail
631                                  */
632                                 if (!bytes) {
633                                         td_verror(td, EIO, "full resid");
634                                         put_io_u(td, io_u);
635                                         break;
636                                 }
637
638                                 io_u->xfer_buflen = io_u->resid;
639                                 io_u->xfer_buf += bytes;
640                                 io_u->offset += bytes;
641
642                                 if (ddir_rw(io_u->ddir))
643                                         td->ts.short_io_u[io_u->ddir]++;
644
645                                 if (io_u->offset == f->real_file_size)
646                                         goto sync_done;
647
648                                 requeue_io_u(td, &io_u);
649                         } else {
650 sync_done:
651                                 if (__should_check_rate(td, 0) ||
652                                     __should_check_rate(td, 1))
653                                         fio_gettime(&comp_time, NULL);
654
655                                 ret = io_u_sync_complete(td, io_u, bytes_done);
656                                 if (ret < 0)
657                                         break;
658                         }
659                         break;
660                 case FIO_Q_QUEUED:
661                         /*
662                          * if the engine doesn't have a commit hook,
663                          * the io_u is really queued. if it does have such
664                          * a hook, it has to call io_u_queued() itself.
665                          */
666                         if (td->io_ops->commit == NULL)
667                                 io_u_queued(td, io_u);
668                         break;
669                 case FIO_Q_BUSY:
670                         requeue_io_u(td, &io_u);
671                         ret2 = td_io_commit(td);
672                         if (ret2 < 0)
673                                 ret = ret2;
674                         break;
675                 default:
676                         assert(ret < 0);
677                         put_io_u(td, io_u);
678                         break;
679                 }
680
681                 if (break_on_this_error(td, &ret))
682                         break;
683
684                 /*
685                  * See if we need to complete some commands
686                  */
687                 full = queue_full(td) || ret == FIO_Q_BUSY;
688                 if (full || !td->o.iodepth_batch_complete) {
689                         min_evts = min(td->o.iodepth_batch_complete,
690                                         td->cur_depth);
691                         if (full && !min_evts)
692                                 min_evts = 1;
693
694                         if (__should_check_rate(td, 0) ||
695                             __should_check_rate(td, 1))
696                                 fio_gettime(&comp_time, NULL);
697
698                         do {
699                                 ret = io_u_queued_complete(td, min_evts, bytes_done);
700                                 if (ret < 0)
701                                         break;
702
703                         } while (full && (td->cur_depth > td->o.iodepth_low));
704                 }
705
706                 if (ret < 0)
707                         break;
708                 if (!(bytes_done[0] + bytes_done[1]))
709                         continue;
710
711                 if (!in_ramp_time(td) && should_check_rate(td, bytes_done)) {
712                         if (check_min_rate(td, &comp_time, bytes_done)) {
713                                 if (exitall_on_terminate)
714                                         terminate_threads(td->groupid);
715                                 td_verror(td, EIO, "check_min_rate");
716                                 break;
717                         }
718                 }
719
720                 if (td->o.thinktime) {
721                         unsigned long long b;
722
723                         b = td->io_blocks[0] + td->io_blocks[1];
724                         if (!(b % td->o.thinktime_blocks)) {
725                                 int left;
726
727                                 if (td->o.thinktime_spin)
728                                         usec_spin(td->o.thinktime_spin);
729
730                                 left = td->o.thinktime - td->o.thinktime_spin;
731                                 if (left)
732                                         usec_sleep(td, left);
733                         }
734                 }
735         }
736
737         if (td->o.fill_device && td->error == ENOSPC) {
738                 td->error = 0;
739                 td->terminate = 1;
740         }
741         if (!td->error) {
742                 struct fio_file *f;
743
744                 i = td->cur_depth;
745                 if (i)
746                         ret = io_u_queued_complete(td, i, NULL);
747
748                 if (should_fsync(td) && td->o.end_fsync) {
749                         td_set_runstate(td, TD_FSYNCING);
750
751                         for_each_file(td, f, i) {
752                                 if (!fio_file_open(f))
753                                         continue;
754                                 fio_io_sync(td, f);
755                         }
756                 }
757         } else
758                 cleanup_pending_aio(td);
759
760         /*
761          * stop job if we failed doing any IO
762          */
763         if ((td->this_io_bytes[0] + td->this_io_bytes[1]) == 0)
764                 td->done = 1;
765 }
766
767 static void cleanup_io_u(struct thread_data *td)
768 {
769         struct flist_head *entry, *n;
770         struct io_u *io_u;
771
772         flist_for_each_safe(entry, n, &td->io_u_freelist) {
773                 io_u = flist_entry(entry, struct io_u, list);
774
775                 flist_del(&io_u->list);
776                 free(io_u);
777         }
778
779         free_io_mem(td);
780 }
781
782 static int init_io_u(struct thread_data *td)
783 {
784         struct io_u *io_u;
785         unsigned int max_bs;
786         int cl_align, i, max_units;
787         char *p;
788
789         max_units = td->o.iodepth;
790         max_bs = max(td->o.max_bs[DDIR_READ], td->o.max_bs[DDIR_WRITE]);
791         td->orig_buffer_size = (unsigned long long) max_bs
792                                         * (unsigned long long) max_units;
793
794         if (td->o.mem_type == MEM_SHMHUGE || td->o.mem_type == MEM_MMAPHUGE) {
795                 unsigned long bs;
796
797                 bs = td->orig_buffer_size + td->o.hugepage_size - 1;
798                 td->orig_buffer_size = bs & ~(td->o.hugepage_size - 1);
799         }
800
801         if (td->orig_buffer_size != (size_t) td->orig_buffer_size) {
802                 log_err("fio: IO memory too large. Reduce max_bs or iodepth\n");
803                 return 1;
804         }
805
806         if (allocate_io_mem(td))
807                 return 1;
808
809         if (td->o.odirect || td->o.mem_align)
810                 p = PAGE_ALIGN(td->orig_buffer) + td->o.mem_align;
811         else
812                 p = td->orig_buffer;
813
814         cl_align = os_cache_line_size();
815
816         for (i = 0; i < max_units; i++) {
817                 void *ptr;
818
819                 if (td->terminate)
820                         return 1;
821
822                 if (posix_memalign(&ptr, cl_align, sizeof(*io_u))) {
823                         log_err("fio: posix_memalign=%s\n", strerror(errno));
824                         break;
825                 }
826
827                 io_u = ptr;
828                 memset(io_u, 0, sizeof(*io_u));
829                 INIT_FLIST_HEAD(&io_u->list);
830                 dprint(FD_MEM, "io_u alloc %p, index %u\n", io_u, i);
831
832                 if (!(td->io_ops->flags & FIO_NOIO)) {
833                         io_u->buf = p + max_bs * i;
834                         dprint(FD_MEM, "io_u %p, mem %p\n", io_u, io_u->buf);
835
836                         if (td_write(td) && !td->o.refill_buffers)
837                                 io_u_fill_buffer(td, io_u, max_bs);
838                         else if (td_write(td) && td->o.verify_pattern_bytes) {
839                                 /*
840                                  * Fill the buffer with the pattern if we are
841                                  * going to be doing writes.
842                                  */
843                                 fill_pattern(td, io_u->buf, max_bs, io_u);
844                         }
845                 }
846
847                 io_u->index = i;
848                 io_u->flags = IO_U_F_FREE;
849                 flist_add(&io_u->list, &td->io_u_freelist);
850         }
851
852         return 0;
853 }
854
855 static int switch_ioscheduler(struct thread_data *td)
856 {
857         char tmp[256], tmp2[128];
858         FILE *f;
859         int ret;
860
861         if (td->io_ops->flags & FIO_DISKLESSIO)
862                 return 0;
863
864         sprintf(tmp, "%s/queue/scheduler", td->sysfs_root);
865
866         f = fopen(tmp, "r+");
867         if (!f) {
868                 if (errno == ENOENT) {
869                         log_err("fio: os or kernel doesn't support IO scheduler"
870                                 " switching\n");
871                         return 0;
872                 }
873                 td_verror(td, errno, "fopen iosched");
874                 return 1;
875         }
876
877         /*
878          * Set io scheduler.
879          */
880         ret = fwrite(td->o.ioscheduler, strlen(td->o.ioscheduler), 1, f);
881         if (ferror(f) || ret != 1) {
882                 td_verror(td, errno, "fwrite");
883                 fclose(f);
884                 return 1;
885         }
886
887         rewind(f);
888
889         /*
890          * Read back and check that the selected scheduler is now the default.
891          */
892         ret = fread(tmp, 1, sizeof(tmp), f);
893         if (ferror(f) || ret < 0) {
894                 td_verror(td, errno, "fread");
895                 fclose(f);
896                 return 1;
897         }
898
899         sprintf(tmp2, "[%s]", td->o.ioscheduler);
900         if (!strstr(tmp, tmp2)) {
901                 log_err("fio: io scheduler %s not found\n", td->o.ioscheduler);
902                 td_verror(td, EINVAL, "iosched_switch");
903                 fclose(f);
904                 return 1;
905         }
906
907         fclose(f);
908         return 0;
909 }
910
911 static int keep_running(struct thread_data *td)
912 {
913         unsigned long long io_done;
914
915         if (td->done)
916                 return 0;
917         if (td->o.time_based)
918                 return 1;
919         if (td->o.loops) {
920                 td->o.loops--;
921                 return 1;
922         }
923
924         io_done = td->io_bytes[DDIR_READ] + td->io_bytes[DDIR_WRITE]
925                         + td->io_skip_bytes;
926         if (io_done < td->o.size)
927                 return 1;
928
929         return 0;
930 }
931
932 static void reset_io_counters(struct thread_data *td)
933 {
934         td->ts.stat_io_bytes[0] = td->ts.stat_io_bytes[1] = 0;
935         td->this_io_bytes[0] = td->this_io_bytes[1] = 0;
936         td->zone_bytes = 0;
937         td->rate_bytes[0] = td->rate_bytes[1] = 0;
938         td->rate_blocks[0] = td->rate_blocks[1] = 0;
939
940         td->last_was_sync = 0;
941
942         /*
943          * reset file done count if we are to start over
944          */
945         if (td->o.time_based || td->o.loops)
946                 td->nr_done_files = 0;
947
948         /*
949          * Set the same seed to get repeatable runs
950          */
951         td_fill_rand_seeds(td);
952 }
953
954 void reset_all_stats(struct thread_data *td)
955 {
956         struct timeval tv;
957         int i;
958
959         reset_io_counters(td);
960
961         for (i = 0; i < 2; i++) {
962                 td->io_bytes[i] = 0;
963                 td->io_blocks[i] = 0;
964                 td->io_issues[i] = 0;
965                 td->ts.total_io_u[i] = 0;
966         }
967         
968         fio_gettime(&tv, NULL);
969         memcpy(&td->epoch, &tv, sizeof(tv));
970         memcpy(&td->start, &tv, sizeof(tv));
971 }
972
973 static void clear_io_state(struct thread_data *td)
974 {
975         struct fio_file *f;
976         unsigned int i;
977
978         reset_io_counters(td);
979
980         close_files(td);
981         for_each_file(td, f, i)
982                 fio_file_clear_done(f);
983 }
984
985 static int exec_string(const char *string)
986 {
987         int ret, newlen = strlen(string) + 1 + 8;
988         char *str;
989
990         str = malloc(newlen);
991         sprintf(str, "sh -c %s", string);
992
993         ret = system(str);
994         if (ret == -1)
995                 log_err("fio: exec of cmd <%s> failed\n", str);
996
997         free(str);
998         return ret;
999 }
1000
1001 /*
1002  * Entry point for the thread based jobs. The process based jobs end up
1003  * here as well, after a little setup.
1004  */
1005 static void *thread_main(void *data)
1006 {
1007         unsigned long long runtime[2], elapsed;
1008         struct thread_data *td = data;
1009         pthread_condattr_t attr;
1010         int clear_state;
1011
1012         if (!td->o.use_thread)
1013                 setsid();
1014
1015         td->pid = getpid();
1016
1017         dprint(FD_PROCESS, "jobs pid=%d started\n", (int) td->pid);
1018
1019         INIT_FLIST_HEAD(&td->io_u_freelist);
1020         INIT_FLIST_HEAD(&td->io_u_busylist);
1021         INIT_FLIST_HEAD(&td->io_u_requeues);
1022         INIT_FLIST_HEAD(&td->io_log_list);
1023         INIT_FLIST_HEAD(&td->io_hist_list);
1024         INIT_FLIST_HEAD(&td->verify_list);
1025         INIT_FLIST_HEAD(&td->trim_list);
1026         pthread_mutex_init(&td->io_u_lock, NULL);
1027         td->io_hist_tree = RB_ROOT;
1028
1029         pthread_condattr_init(&attr);
1030         pthread_cond_init(&td->verify_cond, &attr);
1031         pthread_cond_init(&td->free_cond, &attr);
1032
1033         td_set_runstate(td, TD_INITIALIZED);
1034         dprint(FD_MUTEX, "up startup_mutex\n");
1035         fio_mutex_up(startup_mutex);
1036         dprint(FD_MUTEX, "wait on td->mutex\n");
1037         fio_mutex_down(td->mutex);
1038         dprint(FD_MUTEX, "done waiting on td->mutex\n");
1039
1040         /*
1041          * the ->mutex mutex is now no longer used, close it to avoid
1042          * eating a file descriptor
1043          */
1044         fio_mutex_remove(td->mutex);
1045
1046         if (td->o.uid != -1U && setuid(td->o.uid)) {
1047                 td_verror(td, errno, "setuid");
1048                 goto err;
1049         }
1050         if (td->o.gid != -1U && setgid(td->o.gid)) {
1051                 td_verror(td, errno, "setgid");
1052                 goto err;
1053         }
1054
1055         /*
1056          * May alter parameters that init_io_u() will use, so we need to
1057          * do this first.
1058          */
1059         if (init_iolog(td))
1060                 goto err;
1061
1062         if (init_io_u(td))
1063                 goto err;
1064
1065         if (td->o.verify_async && verify_async_init(td))
1066                 goto err;
1067
1068         if (td->o.cpumask_set && fio_setaffinity(td->pid, td->o.cpumask) == -1) {
1069                 td_verror(td, errno, "cpu_set_affinity");
1070                 goto err;
1071         }
1072
1073         /*
1074          * If we have a gettimeofday() thread, make sure we exclude that
1075          * thread from this job
1076          */
1077         if (td->o.gtod_cpu) {
1078                 fio_cpu_clear(&td->o.cpumask, td->o.gtod_cpu);
1079                 if (fio_setaffinity(td->pid, td->o.cpumask) == -1) {
1080                         td_verror(td, errno, "cpu_set_affinity");
1081                         goto err;
1082                 }
1083         }
1084
1085         if (td->ioprio_set) {
1086                 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, td->ioprio) == -1) {
1087                         td_verror(td, errno, "ioprio_set");
1088                         goto err;
1089                 }
1090         }
1091
1092         if (td->o.cgroup_weight && cgroup_setup(td, cgroup_list, &cgroup_mnt))
1093                 goto err;
1094
1095         if (nice(td->o.nice) == -1) {
1096                 td_verror(td, errno, "nice");
1097                 goto err;
1098         }
1099
1100         if (td->o.ioscheduler && switch_ioscheduler(td))
1101                 goto err;
1102
1103         if (!td->o.create_serialize && setup_files(td))
1104                 goto err;
1105
1106         if (td_io_init(td))
1107                 goto err;
1108
1109         if (init_random_map(td))
1110                 goto err;
1111
1112         if (td->o.exec_prerun) {
1113                 if (exec_string(td->o.exec_prerun))
1114                         goto err;
1115         }
1116
1117         if (td->o.pre_read) {
1118                 if (pre_read_files(td) < 0)
1119                         goto err;
1120         }
1121
1122         fio_gettime(&td->epoch, NULL);
1123         getrusage(RUSAGE_SELF, &td->ts.ru_start);
1124
1125         runtime[0] = runtime[1] = 0;
1126         clear_state = 0;
1127         while (keep_running(td)) {
1128                 fio_gettime(&td->start, NULL);
1129                 memcpy(&td->ts.stat_sample_time[0], &td->start,
1130                                 sizeof(td->start));
1131                 memcpy(&td->ts.stat_sample_time[1], &td->start,
1132                                 sizeof(td->start));
1133                 memcpy(&td->tv_cache, &td->start, sizeof(td->start));
1134
1135                 if (td->o.ratemin[0] || td->o.ratemin[1])
1136                         memcpy(&td->lastrate, &td->ts.stat_sample_time,
1137                                                         sizeof(td->lastrate));
1138
1139                 if (clear_state)
1140                         clear_io_state(td);
1141
1142                 prune_io_piece_log(td);
1143
1144                 do_io(td);
1145
1146                 clear_state = 1;
1147
1148                 if (td_read(td) && td->io_bytes[DDIR_READ]) {
1149                         elapsed = utime_since_now(&td->start);
1150                         runtime[DDIR_READ] += elapsed;
1151                 }
1152                 if (td_write(td) && td->io_bytes[DDIR_WRITE]) {
1153                         elapsed = utime_since_now(&td->start);
1154                         runtime[DDIR_WRITE] += elapsed;
1155                 }
1156
1157                 if (td->error || td->terminate)
1158                         break;
1159
1160                 if (!td->o.do_verify ||
1161                     td->o.verify == VERIFY_NONE ||
1162                     (td->io_ops->flags & FIO_UNIDIR))
1163                         continue;
1164
1165                 clear_io_state(td);
1166
1167                 fio_gettime(&td->start, NULL);
1168
1169                 do_verify(td);
1170
1171                 runtime[DDIR_READ] += utime_since_now(&td->start);
1172
1173                 if (td->error || td->terminate)
1174                         break;
1175         }
1176
1177         update_rusage_stat(td);
1178         td->ts.runtime[0] = (runtime[0] + 999) / 1000;
1179         td->ts.runtime[1] = (runtime[1] + 999) / 1000;
1180         td->ts.total_run_time = mtime_since_now(&td->epoch);
1181         td->ts.io_bytes[0] = td->io_bytes[0];
1182         td->ts.io_bytes[1] = td->io_bytes[1];
1183
1184         fio_mutex_down(writeout_mutex);
1185         if (td->ts.bw_log) {
1186                 if (td->o.bw_log_file) {
1187                         finish_log_named(td, td->ts.bw_log,
1188                                                 td->o.bw_log_file, "bw");
1189                 } else
1190                         finish_log(td, td->ts.bw_log, "bw");
1191         }
1192         if (td->ts.lat_log) {
1193                 if (td->o.lat_log_file) {
1194                         finish_log_named(td, td->ts.lat_log,
1195                                                 td->o.lat_log_file, "lat");
1196                 } else
1197                         finish_log(td, td->ts.lat_log, "lat");
1198         }
1199         if (td->ts.slat_log) {
1200                 if (td->o.lat_log_file) {
1201                         finish_log_named(td, td->ts.slat_log,
1202                                                 td->o.lat_log_file, "slat");
1203                 } else
1204                         finish_log(td, td->ts.slat_log, "slat");
1205         }
1206         if (td->ts.clat_log) {
1207                 if (td->o.lat_log_file) {
1208                         finish_log_named(td, td->ts.clat_log,
1209                                                 td->o.lat_log_file, "clat");
1210                 } else
1211                         finish_log(td, td->ts.clat_log, "clat");
1212         }
1213         fio_mutex_up(writeout_mutex);
1214         if (td->o.exec_postrun)
1215                 exec_string(td->o.exec_postrun);
1216
1217         if (exitall_on_terminate)
1218                 terminate_threads(td->groupid);
1219
1220 err:
1221         if (td->error)
1222                 log_info("fio: pid=%d, err=%d/%s\n", (int) td->pid, td->error,
1223                                                         td->verror);
1224
1225         if (td->o.verify_async)
1226                 verify_async_exit(td);
1227
1228         close_and_free_files(td);
1229         close_ioengine(td);
1230         cleanup_io_u(td);
1231         cgroup_shutdown(td, &cgroup_mnt);
1232
1233         if (td->o.cpumask_set) {
1234                 int ret = fio_cpuset_exit(&td->o.cpumask);
1235
1236                 td_verror(td, ret, "fio_cpuset_exit");
1237         }
1238
1239         /*
1240          * do this very late, it will log file closing as well
1241          */
1242         if (td->o.write_iolog_file)
1243                 write_iolog_close(td);
1244
1245         options_mem_free(td);
1246         td_set_runstate(td, TD_EXITED);
1247         return (void *) (unsigned long) td->error;
1248 }
1249
1250 /*
1251  * We cannot pass the td data into a forked process, so attach the td and
1252  * pass it to the thread worker.
1253  */
1254 static int fork_main(int shmid, int offset)
1255 {
1256         struct thread_data *td;
1257         void *data, *ret;
1258
1259         data = shmat(shmid, NULL, 0);
1260         if (data == (void *) -1) {
1261                 int __err = errno;
1262
1263                 perror("shmat");
1264                 return __err;
1265         }
1266
1267         td = data + offset * sizeof(struct thread_data);
1268         ret = thread_main(td);
1269         shmdt(data);
1270         return (int) (unsigned long) ret;
1271 }
1272
1273 /*
1274  * Run over the job map and reap the threads that have exited, if any.
1275  */
1276 static void reap_threads(int *nr_running, int *t_rate, int *m_rate)
1277 {
1278         struct thread_data *td;
1279         int i, cputhreads, realthreads, pending, status, ret;
1280
1281         /*
1282          * reap exited threads (TD_EXITED -> TD_REAPED)
1283          */
1284         realthreads = pending = cputhreads = 0;
1285         for_each_td(td, i) {
1286                 int flags = 0;
1287
1288                 /*
1289                  * ->io_ops is NULL for a thread that has closed its
1290                  * io engine
1291                  */
1292                 if (td->io_ops && !strcmp(td->io_ops->name, "cpuio"))
1293                         cputhreads++;
1294                 else
1295                         realthreads++;
1296
1297                 if (!td->pid) {
1298                         pending++;
1299                         continue;
1300                 }
1301                 if (td->runstate == TD_REAPED)
1302                         continue;
1303                 if (td->o.use_thread) {
1304                         if (td->runstate == TD_EXITED) {
1305                                 td_set_runstate(td, TD_REAPED);
1306                                 goto reaped;
1307                         }
1308                         continue;
1309                 }
1310
1311                 flags = WNOHANG;
1312                 if (td->runstate == TD_EXITED)
1313                         flags = 0;
1314
1315                 /*
1316                  * check if someone quit or got killed in an unusual way
1317                  */
1318                 ret = waitpid(td->pid, &status, flags);
1319                 if (ret < 0) {
1320                         if (errno == ECHILD) {
1321                                 log_err("fio: pid=%d disappeared %d\n",
1322                                                 (int) td->pid, td->runstate);
1323                                 td_set_runstate(td, TD_REAPED);
1324                                 goto reaped;
1325                         }
1326                         perror("waitpid");
1327                 } else if (ret == td->pid) {
1328                         if (WIFSIGNALED(status)) {
1329                                 int sig = WTERMSIG(status);
1330
1331                                 if (sig != SIGQUIT)
1332                                         log_err("fio: pid=%d, got signal=%d\n",
1333                                                         (int) td->pid, sig);
1334                                 td_set_runstate(td, TD_REAPED);
1335                                 goto reaped;
1336                         }
1337                         if (WIFEXITED(status)) {
1338                                 if (WEXITSTATUS(status) && !td->error)
1339                                         td->error = WEXITSTATUS(status);
1340
1341                                 td_set_runstate(td, TD_REAPED);
1342                                 goto reaped;
1343                         }
1344                 }
1345
1346                 /*
1347                  * thread is not dead, continue
1348                  */
1349                 pending++;
1350                 continue;
1351 reaped:
1352                 (*nr_running)--;
1353                 (*m_rate) -= (td->o.ratemin[0] + td->o.ratemin[1]);
1354                 (*t_rate) -= (td->o.rate[0] + td->o.rate[1]);
1355                 if (!td->pid)
1356                         pending--;
1357
1358                 if (td->error)
1359                         exit_value++;
1360
1361                 done_secs += mtime_since_now(&td->epoch) / 1000;
1362         }
1363
1364         if (*nr_running == cputhreads && !pending && realthreads)
1365                 terminate_threads(TERMINATE_ALL);
1366 }
1367
1368 static void *gtod_thread_main(void *data)
1369 {
1370         fio_mutex_up(startup_mutex);
1371
1372         /*
1373          * As long as we have jobs around, update the clock. It would be nice
1374          * to have some way of NOT hammering that CPU with gettimeofday(),
1375          * but I'm not sure what to use outside of a simple CPU nop to relax
1376          * it - we don't want to lose precision.
1377          */
1378         while (threads) {
1379                 fio_gtod_update();
1380                 nop;
1381         }
1382
1383         return NULL;
1384 }
1385
1386 static int fio_start_gtod_thread(void)
1387 {
1388         pthread_attr_t attr;
1389         int ret;
1390
1391         pthread_attr_init(&attr);
1392         pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN);
1393         ret = pthread_create(&gtod_thread, &attr, gtod_thread_main, NULL);
1394         pthread_attr_destroy(&attr);
1395         if (ret) {
1396                 log_err("Can't create gtod thread: %s\n", strerror(ret));
1397                 return 1;
1398         }
1399
1400         ret = pthread_detach(gtod_thread);
1401         if (ret) {
1402                 log_err("Can't detatch gtod thread: %s\n", strerror(ret));
1403                 return 1;
1404         }
1405
1406         dprint(FD_MUTEX, "wait on startup_mutex\n");
1407         fio_mutex_down(startup_mutex);
1408         dprint(FD_MUTEX, "done waiting on startup_mutex\n");
1409         return 0;
1410 }
1411
1412 /*
1413  * Main function for kicking off and reaping jobs, as needed.
1414  */
1415 static void run_threads(void)
1416 {
1417         struct thread_data *td;
1418         unsigned long spent;
1419         int i, todo, nr_running, m_rate, t_rate, nr_started;
1420
1421         if (fio_pin_memory())
1422                 return;
1423
1424         if (fio_gtod_offload && fio_start_gtod_thread())
1425                 return;
1426
1427         if (!terse_output) {
1428                 log_info("Starting ");
1429                 if (nr_thread)
1430                         log_info("%d thread%s", nr_thread,
1431                                                 nr_thread > 1 ? "s" : "");
1432                 if (nr_process) {
1433                         if (nr_thread)
1434                                 printf(" and ");
1435                         log_info("%d process%s", nr_process,
1436                                                 nr_process > 1 ? "es" : "");
1437                 }
1438                 log_info("\n");
1439                 fflush(stdout);
1440         }
1441
1442         set_sig_handlers();
1443
1444         todo = thread_number;
1445         nr_running = 0;
1446         nr_started = 0;
1447         m_rate = t_rate = 0;
1448
1449         for_each_td(td, i) {
1450                 print_status_init(td->thread_number - 1);
1451
1452                 if (!td->o.create_serialize) {
1453                         init_disk_util(td);
1454                         continue;
1455                 }
1456
1457                 /*
1458                  * do file setup here so it happens sequentially,
1459                  * we don't want X number of threads getting their
1460                  * client data interspersed on disk
1461                  */
1462                 if (setup_files(td)) {
1463                         exit_value++;
1464                         if (td->error)
1465                                 log_err("fio: pid=%d, err=%d/%s\n",
1466                                         (int) td->pid, td->error, td->verror);
1467                         td_set_runstate(td, TD_REAPED);
1468                         todo--;
1469                 } else {
1470                         struct fio_file *f;
1471                         unsigned int i;
1472
1473                         /*
1474                          * for sharing to work, each job must always open
1475                          * its own files. so close them, if we opened them
1476                          * for creation
1477                          */
1478                         for_each_file(td, f, i) {
1479                                 if (fio_file_open(f))
1480                                         td_io_close_file(td, f);
1481                         }
1482                 }
1483
1484                 init_disk_util(td);
1485         }
1486
1487         set_genesis_time();
1488
1489         while (todo) {
1490                 struct thread_data *map[MAX_JOBS];
1491                 struct timeval this_start;
1492                 int this_jobs = 0, left;
1493
1494                 /*
1495                  * create threads (TD_NOT_CREATED -> TD_CREATED)
1496                  */
1497                 for_each_td(td, i) {
1498                         if (td->runstate != TD_NOT_CREATED)
1499                                 continue;
1500
1501                         /*
1502                          * never got a chance to start, killed by other
1503                          * thread for some reason
1504                          */
1505                         if (td->terminate) {
1506                                 todo--;
1507                                 continue;
1508                         }
1509
1510                         if (td->o.start_delay) {
1511                                 spent = mtime_since_genesis();
1512
1513                                 if (td->o.start_delay * 1000 > spent)
1514                                         continue;
1515                         }
1516
1517                         if (td->o.stonewall && (nr_started || nr_running)) {
1518                                 dprint(FD_PROCESS, "%s: stonewall wait\n",
1519                                                         td->o.name);
1520                                 break;
1521                         }
1522
1523                         /*
1524                          * Set state to created. Thread will transition
1525                          * to TD_INITIALIZED when it's done setting up.
1526                          */
1527                         td_set_runstate(td, TD_CREATED);
1528                         map[this_jobs++] = td;
1529                         nr_started++;
1530
1531                         if (td->o.use_thread) {
1532                                 int ret;
1533
1534                                 dprint(FD_PROCESS, "will pthread_create\n");
1535                                 ret = pthread_create(&td->thread, NULL,
1536                                                         thread_main, td);
1537                                 if (ret) {
1538                                         log_err("pthread_create: %s\n",
1539                                                         strerror(ret));
1540                                         nr_started--;
1541                                         break;
1542                                 }
1543                                 ret = pthread_detach(td->thread);
1544                                 if (ret)
1545                                         log_err("pthread_detach: %s",
1546                                                         strerror(ret));
1547                         } else {
1548                                 pid_t pid;
1549                                 dprint(FD_PROCESS, "will fork\n");
1550                                 pid = fork();
1551                                 if (!pid) {
1552                                         int ret = fork_main(shm_id, i);
1553
1554                                         _exit(ret);
1555                                 } else if (i == fio_debug_jobno)
1556                                         *fio_debug_jobp = pid;
1557                         }
1558                         dprint(FD_MUTEX, "wait on startup_mutex\n");
1559                         if (fio_mutex_down_timeout(startup_mutex, 10)) {
1560                                 log_err("fio: job startup hung? exiting.\n");
1561                                 terminate_threads(TERMINATE_ALL);
1562                                 fio_abort = 1;
1563                                 nr_started--;
1564                                 break;
1565                         }
1566                         dprint(FD_MUTEX, "done waiting on startup_mutex\n");
1567                 }
1568
1569                 /*
1570                  * Wait for the started threads to transition to
1571                  * TD_INITIALIZED.
1572                  */
1573                 fio_gettime(&this_start, NULL);
1574                 left = this_jobs;
1575                 while (left && !fio_abort) {
1576                         if (mtime_since_now(&this_start) > JOB_START_TIMEOUT)
1577                                 break;
1578
1579                         usleep(100000);
1580
1581                         for (i = 0; i < this_jobs; i++) {
1582                                 td = map[i];
1583                                 if (!td)
1584                                         continue;
1585                                 if (td->runstate == TD_INITIALIZED) {
1586                                         map[i] = NULL;
1587                                         left--;
1588                                 } else if (td->runstate >= TD_EXITED) {
1589                                         map[i] = NULL;
1590                                         left--;
1591                                         todo--;
1592                                         nr_running++; /* work-around... */
1593                                 }
1594                         }
1595                 }
1596
1597                 if (left) {
1598                         log_err("fio: %d jobs failed to start\n", left);
1599                         for (i = 0; i < this_jobs; i++) {
1600                                 td = map[i];
1601                                 if (!td)
1602                                         continue;
1603                                 kill(td->pid, SIGTERM);
1604                         }
1605                         break;
1606                 }
1607
1608                 /*
1609                  * start created threads (TD_INITIALIZED -> TD_RUNNING).
1610                  */
1611                 for_each_td(td, i) {
1612                         if (td->runstate != TD_INITIALIZED)
1613                                 continue;
1614
1615                         if (in_ramp_time(td))
1616                                 td_set_runstate(td, TD_RAMP);
1617                         else
1618                                 td_set_runstate(td, TD_RUNNING);
1619                         nr_running++;
1620                         nr_started--;
1621                         m_rate += td->o.ratemin[0] + td->o.ratemin[1];
1622                         t_rate += td->o.rate[0] + td->o.rate[1];
1623                         todo--;
1624                         fio_mutex_up(td->mutex);
1625                 }
1626
1627                 reap_threads(&nr_running, &t_rate, &m_rate);
1628
1629                 if (todo)
1630                         usleep(100000);
1631         }
1632
1633         while (nr_running) {
1634                 reap_threads(&nr_running, &t_rate, &m_rate);
1635                 usleep(10000);
1636         }
1637
1638         update_io_ticks();
1639         fio_unpin_memory();
1640 }
1641
1642 int main(int argc, char *argv[])
1643 {
1644         long ps;
1645
1646         sinit();
1647         init_rand(&__fio_rand_state);
1648
1649         /*
1650          * We need locale for number printing, if it isn't set then just
1651          * go with the US format.
1652          */
1653         if (!getenv("LC_NUMERIC"))
1654                 setlocale(LC_NUMERIC, "en_US");
1655
1656         ps = sysconf(_SC_PAGESIZE);
1657         if (ps < 0) {
1658                 log_err("Failed to get page size\n");
1659                 return 1;
1660         }
1661
1662         page_size = ps;
1663         page_mask = ps - 1;
1664
1665         fio_keywords_init();
1666
1667         if (parse_options(argc, argv))
1668                 return 1;
1669
1670         if (exec_profile && load_profile(exec_profile))
1671                 return 1;
1672
1673         if (!thread_number)
1674                 return 0;
1675
1676         if (write_bw_log) {
1677                 setup_log(&agg_io_log[DDIR_READ]);
1678                 setup_log(&agg_io_log[DDIR_WRITE]);
1679         }
1680
1681         startup_mutex = fio_mutex_init(0);
1682         writeout_mutex = fio_mutex_init(1);
1683
1684         set_genesis_time();
1685
1686         status_timer_arm();
1687
1688         cgroup_list = smalloc(sizeof(*cgroup_list));
1689         INIT_FLIST_HEAD(cgroup_list);
1690
1691         run_threads();
1692
1693         if (!fio_abort) {
1694                 show_run_stats();
1695                 if (write_bw_log) {
1696                         __finish_log(agg_io_log[DDIR_READ], "agg-read_bw.log");
1697                         __finish_log(agg_io_log[DDIR_WRITE],
1698                                         "agg-write_bw.log");
1699                 }
1700         }
1701
1702         cgroup_kill(cgroup_list);
1703         sfree(cgroup_list);
1704         sfree(cgroup_mnt);
1705
1706         fio_mutex_remove(startup_mutex);
1707         fio_mutex_remove(writeout_mutex);
1708         return exit_value;
1709 }