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