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