gfio: put disk utilization tab in a scrolled window
[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 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                         if (full && !min_events && td->o.iodepth_batch_complete != 0)
498                                 min_events = 1;
499
500                         do {
501                                 /*
502                                  * Reap required number of io units, if any,
503                                  * and do the verification on them through
504                                  * the callback handler
505                                  */
506                                 if (io_u_queued_complete(td, min_events, NULL) < 0) {
507                                         ret = -1;
508                                         break;
509                                 }
510                         } while (full && (td->cur_depth > td->o.iodepth_low));
511                 }
512                 if (ret < 0)
513                         break;
514         }
515
516         if (!td->error) {
517                 min_events = td->cur_depth;
518
519                 if (min_events)
520                         ret = io_u_queued_complete(td, min_events, NULL);
521         } else
522                 cleanup_pending_aio(td);
523
524         td_set_runstate(td, TD_RUNNING);
525
526         dprint(FD_VERIFY, "exiting loop\n");
527 }
528
529 static int io_bytes_exceeded(struct thread_data *td)
530 {
531         unsigned long long bytes;
532
533         if (td_rw(td))
534                 bytes = td->this_io_bytes[0] + td->this_io_bytes[1];
535         else if (td_write(td))
536                 bytes = td->this_io_bytes[1];
537         else
538                 bytes = td->this_io_bytes[0];
539
540         return bytes >= td->o.size;
541 }
542
543 /*
544  * Main IO worker function. It retrieves io_u's to process and queues
545  * and reaps them, checking for rate and errors along the way.
546  */
547 static void do_io(struct thread_data *td)
548 {
549         unsigned int i;
550         int ret = 0;
551
552         if (in_ramp_time(td))
553                 td_set_runstate(td, TD_RAMP);
554         else
555                 td_set_runstate(td, TD_RUNNING);
556
557         while ((td->o.read_iolog_file && !flist_empty(&td->io_log_list)) ||
558                 (!flist_empty(&td->trim_list)) || !io_bytes_exceeded(td)) {
559                 struct timeval comp_time;
560                 unsigned long bytes_done[2] = { 0, 0 };
561                 int min_evts = 0;
562                 struct io_u *io_u;
563                 int ret2, full;
564                 enum fio_ddir ddir;
565
566                 if (td->terminate)
567                         break;
568
569                 update_tv_cache(td);
570
571                 if (runtime_exceeded(td, &td->tv_cache)) {
572                         __update_tv_cache(td);
573                         if (runtime_exceeded(td, &td->tv_cache)) {
574                                 td->terminate = 1;
575                                 break;
576                         }
577                 }
578
579                 if (flow_threshold_exceeded(td))
580                         continue;
581
582                 io_u = get_io_u(td);
583                 if (!io_u)
584                         break;
585
586                 ddir = io_u->ddir;
587
588                 /*
589                  * Add verification end_io handler if:
590                  *      - Asked to verify (!td_rw(td))
591                  *      - Or the io_u is from our verify list (mixed write/ver)
592                  */
593                 if (td->o.verify != VERIFY_NONE && io_u->ddir == DDIR_READ &&
594                     ((io_u->flags & IO_U_F_VER_LIST) || !td_rw(td))) {
595                         if (td->o.verify_async)
596                                 io_u->end_io = verify_io_u_async;
597                         else
598                                 io_u->end_io = verify_io_u;
599                         td_set_runstate(td, TD_VERIFYING);
600                 } else if (in_ramp_time(td))
601                         td_set_runstate(td, TD_RAMP);
602                 else
603                         td_set_runstate(td, TD_RUNNING);
604
605                 ret = td_io_queue(td, io_u);
606                 switch (ret) {
607                 case FIO_Q_COMPLETED:
608                         if (io_u->error) {
609                                 ret = -io_u->error;
610                                 clear_io_u(td, io_u);
611                         } else if (io_u->resid) {
612                                 int bytes = io_u->xfer_buflen - io_u->resid;
613                                 struct fio_file *f = io_u->file;
614
615                                 /*
616                                  * zero read, fail
617                                  */
618                                 if (!bytes) {
619                                         td_verror(td, EIO, "full resid");
620                                         put_io_u(td, io_u);
621                                         break;
622                                 }
623
624                                 io_u->xfer_buflen = io_u->resid;
625                                 io_u->xfer_buf += bytes;
626                                 io_u->offset += bytes;
627
628                                 if (ddir_rw(io_u->ddir))
629                                         td->ts.short_io_u[io_u->ddir]++;
630
631                                 if (io_u->offset == f->real_file_size)
632                                         goto sync_done;
633
634                                 requeue_io_u(td, &io_u);
635                         } else {
636 sync_done:
637                                 if (__should_check_rate(td, 0) ||
638                                     __should_check_rate(td, 1))
639                                         fio_gettime(&comp_time, NULL);
640
641                                 ret = io_u_sync_complete(td, io_u, bytes_done);
642                                 if (ret < 0)
643                                         break;
644                         }
645                         break;
646                 case FIO_Q_QUEUED:
647                         /*
648                          * if the engine doesn't have a commit hook,
649                          * the io_u is really queued. if it does have such
650                          * a hook, it has to call io_u_queued() itself.
651                          */
652                         if (td->io_ops->commit == NULL)
653                                 io_u_queued(td, io_u);
654                         break;
655                 case FIO_Q_BUSY:
656                         requeue_io_u(td, &io_u);
657                         ret2 = td_io_commit(td);
658                         if (ret2 < 0)
659                                 ret = ret2;
660                         break;
661                 default:
662                         assert(ret < 0);
663                         put_io_u(td, io_u);
664                         break;
665                 }
666
667                 if (break_on_this_error(td, ddir, &ret))
668                         break;
669
670                 /*
671                  * See if we need to complete some commands. Note that we
672                  * can get BUSY even without IO queued, if the system is
673                  * resource starved.
674                  */
675                 full = queue_full(td) || (ret == FIO_Q_BUSY && td->cur_depth);
676                 if (full || !td->o.iodepth_batch_complete) {
677                         min_evts = min(td->o.iodepth_batch_complete,
678                                         td->cur_depth);
679                         if (full && !min_evts && td->o.iodepth_batch_complete != 0)
680                                 min_evts = 1;
681
682                         if (__should_check_rate(td, 0) ||
683                             __should_check_rate(td, 1))
684                                 fio_gettime(&comp_time, NULL);
685
686                         do {
687                                 ret = io_u_queued_complete(td, min_evts, bytes_done);
688                                 if (ret < 0)
689                                         break;
690
691                         } while (full && (td->cur_depth > td->o.iodepth_low));
692                 }
693
694                 if (ret < 0)
695                         break;
696                 if (!(bytes_done[0] + bytes_done[1]))
697                         continue;
698
699                 if (!in_ramp_time(td) && should_check_rate(td, bytes_done)) {
700                         if (check_min_rate(td, &comp_time, bytes_done)) {
701                                 if (exitall_on_terminate)
702                                         fio_terminate_threads(td->groupid);
703                                 td_verror(td, EIO, "check_min_rate");
704                                 break;
705                         }
706                 }
707
708                 if (td->o.thinktime) {
709                         unsigned long long b;
710
711                         b = td->io_blocks[0] + td->io_blocks[1];
712                         if (!(b % td->o.thinktime_blocks)) {
713                                 int left;
714
715                                 if (td->o.thinktime_spin)
716                                         usec_spin(td->o.thinktime_spin);
717
718                                 left = td->o.thinktime - td->o.thinktime_spin;
719                                 if (left)
720                                         usec_sleep(td, left);
721                         }
722                 }
723         }
724
725         if (td->trim_entries)
726                 log_err("fio: %d trim entries leaked?\n", td->trim_entries);
727
728         if (td->o.fill_device && td->error == ENOSPC) {
729                 td->error = 0;
730                 td->terminate = 1;
731         }
732         if (!td->error) {
733                 struct fio_file *f;
734
735                 i = td->cur_depth;
736                 if (i) {
737                         ret = io_u_queued_complete(td, i, NULL);
738                         if (td->o.fill_device && td->error == ENOSPC)
739                                 td->error = 0;
740                 }
741
742                 if (should_fsync(td) && td->o.end_fsync) {
743                         td_set_runstate(td, TD_FSYNCING);
744
745                         for_each_file(td, f, i) {
746                                 if (!fio_file_open(f))
747                                         continue;
748                                 fio_io_sync(td, f);
749                         }
750                 }
751         } else
752                 cleanup_pending_aio(td);
753
754         /*
755          * stop job if we failed doing any IO
756          */
757         if ((td->this_io_bytes[0] + td->this_io_bytes[1]) == 0)
758                 td->done = 1;
759 }
760
761 static void cleanup_io_u(struct thread_data *td)
762 {
763         struct flist_head *entry, *n;
764         struct io_u *io_u;
765
766         flist_for_each_safe(entry, n, &td->io_u_freelist) {
767                 io_u = flist_entry(entry, struct io_u, list);
768
769                 flist_del(&io_u->list);
770                 fio_memfree(io_u, sizeof(*io_u));
771         }
772
773         free_io_mem(td);
774 }
775
776 static int init_io_u(struct thread_data *td)
777 {
778         struct io_u *io_u;
779         unsigned int max_bs, min_write;
780         int cl_align, i, max_units;
781         char *p;
782
783         max_units = td->o.iodepth;
784         max_bs = max(td->o.max_bs[DDIR_READ], td->o.max_bs[DDIR_WRITE]);
785         min_write = td->o.min_bs[DDIR_WRITE];
786         td->orig_buffer_size = (unsigned long long) max_bs
787                                         * (unsigned long long) max_units;
788
789         if (td->o.mem_type == MEM_SHMHUGE || td->o.mem_type == MEM_MMAPHUGE) {
790                 unsigned long bs;
791
792                 bs = td->orig_buffer_size + td->o.hugepage_size - 1;
793                 td->orig_buffer_size = bs & ~(td->o.hugepage_size - 1);
794         }
795
796         if (td->orig_buffer_size != (size_t) td->orig_buffer_size) {
797                 log_err("fio: IO memory too large. Reduce max_bs or iodepth\n");
798                 return 1;
799         }
800
801         if (allocate_io_mem(td))
802                 return 1;
803
804         if (td->o.odirect || td->o.mem_align ||
805             (td->io_ops->flags & FIO_RAWIO))
806                 p = PAGE_ALIGN(td->orig_buffer) + td->o.mem_align;
807         else
808                 p = td->orig_buffer;
809
810         cl_align = os_cache_line_size();
811
812         for (i = 0; i < max_units; i++) {
813                 void *ptr;
814
815                 if (td->terminate)
816                         return 1;
817
818                 ptr = fio_memalign(cl_align, sizeof(*io_u));
819                 if (!ptr) {
820                         log_err("fio: unable to allocate aligned memory\n");
821                         break;
822                 }
823
824                 io_u = ptr;
825                 memset(io_u, 0, sizeof(*io_u));
826                 INIT_FLIST_HEAD(&io_u->list);
827                 dprint(FD_MEM, "io_u alloc %p, index %u\n", io_u, i);
828
829                 if (!(td->io_ops->flags & FIO_NOIO)) {
830                         io_u->buf = p;
831                         dprint(FD_MEM, "io_u %p, mem %p\n", io_u, io_u->buf);
832
833                         if (td_write(td))
834                                 io_u_fill_buffer(td, io_u, min_write, max_bs);
835                         if (td_write(td) && td->o.verify_pattern_bytes) {
836                                 /*
837                                  * Fill the buffer with the pattern if we are
838                                  * going to be doing writes.
839                                  */
840                                 fill_pattern(td, io_u->buf, max_bs, io_u, 0, 0);
841                         }
842                 }
843
844                 io_u->index = i;
845                 io_u->flags = IO_U_F_FREE;
846                 flist_add(&io_u->list, &td->io_u_freelist);
847                 p += max_bs;
848         }
849
850         return 0;
851 }
852
853 static int switch_ioscheduler(struct thread_data *td)
854 {
855         char tmp[256], tmp2[128];
856         FILE *f;
857         int ret;
858
859         if (td->io_ops->flags & FIO_DISKLESSIO)
860                 return 0;
861
862         sprintf(tmp, "%s/queue/scheduler", td->sysfs_root);
863
864         f = fopen(tmp, "r+");
865         if (!f) {
866                 if (errno == ENOENT) {
867                         log_err("fio: os or kernel doesn't support IO scheduler"
868                                 " switching\n");
869                         return 0;
870                 }
871                 td_verror(td, errno, "fopen iosched");
872                 return 1;
873         }
874
875         /*
876          * Set io scheduler.
877          */
878         ret = fwrite(td->o.ioscheduler, strlen(td->o.ioscheduler), 1, f);
879         if (ferror(f) || ret != 1) {
880                 td_verror(td, errno, "fwrite");
881                 fclose(f);
882                 return 1;
883         }
884
885         rewind(f);
886
887         /*
888          * Read back and check that the selected scheduler is now the default.
889          */
890         ret = fread(tmp, 1, sizeof(tmp), f);
891         if (ferror(f) || ret < 0) {
892                 td_verror(td, errno, "fread");
893                 fclose(f);
894                 return 1;
895         }
896
897         sprintf(tmp2, "[%s]", td->o.ioscheduler);
898         if (!strstr(tmp, tmp2)) {
899                 log_err("fio: io scheduler %s not found\n", td->o.ioscheduler);
900                 td_verror(td, EINVAL, "iosched_switch");
901                 fclose(f);
902                 return 1;
903         }
904
905         fclose(f);
906         return 0;
907 }
908
909 static int keep_running(struct thread_data *td)
910 {
911         unsigned long long io_done;
912
913         if (td->done)
914                 return 0;
915         if (td->o.time_based)
916                 return 1;
917         if (td->o.loops) {
918                 td->o.loops--;
919                 return 1;
920         }
921
922         io_done = td->io_bytes[DDIR_READ] + td->io_bytes[DDIR_WRITE]
923                         + td->io_skip_bytes;
924         if (io_done < td->o.size)
925                 return 1;
926
927         return 0;
928 }
929
930 static int exec_string(const char *string)
931 {
932         int ret, newlen = strlen(string) + 1 + 8;
933         char *str;
934
935         str = malloc(newlen);
936         sprintf(str, "sh -c %s", string);
937
938         ret = system(str);
939         if (ret == -1)
940                 log_err("fio: exec of cmd <%s> failed\n", str);
941
942         free(str);
943         return ret;
944 }
945
946 /*
947  * Entry point for the thread based jobs. The process based jobs end up
948  * here as well, after a little setup.
949  */
950 static void *thread_main(void *data)
951 {
952         unsigned long long elapsed;
953         struct thread_data *td = data;
954         pthread_condattr_t attr;
955         int clear_state;
956
957         if (!td->o.use_thread) {
958                 setsid();
959                 td->pid = getpid();
960         } else
961                 td->pid = gettid();
962
963         dprint(FD_PROCESS, "jobs pid=%d started\n", (int) td->pid);
964
965         INIT_FLIST_HEAD(&td->io_u_freelist);
966         INIT_FLIST_HEAD(&td->io_u_busylist);
967         INIT_FLIST_HEAD(&td->io_u_requeues);
968         INIT_FLIST_HEAD(&td->io_log_list);
969         INIT_FLIST_HEAD(&td->io_hist_list);
970         INIT_FLIST_HEAD(&td->verify_list);
971         INIT_FLIST_HEAD(&td->trim_list);
972         pthread_mutex_init(&td->io_u_lock, NULL);
973         td->io_hist_tree = RB_ROOT;
974
975         pthread_condattr_init(&attr);
976         pthread_cond_init(&td->verify_cond, &attr);
977         pthread_cond_init(&td->free_cond, &attr);
978
979         td_set_runstate(td, TD_INITIALIZED);
980         dprint(FD_MUTEX, "up startup_mutex\n");
981         fio_mutex_up(startup_mutex);
982         dprint(FD_MUTEX, "wait on td->mutex\n");
983         fio_mutex_down(td->mutex);
984         dprint(FD_MUTEX, "done waiting on td->mutex\n");
985
986         /*
987          * the ->mutex mutex is now no longer used, close it to avoid
988          * eating a file descriptor
989          */
990         fio_mutex_remove(td->mutex);
991
992         /*
993          * A new gid requires privilege, so we need to do this before setting
994          * the uid.
995          */
996         if (td->o.gid != -1U && setgid(td->o.gid)) {
997                 td_verror(td, errno, "setgid");
998                 goto err;
999         }
1000         if (td->o.uid != -1U && setuid(td->o.uid)) {
1001                 td_verror(td, errno, "setuid");
1002                 goto err;
1003         }
1004
1005         /*
1006          * If we have a gettimeofday() thread, make sure we exclude that
1007          * thread from this job
1008          */
1009         if (td->o.gtod_cpu)
1010                 fio_cpu_clear(&td->o.cpumask, td->o.gtod_cpu);
1011
1012         /*
1013          * Set affinity first, in case it has an impact on the memory
1014          * allocations.
1015          */
1016         if (td->o.cpumask_set && fio_setaffinity(td->pid, td->o.cpumask) == -1) {
1017                 td_verror(td, errno, "cpu_set_affinity");
1018                 goto err;
1019         }
1020
1021         /*
1022          * May alter parameters that init_io_u() will use, so we need to
1023          * do this first.
1024          */
1025         if (init_iolog(td))
1026                 goto err;
1027
1028         if (init_io_u(td))
1029                 goto err;
1030
1031         if (td->o.verify_async && verify_async_init(td))
1032                 goto err;
1033
1034         if (td->ioprio_set) {
1035                 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, td->ioprio) == -1) {
1036                         td_verror(td, errno, "ioprio_set");
1037                         goto err;
1038                 }
1039         }
1040
1041         if (td->o.cgroup_weight && cgroup_setup(td, cgroup_list, &cgroup_mnt))
1042                 goto err;
1043
1044         errno = 0;
1045         if (nice(td->o.nice) == -1 && errno != 0) {
1046                 td_verror(td, errno, "nice");
1047                 goto err;
1048         }
1049
1050         if (td->o.ioscheduler && switch_ioscheduler(td))
1051                 goto err;
1052
1053         if (!td->o.create_serialize && setup_files(td))
1054                 goto err;
1055
1056         if (td_io_init(td))
1057                 goto err;
1058
1059         if (init_random_map(td))
1060                 goto err;
1061
1062         if (td->o.exec_prerun) {
1063                 if (exec_string(td->o.exec_prerun))
1064                         goto err;
1065         }
1066
1067         if (td->o.pre_read) {
1068                 if (pre_read_files(td) < 0)
1069                         goto err;
1070         }
1071
1072         fio_gettime(&td->epoch, NULL);
1073         getrusage(RUSAGE_SELF, &td->ru_start);
1074
1075         clear_state = 0;
1076         while (keep_running(td)) {
1077                 fio_gettime(&td->start, NULL);
1078                 memcpy(&td->bw_sample_time, &td->start, sizeof(td->start));
1079                 memcpy(&td->iops_sample_time, &td->start, sizeof(td->start));
1080                 memcpy(&td->tv_cache, &td->start, sizeof(td->start));
1081
1082                 if (td->o.ratemin[0] || td->o.ratemin[1]) {
1083                         memcpy(&td->lastrate[0], &td->bw_sample_time,
1084                                                 sizeof(td->bw_sample_time));
1085                         memcpy(&td->lastrate[1], &td->bw_sample_time,
1086                                                 sizeof(td->bw_sample_time));
1087                 }
1088
1089                 if (clear_state)
1090                         clear_io_state(td);
1091
1092                 prune_io_piece_log(td);
1093
1094                 do_io(td);
1095
1096                 clear_state = 1;
1097
1098                 if (td_read(td) && td->io_bytes[DDIR_READ]) {
1099                         elapsed = utime_since_now(&td->start);
1100                         td->ts.runtime[DDIR_READ] += elapsed;
1101                 }
1102                 if (td_write(td) && td->io_bytes[DDIR_WRITE]) {
1103                         elapsed = utime_since_now(&td->start);
1104                         td->ts.runtime[DDIR_WRITE] += elapsed;
1105                 }
1106
1107                 if (td->error || td->terminate)
1108                         break;
1109
1110                 if (!td->o.do_verify ||
1111                     td->o.verify == VERIFY_NONE ||
1112                     (td->io_ops->flags & FIO_UNIDIR))
1113                         continue;
1114
1115                 clear_io_state(td);
1116
1117                 fio_gettime(&td->start, NULL);
1118
1119                 do_verify(td);
1120
1121                 td->ts.runtime[DDIR_READ] += utime_since_now(&td->start);
1122
1123                 if (td->error || td->terminate)
1124                         break;
1125         }
1126
1127         update_rusage_stat(td);
1128         td->ts.runtime[0] = (td->ts.runtime[0] + 999) / 1000;
1129         td->ts.runtime[1] = (td->ts.runtime[1] + 999) / 1000;
1130         td->ts.total_run_time = mtime_since_now(&td->epoch);
1131         td->ts.io_bytes[0] = td->io_bytes[0];
1132         td->ts.io_bytes[1] = td->io_bytes[1];
1133
1134         fio_mutex_down(writeout_mutex);
1135         if (td->bw_log) {
1136                 if (td->o.bw_log_file) {
1137                         finish_log_named(td, td->bw_log,
1138                                                 td->o.bw_log_file, "bw");
1139                 } else
1140                         finish_log(td, td->bw_log, "bw");
1141         }
1142         if (td->lat_log) {
1143                 if (td->o.lat_log_file) {
1144                         finish_log_named(td, td->lat_log,
1145                                                 td->o.lat_log_file, "lat");
1146                 } else
1147                         finish_log(td, td->lat_log, "lat");
1148         }
1149         if (td->slat_log) {
1150                 if (td->o.lat_log_file) {
1151                         finish_log_named(td, td->slat_log,
1152                                                 td->o.lat_log_file, "slat");
1153                 } else
1154                         finish_log(td, td->slat_log, "slat");
1155         }
1156         if (td->clat_log) {
1157                 if (td->o.lat_log_file) {
1158                         finish_log_named(td, td->clat_log,
1159                                                 td->o.lat_log_file, "clat");
1160                 } else
1161                         finish_log(td, td->clat_log, "clat");
1162         }
1163         if (td->iops_log) {
1164                 if (td->o.iops_log_file) {
1165                         finish_log_named(td, td->iops_log,
1166                                                 td->o.iops_log_file, "iops");
1167                 } else
1168                         finish_log(td, td->iops_log, "iops");
1169         }
1170
1171         fio_mutex_up(writeout_mutex);
1172         if (td->o.exec_postrun)
1173                 exec_string(td->o.exec_postrun);
1174
1175         if (exitall_on_terminate)
1176                 fio_terminate_threads(td->groupid);
1177
1178 err:
1179         if (td->error)
1180                 log_info("fio: pid=%d, err=%d/%s\n", (int) td->pid, td->error,
1181                                                         td->verror);
1182
1183         if (td->o.verify_async)
1184                 verify_async_exit(td);
1185
1186         close_and_free_files(td);
1187         close_ioengine(td);
1188         cleanup_io_u(td);
1189         cgroup_shutdown(td, &cgroup_mnt);
1190
1191         if (td->o.cpumask_set) {
1192                 int ret = fio_cpuset_exit(&td->o.cpumask);
1193
1194                 td_verror(td, ret, "fio_cpuset_exit");
1195         }
1196
1197         /*
1198          * do this very late, it will log file closing as well
1199          */
1200         if (td->o.write_iolog_file)
1201                 write_iolog_close(td);
1202
1203         td_set_runstate(td, TD_EXITED);
1204         return (void *) (uintptr_t) td->error;
1205 }
1206
1207
1208 /*
1209  * We cannot pass the td data into a forked process, so attach the td and
1210  * pass it to the thread worker.
1211  */
1212 static int fork_main(int shmid, int offset)
1213 {
1214         struct thread_data *td;
1215         void *data, *ret;
1216
1217 #ifndef __hpux
1218         data = shmat(shmid, NULL, 0);
1219         if (data == (void *) -1) {
1220                 int __err = errno;
1221
1222                 perror("shmat");
1223                 return __err;
1224         }
1225 #else
1226         /*
1227          * HP-UX inherits shm mappings?
1228          */
1229         data = threads;
1230 #endif
1231
1232         td = data + offset * sizeof(struct thread_data);
1233         ret = thread_main(td);
1234         shmdt(data);
1235         return (int) (uintptr_t) ret;
1236 }
1237
1238 /*
1239  * Run over the job map and reap the threads that have exited, if any.
1240  */
1241 static void reap_threads(unsigned int *nr_running, unsigned int *t_rate,
1242                          unsigned int *m_rate)
1243 {
1244         struct thread_data *td;
1245         unsigned int cputhreads, realthreads, pending;
1246         int i, status, ret;
1247
1248         /*
1249          * reap exited threads (TD_EXITED -> TD_REAPED)
1250          */
1251         realthreads = pending = cputhreads = 0;
1252         for_each_td(td, i) {
1253                 int flags = 0;
1254
1255                 /*
1256                  * ->io_ops is NULL for a thread that has closed its
1257                  * io engine
1258                  */
1259                 if (td->io_ops && !strcmp(td->io_ops->name, "cpuio"))
1260                         cputhreads++;
1261                 else
1262                         realthreads++;
1263
1264                 if (!td->pid) {
1265                         pending++;
1266                         continue;
1267                 }
1268                 if (td->runstate == TD_REAPED)
1269                         continue;
1270                 if (td->o.use_thread) {
1271                         if (td->runstate == TD_EXITED) {
1272                                 td_set_runstate(td, TD_REAPED);
1273                                 goto reaped;
1274                         }
1275                         continue;
1276                 }
1277
1278                 flags = WNOHANG;
1279                 if (td->runstate == TD_EXITED)
1280                         flags = 0;
1281
1282                 /*
1283                  * check if someone quit or got killed in an unusual way
1284                  */
1285                 ret = waitpid(td->pid, &status, flags);
1286                 if (ret < 0) {
1287                         if (errno == ECHILD) {
1288                                 log_err("fio: pid=%d disappeared %d\n",
1289                                                 (int) td->pid, td->runstate);
1290                                 td_set_runstate(td, TD_REAPED);
1291                                 goto reaped;
1292                         }
1293                         perror("waitpid");
1294                 } else if (ret == td->pid) {
1295                         if (WIFSIGNALED(status)) {
1296                                 int sig = WTERMSIG(status);
1297
1298                                 if (sig != SIGTERM)
1299                                         log_err("fio: pid=%d, got signal=%d\n",
1300                                                         (int) td->pid, sig);
1301                                 td_set_runstate(td, TD_REAPED);
1302                                 goto reaped;
1303                         }
1304                         if (WIFEXITED(status)) {
1305                                 if (WEXITSTATUS(status) && !td->error)
1306                                         td->error = WEXITSTATUS(status);
1307
1308                                 td_set_runstate(td, TD_REAPED);
1309                                 goto reaped;
1310                         }
1311                 }
1312
1313                 /*
1314                  * thread is not dead, continue
1315                  */
1316                 pending++;
1317                 continue;
1318 reaped:
1319                 (*nr_running)--;
1320                 (*m_rate) -= (td->o.ratemin[0] + td->o.ratemin[1]);
1321                 (*t_rate) -= (td->o.rate[0] + td->o.rate[1]);
1322                 if (!td->pid)
1323                         pending--;
1324
1325                 if (td->error)
1326                         exit_value++;
1327
1328                 done_secs += mtime_since_now(&td->epoch) / 1000;
1329         }
1330
1331         if (*nr_running == cputhreads && !pending && realthreads)
1332                 fio_terminate_threads(TERMINATE_ALL);
1333 }
1334
1335 /*
1336  * Main function for kicking off and reaping jobs, as needed.
1337  */
1338 static void run_threads(void)
1339 {
1340         struct thread_data *td;
1341         unsigned long spent;
1342         unsigned int i, todo, nr_running, m_rate, t_rate, nr_started;
1343
1344         if (fio_pin_memory())
1345                 return;
1346
1347         if (fio_gtod_offload && fio_start_gtod_thread())
1348                 return;
1349
1350         set_sig_handlers();
1351
1352         if (!terse_output) {
1353                 log_info("Starting ");
1354                 if (nr_thread)
1355                         log_info("%d thread%s", nr_thread,
1356                                                 nr_thread > 1 ? "s" : "");
1357                 if (nr_process) {
1358                         if (nr_thread)
1359                                 log_info(" and ");
1360                         log_info("%d process%s", nr_process,
1361                                                 nr_process > 1 ? "es" : "");
1362                 }
1363                 log_info("\n");
1364                 fflush(stdout);
1365         }
1366
1367         todo = thread_number;
1368         nr_running = 0;
1369         nr_started = 0;
1370         m_rate = t_rate = 0;
1371
1372         for_each_td(td, i) {
1373                 print_status_init(td->thread_number - 1);
1374
1375                 if (!td->o.create_serialize)
1376                         continue;
1377
1378                 /*
1379                  * do file setup here so it happens sequentially,
1380                  * we don't want X number of threads getting their
1381                  * client data interspersed on disk
1382                  */
1383                 if (setup_files(td)) {
1384                         exit_value++;
1385                         if (td->error)
1386                                 log_err("fio: pid=%d, err=%d/%s\n",
1387                                         (int) td->pid, td->error, td->verror);
1388                         td_set_runstate(td, TD_REAPED);
1389                         todo--;
1390                 } else {
1391                         struct fio_file *f;
1392                         unsigned int j;
1393
1394                         /*
1395                          * for sharing to work, each job must always open
1396                          * its own files. so close them, if we opened them
1397                          * for creation
1398                          */
1399                         for_each_file(td, f, j) {
1400                                 if (fio_file_open(f))
1401                                         td_io_close_file(td, f);
1402                         }
1403                 }
1404         }
1405
1406         set_genesis_time();
1407
1408         while (todo) {
1409                 struct thread_data *map[REAL_MAX_JOBS];
1410                 struct timeval this_start;
1411                 int this_jobs = 0, left;
1412
1413                 /*
1414                  * create threads (TD_NOT_CREATED -> TD_CREATED)
1415                  */
1416                 for_each_td(td, i) {
1417                         if (td->runstate != TD_NOT_CREATED)
1418                                 continue;
1419
1420                         /*
1421                          * never got a chance to start, killed by other
1422                          * thread for some reason
1423                          */
1424                         if (td->terminate) {
1425                                 todo--;
1426                                 continue;
1427                         }
1428
1429                         if (td->o.start_delay) {
1430                                 spent = mtime_since_genesis();
1431
1432                                 if (td->o.start_delay * 1000 > spent)
1433                                         continue;
1434                         }
1435
1436                         if (td->o.stonewall && (nr_started || nr_running)) {
1437                                 dprint(FD_PROCESS, "%s: stonewall wait\n",
1438                                                         td->o.name);
1439                                 break;
1440                         }
1441
1442                         init_disk_util(td);
1443
1444                         /*
1445                          * Set state to created. Thread will transition
1446                          * to TD_INITIALIZED when it's done setting up.
1447                          */
1448                         td_set_runstate(td, TD_CREATED);
1449                         map[this_jobs++] = td;
1450                         nr_started++;
1451
1452                         if (td->o.use_thread) {
1453                                 int ret;
1454
1455                                 dprint(FD_PROCESS, "will pthread_create\n");
1456                                 ret = pthread_create(&td->thread, NULL,
1457                                                         thread_main, td);
1458                                 if (ret) {
1459                                         log_err("pthread_create: %s\n",
1460                                                         strerror(ret));
1461                                         nr_started--;
1462                                         break;
1463                                 }
1464                                 ret = pthread_detach(td->thread);
1465                                 if (ret)
1466                                         log_err("pthread_detach: %s",
1467                                                         strerror(ret));
1468                         } else {
1469                                 pid_t pid;
1470                                 dprint(FD_PROCESS, "will fork\n");
1471                                 pid = fork();
1472                                 if (!pid) {
1473                                         int ret = fork_main(shm_id, i);
1474
1475                                         _exit(ret);
1476                                 } else if (i == fio_debug_jobno)
1477                                         *fio_debug_jobp = pid;
1478                         }
1479                         dprint(FD_MUTEX, "wait on startup_mutex\n");
1480                         if (fio_mutex_down_timeout(startup_mutex, 10)) {
1481                                 log_err("fio: job startup hung? exiting.\n");
1482                                 fio_terminate_threads(TERMINATE_ALL);
1483                                 fio_abort = 1;
1484                                 nr_started--;
1485                                 break;
1486                         }
1487                         dprint(FD_MUTEX, "done waiting on startup_mutex\n");
1488                 }
1489
1490                 /*
1491                  * Wait for the started threads to transition to
1492                  * TD_INITIALIZED.
1493                  */
1494                 fio_gettime(&this_start, NULL);
1495                 left = this_jobs;
1496                 while (left && !fio_abort) {
1497                         if (mtime_since_now(&this_start) > JOB_START_TIMEOUT)
1498                                 break;
1499
1500                         usleep(100000);
1501
1502                         for (i = 0; i < this_jobs; i++) {
1503                                 td = map[i];
1504                                 if (!td)
1505                                         continue;
1506                                 if (td->runstate == TD_INITIALIZED) {
1507                                         map[i] = NULL;
1508                                         left--;
1509                                 } else if (td->runstate >= TD_EXITED) {
1510                                         map[i] = NULL;
1511                                         left--;
1512                                         todo--;
1513                                         nr_running++; /* work-around... */
1514                                 }
1515                         }
1516                 }
1517
1518                 if (left) {
1519                         log_err("fio: %d job%s failed to start\n", left,
1520                                         left > 1 ? "s" : "");
1521                         for (i = 0; i < this_jobs; i++) {
1522                                 td = map[i];
1523                                 if (!td)
1524                                         continue;
1525                                 kill(td->pid, SIGTERM);
1526                         }
1527                         break;
1528                 }
1529
1530                 /*
1531                  * start created threads (TD_INITIALIZED -> TD_RUNNING).
1532                  */
1533                 for_each_td(td, i) {
1534                         if (td->runstate != TD_INITIALIZED)
1535                                 continue;
1536
1537                         if (in_ramp_time(td))
1538                                 td_set_runstate(td, TD_RAMP);
1539                         else
1540                                 td_set_runstate(td, TD_RUNNING);
1541                         nr_running++;
1542                         nr_started--;
1543                         m_rate += td->o.ratemin[0] + td->o.ratemin[1];
1544                         t_rate += td->o.rate[0] + td->o.rate[1];
1545                         todo--;
1546                         fio_mutex_up(td->mutex);
1547                 }
1548
1549                 reap_threads(&nr_running, &t_rate, &m_rate);
1550
1551                 if (todo) {
1552                         if (is_backend)
1553                                 fio_server_idle_loop();
1554                         else
1555                                 usleep(100000);
1556                 }
1557         }
1558
1559         while (nr_running) {
1560                 reap_threads(&nr_running, &t_rate, &m_rate);
1561
1562                 if (is_backend)
1563                         fio_server_idle_loop();
1564                 else
1565                         usleep(10000);
1566         }
1567
1568         update_io_ticks();
1569         fio_unpin_memory();
1570 }
1571
1572 static void *disk_thread_main(void *data)
1573 {
1574         fio_mutex_up(startup_mutex);
1575
1576         while (threads) {
1577                 usleep(DISK_UTIL_MSEC * 1000);
1578                 if (!threads)
1579                         break;
1580                 update_io_ticks();
1581
1582                 if (!is_backend)
1583                         print_thread_status();
1584         }
1585
1586         return NULL;
1587 }
1588
1589 static int create_disk_util_thread(void)
1590 {
1591         int ret;
1592
1593         ret = pthread_create(&disk_util_thread, NULL, disk_thread_main, NULL);
1594         if (ret) {
1595                 log_err("Can't create disk util thread: %s\n", strerror(ret));
1596                 return 1;
1597         }
1598
1599         ret = pthread_detach(disk_util_thread);
1600         if (ret) {
1601                 log_err("Can't detatch disk util thread: %s\n", strerror(ret));
1602                 return 1;
1603         }
1604
1605         dprint(FD_MUTEX, "wait on startup_mutex\n");
1606         fio_mutex_down(startup_mutex);
1607         dprint(FD_MUTEX, "done waiting on startup_mutex\n");
1608         return 0;
1609 }
1610
1611 int fio_backend(void)
1612 {
1613         struct thread_data *td;
1614         int i;
1615
1616         if (exec_profile) {
1617                 if (load_profile(exec_profile))
1618                         return 1;
1619                 free(exec_profile);
1620                 exec_profile = NULL;
1621         }
1622         if (!thread_number)
1623                 return 0;
1624
1625         if (write_bw_log) {
1626                 setup_log(&agg_io_log[DDIR_READ], 0, IO_LOG_TYPE_BW);
1627                 setup_log(&agg_io_log[DDIR_WRITE], 0, IO_LOG_TYPE_BW);
1628         }
1629
1630         startup_mutex = fio_mutex_init(0);
1631         if (startup_mutex == NULL)
1632                 return 1;
1633         writeout_mutex = fio_mutex_init(1);
1634         if (writeout_mutex == NULL)
1635                 return 1;
1636
1637         set_genesis_time();
1638         create_disk_util_thread();
1639
1640         cgroup_list = smalloc(sizeof(*cgroup_list));
1641         INIT_FLIST_HEAD(cgroup_list);
1642
1643         run_threads();
1644
1645         if (!fio_abort) {
1646                 show_run_stats();
1647                 if (write_bw_log) {
1648                         __finish_log(agg_io_log[DDIR_READ], "agg-read_bw.log");
1649                         __finish_log(agg_io_log[DDIR_WRITE],
1650                                         "agg-write_bw.log");
1651                 }
1652         }
1653
1654         for_each_td(td, i)
1655                 fio_options_free(td);
1656
1657         cgroup_kill(cgroup_list);
1658         sfree(cgroup_list);
1659         sfree(cgroup_mnt);
1660
1661         fio_mutex_remove(startup_mutex);
1662         fio_mutex_remove(writeout_mutex);
1663         return exit_value;
1664 }