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