Refactor fio_show_ioengine_help()
[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/mman.h>
38 #include <math.h>
39
40 #include "fio.h"
41 #ifndef FIO_NO_HAVE_SHM_H
42 #include <sys/shm.h>
43 #endif
44 #include "hash.h"
45 #include "smalloc.h"
46 #include "verify.h"
47 #include "trim.h"
48 #include "diskutil.h"
49 #include "cgroup.h"
50 #include "profile.h"
51 #include "lib/rand.h"
52 #include "lib/memalign.h"
53 #include "server.h"
54 #include "lib/getrusage.h"
55 #include "idletime.h"
56 #include "err.h"
57 #include "workqueue.h"
58 #include "lib/mountcheck.h"
59 #include "rate-submit.h"
60 #include "helper_thread.h"
61
62 static struct fio_mutex *startup_mutex;
63 static struct flist_head *cgroup_list;
64 static char *cgroup_mnt;
65 static int exit_value;
66 static volatile int fio_abort;
67 static unsigned int nr_process = 0;
68 static unsigned int nr_thread = 0;
69
70 struct io_log *agg_io_log[DDIR_RWDIR_CNT];
71
72 int groupid = 0;
73 unsigned int thread_number = 0;
74 unsigned int stat_number = 0;
75 int shm_id = 0;
76 int temp_stall_ts;
77 unsigned long done_secs = 0;
78
79 #define PAGE_ALIGN(buf) \
80         (char *) (((uintptr_t) (buf) + page_mask) & ~page_mask)
81
82 #define JOB_START_TIMEOUT       (5 * 1000)
83
84 static void sig_int(int sig)
85 {
86         if (threads) {
87                 if (is_backend)
88                         fio_server_got_signal(sig);
89                 else {
90                         log_info("\nfio: terminating on signal %d\n", sig);
91                         log_info_flush();
92                         exit_value = 128;
93                 }
94
95                 fio_terminate_threads(TERMINATE_ALL);
96         }
97 }
98
99 void sig_show_status(int sig)
100 {
101         show_running_run_stats();
102 }
103
104 static void set_sig_handlers(void)
105 {
106         struct sigaction act;
107
108         memset(&act, 0, sizeof(act));
109         act.sa_handler = sig_int;
110         act.sa_flags = SA_RESTART;
111         sigaction(SIGINT, &act, NULL);
112
113         memset(&act, 0, sizeof(act));
114         act.sa_handler = sig_int;
115         act.sa_flags = SA_RESTART;
116         sigaction(SIGTERM, &act, NULL);
117
118 /* Windows uses SIGBREAK as a quit signal from other applications */
119 #ifdef WIN32
120         memset(&act, 0, sizeof(act));
121         act.sa_handler = sig_int;
122         act.sa_flags = SA_RESTART;
123         sigaction(SIGBREAK, &act, NULL);
124 #endif
125
126         memset(&act, 0, sizeof(act));
127         act.sa_handler = sig_show_status;
128         act.sa_flags = SA_RESTART;
129         sigaction(SIGUSR1, &act, NULL);
130
131         if (is_backend) {
132                 memset(&act, 0, sizeof(act));
133                 act.sa_handler = sig_int;
134                 act.sa_flags = SA_RESTART;
135                 sigaction(SIGPIPE, &act, NULL);
136         }
137 }
138
139 /*
140  * Check if we are above the minimum rate given.
141  */
142 static bool __check_min_rate(struct thread_data *td, struct timeval *now,
143                              enum fio_ddir ddir)
144 {
145         unsigned long long bytes = 0;
146         unsigned long iops = 0;
147         unsigned long spent;
148         unsigned long rate;
149         unsigned int ratemin = 0;
150         unsigned int rate_iops = 0;
151         unsigned int rate_iops_min = 0;
152
153         assert(ddir_rw(ddir));
154
155         if (!td->o.ratemin[ddir] && !td->o.rate_iops_min[ddir])
156                 return false;
157
158         /*
159          * allow a 2 second settle period in the beginning
160          */
161         if (mtime_since(&td->start, now) < 2000)
162                 return false;
163
164         iops += td->this_io_blocks[ddir];
165         bytes += td->this_io_bytes[ddir];
166         ratemin += td->o.ratemin[ddir];
167         rate_iops += td->o.rate_iops[ddir];
168         rate_iops_min += td->o.rate_iops_min[ddir];
169
170         /*
171          * if rate blocks is set, sample is running
172          */
173         if (td->rate_bytes[ddir] || td->rate_blocks[ddir]) {
174                 spent = mtime_since(&td->lastrate[ddir], now);
175                 if (spent < td->o.ratecycle)
176                         return false;
177
178                 if (td->o.rate[ddir] || td->o.ratemin[ddir]) {
179                         /*
180                          * check bandwidth specified rate
181                          */
182                         if (bytes < td->rate_bytes[ddir]) {
183                                 log_err("%s: rate_min=%uB/s not met, only transferred %lluB\n",
184                                         td->o.name, ratemin, bytes);
185                                 return true;
186                         } else {
187                                 if (spent)
188                                         rate = ((bytes - td->rate_bytes[ddir]) * 1000) / spent;
189                                 else
190                                         rate = 0;
191
192                                 if (rate < ratemin ||
193                                     bytes < td->rate_bytes[ddir]) {
194                                         log_err("%s: rate_min=%uB/s not met, got %luB/s\n",
195                                                 td->o.name, ratemin, rate);
196                                         return true;
197                                 }
198                         }
199                 } else {
200                         /*
201                          * checks iops specified rate
202                          */
203                         if (iops < rate_iops) {
204                                 log_err("%s: rate_iops_min=%u not met, only performed %lu IOs\n",
205                                                 td->o.name, rate_iops, iops);
206                                 return true;
207                         } else {
208                                 if (spent)
209                                         rate = ((iops - td->rate_blocks[ddir]) * 1000) / spent;
210                                 else
211                                         rate = 0;
212
213                                 if (rate < rate_iops_min ||
214                                     iops < td->rate_blocks[ddir]) {
215                                         log_err("%s: rate_iops_min=%u not met, got %lu IOPS\n",
216                                                 td->o.name, rate_iops_min, rate);
217                                         return true;
218                                 }
219                         }
220                 }
221         }
222
223         td->rate_bytes[ddir] = bytes;
224         td->rate_blocks[ddir] = iops;
225         memcpy(&td->lastrate[ddir], now, sizeof(*now));
226         return false;
227 }
228
229 static bool check_min_rate(struct thread_data *td, struct timeval *now)
230 {
231         bool ret = false;
232
233         if (td->bytes_done[DDIR_READ])
234                 ret |= __check_min_rate(td, now, DDIR_READ);
235         if (td->bytes_done[DDIR_WRITE])
236                 ret |= __check_min_rate(td, now, DDIR_WRITE);
237         if (td->bytes_done[DDIR_TRIM])
238                 ret |= __check_min_rate(td, now, DDIR_TRIM);
239
240         return ret;
241 }
242
243 /*
244  * When job exits, we can cancel the in-flight IO if we are using async
245  * io. Attempt to do so.
246  */
247 static void cleanup_pending_aio(struct thread_data *td)
248 {
249         int r;
250
251         /*
252          * get immediately available events, if any
253          */
254         r = io_u_queued_complete(td, 0);
255         if (r < 0)
256                 return;
257
258         /*
259          * now cancel remaining active events
260          */
261         if (td->io_ops->cancel) {
262                 struct io_u *io_u;
263                 int i;
264
265                 io_u_qiter(&td->io_u_all, io_u, i) {
266                         if (io_u->flags & IO_U_F_FLIGHT) {
267                                 r = td->io_ops->cancel(td, io_u);
268                                 if (!r)
269                                         put_io_u(td, io_u);
270                         }
271                 }
272         }
273
274         if (td->cur_depth)
275                 r = io_u_queued_complete(td, td->cur_depth);
276 }
277
278 /*
279  * Helper to handle the final sync of a file. Works just like the normal
280  * io path, just does everything sync.
281  */
282 static bool fio_io_sync(struct thread_data *td, struct fio_file *f)
283 {
284         struct io_u *io_u = __get_io_u(td);
285         int ret;
286
287         if (!io_u)
288                 return true;
289
290         io_u->ddir = DDIR_SYNC;
291         io_u->file = f;
292
293         if (td_io_prep(td, io_u)) {
294                 put_io_u(td, io_u);
295                 return true;
296         }
297
298 requeue:
299         ret = td_io_queue(td, io_u);
300         if (ret < 0) {
301                 td_verror(td, io_u->error, "td_io_queue");
302                 put_io_u(td, io_u);
303                 return true;
304         } else if (ret == FIO_Q_QUEUED) {
305                 if (td_io_commit(td))
306                         return true;
307                 if (io_u_queued_complete(td, 1) < 0)
308                         return true;
309         } else if (ret == FIO_Q_COMPLETED) {
310                 if (io_u->error) {
311                         td_verror(td, io_u->error, "td_io_queue");
312                         return true;
313                 }
314
315                 if (io_u_sync_complete(td, io_u) < 0)
316                         return true;
317         } else if (ret == FIO_Q_BUSY) {
318                 if (td_io_commit(td))
319                         return true;
320                 goto requeue;
321         }
322
323         return false;
324 }
325
326 static int fio_file_fsync(struct thread_data *td, struct fio_file *f)
327 {
328         int ret;
329
330         if (fio_file_open(f))
331                 return fio_io_sync(td, f);
332
333         if (td_io_open_file(td, f))
334                 return 1;
335
336         ret = fio_io_sync(td, f);
337         td_io_close_file(td, f);
338         return ret;
339 }
340
341 static inline void __update_tv_cache(struct thread_data *td)
342 {
343         fio_gettime(&td->tv_cache, NULL);
344 }
345
346 static inline void update_tv_cache(struct thread_data *td)
347 {
348         if ((++td->tv_cache_nr & td->tv_cache_mask) == td->tv_cache_mask)
349                 __update_tv_cache(td);
350 }
351
352 static inline bool runtime_exceeded(struct thread_data *td, struct timeval *t)
353 {
354         if (in_ramp_time(td))
355                 return false;
356         if (!td->o.timeout)
357                 return false;
358         if (utime_since(&td->epoch, t) >= td->o.timeout)
359                 return true;
360
361         return false;
362 }
363
364 /*
365  * We need to update the runtime consistently in ms, but keep a running
366  * tally of the current elapsed time in microseconds for sub millisecond
367  * updates.
368  */
369 static inline void update_runtime(struct thread_data *td,
370                                   unsigned long long *elapsed_us,
371                                   const enum fio_ddir ddir)
372 {
373         if (ddir == DDIR_WRITE && td_write(td) && td->o.verify_only)
374                 return;
375
376         td->ts.runtime[ddir] -= (elapsed_us[ddir] + 999) / 1000;
377         elapsed_us[ddir] += utime_since_now(&td->start);
378         td->ts.runtime[ddir] += (elapsed_us[ddir] + 999) / 1000;
379 }
380
381 static bool break_on_this_error(struct thread_data *td, enum fio_ddir ddir,
382                                 int *retptr)
383 {
384         int ret = *retptr;
385
386         if (ret < 0 || td->error) {
387                 int err = td->error;
388                 enum error_type_bit eb;
389
390                 if (ret < 0)
391                         err = -ret;
392
393                 eb = td_error_type(ddir, err);
394                 if (!(td->o.continue_on_error & (1 << eb)))
395                         return true;
396
397                 if (td_non_fatal_error(td, eb, err)) {
398                         /*
399                          * Continue with the I/Os in case of
400                          * a non fatal error.
401                          */
402                         update_error_count(td, err);
403                         td_clear_error(td);
404                         *retptr = 0;
405                         return false;
406                 } else if (td->o.fill_device && err == ENOSPC) {
407                         /*
408                          * We expect to hit this error if
409                          * fill_device option is set.
410                          */
411                         td_clear_error(td);
412                         fio_mark_td_terminate(td);
413                         return true;
414                 } else {
415                         /*
416                          * Stop the I/O in case of a fatal
417                          * error.
418                          */
419                         update_error_count(td, err);
420                         return true;
421                 }
422         }
423
424         return false;
425 }
426
427 static void check_update_rusage(struct thread_data *td)
428 {
429         if (td->update_rusage) {
430                 td->update_rusage = 0;
431                 update_rusage_stat(td);
432                 fio_mutex_up(td->rusage_sem);
433         }
434 }
435
436 static int wait_for_completions(struct thread_data *td, struct timeval *time)
437 {
438         const int full = queue_full(td);
439         int min_evts = 0;
440         int ret;
441
442         if (td->flags & TD_F_REGROW_LOGS)
443                 return io_u_quiesce(td);
444
445         /*
446          * if the queue is full, we MUST reap at least 1 event
447          */
448         min_evts = min(td->o.iodepth_batch_complete_min, td->cur_depth);
449         if ((full && !min_evts) || !td->o.iodepth_batch_complete_min)
450                 min_evts = 1;
451
452         if (time && (__should_check_rate(td, DDIR_READ) ||
453             __should_check_rate(td, DDIR_WRITE) ||
454             __should_check_rate(td, DDIR_TRIM)))
455                 fio_gettime(time, NULL);
456
457         do {
458                 ret = io_u_queued_complete(td, min_evts);
459                 if (ret < 0)
460                         break;
461         } while (full && (td->cur_depth > td->o.iodepth_low));
462
463         return ret;
464 }
465
466 int io_queue_event(struct thread_data *td, struct io_u *io_u, int *ret,
467                    enum fio_ddir ddir, uint64_t *bytes_issued, int from_verify,
468                    struct timeval *comp_time)
469 {
470         int ret2;
471
472         switch (*ret) {
473         case FIO_Q_COMPLETED:
474                 if (io_u->error) {
475                         *ret = -io_u->error;
476                         clear_io_u(td, io_u);
477                 } else if (io_u->resid) {
478                         int bytes = io_u->xfer_buflen - io_u->resid;
479                         struct fio_file *f = io_u->file;
480
481                         if (bytes_issued)
482                                 *bytes_issued += bytes;
483
484                         if (!from_verify)
485                                 trim_io_piece(td, io_u);
486
487                         /*
488                          * zero read, fail
489                          */
490                         if (!bytes) {
491                                 if (!from_verify)
492                                         unlog_io_piece(td, io_u);
493                                 td_verror(td, EIO, "full resid");
494                                 put_io_u(td, io_u);
495                                 break;
496                         }
497
498                         io_u->xfer_buflen = io_u->resid;
499                         io_u->xfer_buf += bytes;
500                         io_u->offset += bytes;
501
502                         if (ddir_rw(io_u->ddir))
503                                 td->ts.short_io_u[io_u->ddir]++;
504
505                         f = io_u->file;
506                         if (io_u->offset == f->real_file_size)
507                                 goto sync_done;
508
509                         requeue_io_u(td, &io_u);
510                 } else {
511 sync_done:
512                         if (comp_time && (__should_check_rate(td, DDIR_READ) ||
513                             __should_check_rate(td, DDIR_WRITE) ||
514                             __should_check_rate(td, DDIR_TRIM)))
515                                 fio_gettime(comp_time, NULL);
516
517                         *ret = io_u_sync_complete(td, io_u);
518                         if (*ret < 0)
519                                 break;
520                 }
521
522                 if (td->flags & TD_F_REGROW_LOGS)
523                         regrow_logs(td);
524
525                 /*
526                  * when doing I/O (not when verifying),
527                  * check for any errors that are to be ignored
528                  */
529                 if (!from_verify)
530                         break;
531
532                 return 0;
533         case FIO_Q_QUEUED:
534                 /*
535                  * if the engine doesn't have a commit hook,
536                  * the io_u is really queued. if it does have such
537                  * a hook, it has to call io_u_queued() itself.
538                  */
539                 if (td->io_ops->commit == NULL)
540                         io_u_queued(td, io_u);
541                 if (bytes_issued)
542                         *bytes_issued += io_u->xfer_buflen;
543                 break;
544         case FIO_Q_BUSY:
545                 if (!from_verify)
546                         unlog_io_piece(td, io_u);
547                 requeue_io_u(td, &io_u);
548                 ret2 = td_io_commit(td);
549                 if (ret2 < 0)
550                         *ret = ret2;
551                 break;
552         default:
553                 assert(*ret < 0);
554                 td_verror(td, -(*ret), "td_io_queue");
555                 break;
556         }
557
558         if (break_on_this_error(td, ddir, ret))
559                 return 1;
560
561         return 0;
562 }
563
564 static inline bool io_in_polling(struct thread_data *td)
565 {
566         return !td->o.iodepth_batch_complete_min &&
567                    !td->o.iodepth_batch_complete_max;
568 }
569 /*
570  * Unlinks files from thread data fio_file structure
571  */
572 static int unlink_all_files(struct thread_data *td)
573 {
574         struct fio_file *f;
575         unsigned int i;
576         int ret = 0;
577
578         for_each_file(td, f, i) {
579                 if (f->filetype != FIO_TYPE_FILE)
580                         continue;
581                 ret = td_io_unlink_file(td, f);
582                 if (ret)
583                         break;
584         }
585
586         if (ret)
587                 td_verror(td, ret, "unlink_all_files");
588
589         return ret;
590 }
591
592 /*
593  * The main verify engine. Runs over the writes we previously submitted,
594  * reads the blocks back in, and checks the crc/md5 of the data.
595  */
596 static void do_verify(struct thread_data *td, uint64_t verify_bytes)
597 {
598         struct fio_file *f;
599         struct io_u *io_u;
600         int ret, min_events;
601         unsigned int i;
602
603         dprint(FD_VERIFY, "starting loop\n");
604
605         /*
606          * sync io first and invalidate cache, to make sure we really
607          * read from disk.
608          */
609         for_each_file(td, f, i) {
610                 if (!fio_file_open(f))
611                         continue;
612                 if (fio_io_sync(td, f))
613                         break;
614                 if (file_invalidate_cache(td, f))
615                         break;
616         }
617
618         check_update_rusage(td);
619
620         if (td->error)
621                 return;
622
623         /*
624          * verify_state needs to be reset before verification
625          * proceeds so that expected random seeds match actual
626          * random seeds in headers. The main loop will reset
627          * all random number generators if randrepeat is set.
628          */
629         if (!td->o.rand_repeatable)
630                 td_fill_verify_state_seed(td);
631
632         td_set_runstate(td, TD_VERIFYING);
633
634         io_u = NULL;
635         while (!td->terminate) {
636                 enum fio_ddir ddir;
637                 int full;
638
639                 update_tv_cache(td);
640                 check_update_rusage(td);
641
642                 if (runtime_exceeded(td, &td->tv_cache)) {
643                         __update_tv_cache(td);
644                         if (runtime_exceeded(td, &td->tv_cache)) {
645                                 fio_mark_td_terminate(td);
646                                 break;
647                         }
648                 }
649
650                 if (flow_threshold_exceeded(td))
651                         continue;
652
653                 if (!td->o.experimental_verify) {
654                         io_u = __get_io_u(td);
655                         if (!io_u)
656                                 break;
657
658                         if (get_next_verify(td, io_u)) {
659                                 put_io_u(td, io_u);
660                                 break;
661                         }
662
663                         if (td_io_prep(td, io_u)) {
664                                 put_io_u(td, io_u);
665                                 break;
666                         }
667                 } else {
668                         if (ddir_rw_sum(td->bytes_done) + td->o.rw_min_bs > verify_bytes)
669                                 break;
670
671                         while ((io_u = get_io_u(td)) != NULL) {
672                                 if (IS_ERR_OR_NULL(io_u)) {
673                                         io_u = NULL;
674                                         ret = FIO_Q_BUSY;
675                                         goto reap;
676                                 }
677
678                                 /*
679                                  * We are only interested in the places where
680                                  * we wrote or trimmed IOs. Turn those into
681                                  * reads for verification purposes.
682                                  */
683                                 if (io_u->ddir == DDIR_READ) {
684                                         /*
685                                          * Pretend we issued it for rwmix
686                                          * accounting
687                                          */
688                                         td->io_issues[DDIR_READ]++;
689                                         put_io_u(td, io_u);
690                                         continue;
691                                 } else if (io_u->ddir == DDIR_TRIM) {
692                                         io_u->ddir = DDIR_READ;
693                                         io_u_set(td, io_u, IO_U_F_TRIMMED);
694                                         break;
695                                 } else if (io_u->ddir == DDIR_WRITE) {
696                                         io_u->ddir = DDIR_READ;
697                                         break;
698                                 } else {
699                                         put_io_u(td, io_u);
700                                         continue;
701                                 }
702                         }
703
704                         if (!io_u)
705                                 break;
706                 }
707
708                 if (verify_state_should_stop(td, io_u)) {
709                         put_io_u(td, io_u);
710                         break;
711                 }
712
713                 if (td->o.verify_async)
714                         io_u->end_io = verify_io_u_async;
715                 else
716                         io_u->end_io = verify_io_u;
717
718                 ddir = io_u->ddir;
719                 if (!td->o.disable_slat)
720                         fio_gettime(&io_u->start_time, NULL);
721
722                 ret = td_io_queue(td, io_u);
723
724                 if (io_queue_event(td, io_u, &ret, ddir, NULL, 1, NULL))
725                         break;
726
727                 /*
728                  * if we can queue more, do so. but check if there are
729                  * completed io_u's first. Note that we can get BUSY even
730                  * without IO queued, if the system is resource starved.
731                  */
732 reap:
733                 full = queue_full(td) || (ret == FIO_Q_BUSY && td->cur_depth);
734                 if (full || io_in_polling(td))
735                         ret = wait_for_completions(td, NULL);
736
737                 if (ret < 0)
738                         break;
739         }
740
741         check_update_rusage(td);
742
743         if (!td->error) {
744                 min_events = td->cur_depth;
745
746                 if (min_events)
747                         ret = io_u_queued_complete(td, min_events);
748         } else
749                 cleanup_pending_aio(td);
750
751         td_set_runstate(td, TD_RUNNING);
752
753         dprint(FD_VERIFY, "exiting loop\n");
754 }
755
756 static bool exceeds_number_ios(struct thread_data *td)
757 {
758         unsigned long long number_ios;
759
760         if (!td->o.number_ios)
761                 return false;
762
763         number_ios = ddir_rw_sum(td->io_blocks);
764         number_ios += td->io_u_queued + td->io_u_in_flight;
765
766         return number_ios >= (td->o.number_ios * td->loops);
767 }
768
769 static bool io_bytes_exceeded(struct thread_data *td, uint64_t *this_bytes)
770 {
771         unsigned long long bytes, limit;
772
773         if (td_rw(td))
774                 bytes = this_bytes[DDIR_READ] + this_bytes[DDIR_WRITE];
775         else if (td_write(td))
776                 bytes = this_bytes[DDIR_WRITE];
777         else if (td_read(td))
778                 bytes = this_bytes[DDIR_READ];
779         else
780                 bytes = this_bytes[DDIR_TRIM];
781
782         if (td->o.io_limit)
783                 limit = td->o.io_limit;
784         else
785                 limit = td->o.size;
786
787         limit *= td->loops;
788         return bytes >= limit || exceeds_number_ios(td);
789 }
790
791 static bool io_issue_bytes_exceeded(struct thread_data *td)
792 {
793         return io_bytes_exceeded(td, td->io_issue_bytes);
794 }
795
796 static bool io_complete_bytes_exceeded(struct thread_data *td)
797 {
798         return io_bytes_exceeded(td, td->this_io_bytes);
799 }
800
801 /*
802  * used to calculate the next io time for rate control
803  *
804  */
805 static long long usec_for_io(struct thread_data *td, enum fio_ddir ddir)
806 {
807         uint64_t secs, remainder, bps, bytes, iops;
808
809         assert(!(td->flags & TD_F_CHILD));
810         bytes = td->rate_io_issue_bytes[ddir];
811         bps = td->rate_bps[ddir];
812
813         if (td->o.rate_process == RATE_PROCESS_POISSON) {
814                 uint64_t val;
815                 iops = bps / td->o.bs[ddir];
816                 val = (int64_t) (1000000 / iops) *
817                                 -logf(__rand_0_1(&td->poisson_state));
818                 if (val) {
819                         dprint(FD_RATE, "poisson rate iops=%llu\n",
820                                         (unsigned long long) 1000000 / val);
821                 }
822                 td->last_usec += val;
823                 return td->last_usec;
824         } else if (bps) {
825                 secs = bytes / bps;
826                 remainder = bytes % bps;
827                 return remainder * 1000000 / bps + secs * 1000000;
828         }
829
830         return 0;
831 }
832
833 /*
834  * Main IO worker function. It retrieves io_u's to process and queues
835  * and reaps them, checking for rate and errors along the way.
836  *
837  * Returns number of bytes written and trimmed.
838  */
839 static void do_io(struct thread_data *td, uint64_t *bytes_done)
840 {
841         unsigned int i;
842         int ret = 0;
843         uint64_t total_bytes, bytes_issued = 0;
844
845         for (i = 0; i < DDIR_RWDIR_CNT; i++)
846                 bytes_done[i] = td->bytes_done[i];
847
848         if (in_ramp_time(td))
849                 td_set_runstate(td, TD_RAMP);
850         else
851                 td_set_runstate(td, TD_RUNNING);
852
853         lat_target_init(td);
854
855         total_bytes = td->o.size;
856         /*
857         * Allow random overwrite workloads to write up to io_limit
858         * before starting verification phase as 'size' doesn't apply.
859         */
860         if (td_write(td) && td_random(td) && td->o.norandommap)
861                 total_bytes = max(total_bytes, (uint64_t) td->o.io_limit);
862         /*
863          * If verify_backlog is enabled, we'll run the verify in this
864          * handler as well. For that case, we may need up to twice the
865          * amount of bytes.
866          */
867         if (td->o.verify != VERIFY_NONE &&
868            (td_write(td) && td->o.verify_backlog))
869                 total_bytes += td->o.size;
870
871         /* In trimwrite mode, each byte is trimmed and then written, so
872          * allow total_bytes to be twice as big */
873         if (td_trimwrite(td))
874                 total_bytes += td->total_io_size;
875
876         while ((td->o.read_iolog_file && !flist_empty(&td->io_log_list)) ||
877                 (!flist_empty(&td->trim_list)) || !io_issue_bytes_exceeded(td) ||
878                 td->o.time_based) {
879                 struct timeval comp_time;
880                 struct io_u *io_u;
881                 int full;
882                 enum fio_ddir ddir;
883
884                 check_update_rusage(td);
885
886                 if (td->terminate || td->done)
887                         break;
888
889                 update_tv_cache(td);
890
891                 if (runtime_exceeded(td, &td->tv_cache)) {
892                         __update_tv_cache(td);
893                         if (runtime_exceeded(td, &td->tv_cache)) {
894                                 fio_mark_td_terminate(td);
895                                 break;
896                         }
897                 }
898
899                 if (flow_threshold_exceeded(td))
900                         continue;
901
902                 /*
903                  * Break if we exceeded the bytes. The exception is time
904                  * based runs, but we still need to break out of the loop
905                  * for those to run verification, if enabled.
906                  */
907                 if (bytes_issued >= total_bytes &&
908                     (!td->o.time_based ||
909                      (td->o.time_based && td->o.verify != VERIFY_NONE)))
910                         break;
911
912                 io_u = get_io_u(td);
913                 if (IS_ERR_OR_NULL(io_u)) {
914                         int err = PTR_ERR(io_u);
915
916                         io_u = NULL;
917                         if (err == -EBUSY) {
918                                 ret = FIO_Q_BUSY;
919                                 goto reap;
920                         }
921                         if (td->o.latency_target)
922                                 goto reap;
923                         break;
924                 }
925
926                 ddir = io_u->ddir;
927
928                 /*
929                  * Add verification end_io handler if:
930                  *      - Asked to verify (!td_rw(td))
931                  *      - Or the io_u is from our verify list (mixed write/ver)
932                  */
933                 if (td->o.verify != VERIFY_NONE && io_u->ddir == DDIR_READ &&
934                     ((io_u->flags & IO_U_F_VER_LIST) || !td_rw(td))) {
935
936                         if (!td->o.verify_pattern_bytes) {
937                                 io_u->rand_seed = __rand(&td->verify_state);
938                                 if (sizeof(int) != sizeof(long *))
939                                         io_u->rand_seed *= __rand(&td->verify_state);
940                         }
941
942                         if (verify_state_should_stop(td, io_u)) {
943                                 put_io_u(td, io_u);
944                                 break;
945                         }
946
947                         if (td->o.verify_async)
948                                 io_u->end_io = verify_io_u_async;
949                         else
950                                 io_u->end_io = verify_io_u;
951                         td_set_runstate(td, TD_VERIFYING);
952                 } else if (in_ramp_time(td))
953                         td_set_runstate(td, TD_RAMP);
954                 else
955                         td_set_runstate(td, TD_RUNNING);
956
957                 /*
958                  * Always log IO before it's issued, so we know the specific
959                  * order of it. The logged unit will track when the IO has
960                  * completed.
961                  */
962                 if (td_write(td) && io_u->ddir == DDIR_WRITE &&
963                     td->o.do_verify &&
964                     td->o.verify != VERIFY_NONE &&
965                     !td->o.experimental_verify)
966                         log_io_piece(td, io_u);
967
968                 if (td->o.io_submit_mode == IO_MODE_OFFLOAD) {
969                         const unsigned long blen = io_u->xfer_buflen;
970                         const enum fio_ddir ddir = acct_ddir(io_u);
971
972                         if (td->error)
973                                 break;
974
975                         workqueue_enqueue(&td->io_wq, &io_u->work);
976                         ret = FIO_Q_QUEUED;
977
978                         if (ddir_rw(ddir)) {
979                                 td->io_issues[ddir]++;
980                                 td->io_issue_bytes[ddir] += blen;
981                                 td->rate_io_issue_bytes[ddir] += blen;
982                         }
983
984                         if (should_check_rate(td))
985                                 td->rate_next_io_time[ddir] = usec_for_io(td, ddir);
986
987                 } else {
988                         ret = td_io_queue(td, io_u);
989
990                         if (should_check_rate(td))
991                                 td->rate_next_io_time[ddir] = usec_for_io(td, ddir);
992
993                         if (io_queue_event(td, io_u, &ret, ddir, &bytes_issued, 0, &comp_time))
994                                 break;
995
996                         /*
997                          * See if we need to complete some commands. Note that
998                          * we can get BUSY even without IO queued, if the
999                          * system is resource starved.
1000                          */
1001 reap:
1002                         full = queue_full(td) ||
1003                                 (ret == FIO_Q_BUSY && td->cur_depth);
1004                         if (full || io_in_polling(td))
1005                                 ret = wait_for_completions(td, &comp_time);
1006                 }
1007                 if (ret < 0)
1008                         break;
1009                 if (!ddir_rw_sum(td->bytes_done) &&
1010                     !td_ioengine_flagged(td, FIO_NOIO))
1011                         continue;
1012
1013                 if (!in_ramp_time(td) && should_check_rate(td)) {
1014                         if (check_min_rate(td, &comp_time)) {
1015                                 if (exitall_on_terminate || td->o.exitall_error)
1016                                         fio_terminate_threads(td->groupid);
1017                                 td_verror(td, EIO, "check_min_rate");
1018                                 break;
1019                         }
1020                 }
1021                 if (!in_ramp_time(td) && td->o.latency_target)
1022                         lat_target_check(td);
1023
1024                 if (td->o.thinktime) {
1025                         unsigned long long b;
1026
1027                         b = ddir_rw_sum(td->io_blocks);
1028                         if (!(b % td->o.thinktime_blocks)) {
1029                                 int left;
1030
1031                                 io_u_quiesce(td);
1032
1033                                 if (td->o.thinktime_spin)
1034                                         usec_spin(td->o.thinktime_spin);
1035
1036                                 left = td->o.thinktime - td->o.thinktime_spin;
1037                                 if (left)
1038                                         usec_sleep(td, left);
1039                         }
1040                 }
1041         }
1042
1043         check_update_rusage(td);
1044
1045         if (td->trim_entries)
1046                 log_err("fio: %lu trim entries leaked?\n", td->trim_entries);
1047
1048         if (td->o.fill_device && td->error == ENOSPC) {
1049                 td->error = 0;
1050                 fio_mark_td_terminate(td);
1051         }
1052         if (!td->error) {
1053                 struct fio_file *f;
1054
1055                 if (td->o.io_submit_mode == IO_MODE_OFFLOAD) {
1056                         workqueue_flush(&td->io_wq);
1057                         i = 0;
1058                 } else
1059                         i = td->cur_depth;
1060
1061                 if (i) {
1062                         ret = io_u_queued_complete(td, i);
1063                         if (td->o.fill_device && td->error == ENOSPC)
1064                                 td->error = 0;
1065                 }
1066
1067                 if (should_fsync(td) && td->o.end_fsync) {
1068                         td_set_runstate(td, TD_FSYNCING);
1069
1070                         for_each_file(td, f, i) {
1071                                 if (!fio_file_fsync(td, f))
1072                                         continue;
1073
1074                                 log_err("fio: end_fsync failed for file %s\n",
1075                                                                 f->file_name);
1076                         }
1077                 }
1078         } else
1079                 cleanup_pending_aio(td);
1080
1081         /*
1082          * stop job if we failed doing any IO
1083          */
1084         if (!ddir_rw_sum(td->this_io_bytes))
1085                 td->done = 1;
1086
1087         for (i = 0; i < DDIR_RWDIR_CNT; i++)
1088                 bytes_done[i] = td->bytes_done[i] - bytes_done[i];
1089 }
1090
1091 static void free_file_completion_logging(struct thread_data *td)
1092 {
1093         struct fio_file *f;
1094         unsigned int i;
1095
1096         for_each_file(td, f, i) {
1097                 if (!f->last_write_comp)
1098                         break;
1099                 sfree(f->last_write_comp);
1100         }
1101 }
1102
1103 static int init_file_completion_logging(struct thread_data *td,
1104                                         unsigned int depth)
1105 {
1106         struct fio_file *f;
1107         unsigned int i;
1108
1109         if (td->o.verify == VERIFY_NONE || !td->o.verify_state_save)
1110                 return 0;
1111
1112         for_each_file(td, f, i) {
1113                 f->last_write_comp = scalloc(depth, sizeof(uint64_t));
1114                 if (!f->last_write_comp)
1115                         goto cleanup;
1116         }
1117
1118         return 0;
1119
1120 cleanup:
1121         free_file_completion_logging(td);
1122         log_err("fio: failed to alloc write comp data\n");
1123         return 1;
1124 }
1125
1126 static void cleanup_io_u(struct thread_data *td)
1127 {
1128         struct io_u *io_u;
1129
1130         while ((io_u = io_u_qpop(&td->io_u_freelist)) != NULL) {
1131
1132                 if (td->io_ops->io_u_free)
1133                         td->io_ops->io_u_free(td, io_u);
1134
1135                 fio_memfree(io_u, sizeof(*io_u));
1136         }
1137
1138         free_io_mem(td);
1139
1140         io_u_rexit(&td->io_u_requeues);
1141         io_u_qexit(&td->io_u_freelist);
1142         io_u_qexit(&td->io_u_all);
1143
1144         free_file_completion_logging(td);
1145 }
1146
1147 static int init_io_u(struct thread_data *td)
1148 {
1149         struct io_u *io_u;
1150         unsigned int max_bs, min_write;
1151         int cl_align, i, max_units;
1152         int data_xfer = 1, err;
1153         char *p;
1154
1155         max_units = td->o.iodepth;
1156         max_bs = td_max_bs(td);
1157         min_write = td->o.min_bs[DDIR_WRITE];
1158         td->orig_buffer_size = (unsigned long long) max_bs
1159                                         * (unsigned long long) max_units;
1160
1161         if (td_ioengine_flagged(td, FIO_NOIO) || !(td_read(td) || td_write(td)))
1162                 data_xfer = 0;
1163
1164         err = 0;
1165         err += io_u_rinit(&td->io_u_requeues, td->o.iodepth);
1166         err += io_u_qinit(&td->io_u_freelist, td->o.iodepth);
1167         err += io_u_qinit(&td->io_u_all, td->o.iodepth);
1168
1169         if (err) {
1170                 log_err("fio: failed setting up IO queues\n");
1171                 return 1;
1172         }
1173
1174         /*
1175          * if we may later need to do address alignment, then add any
1176          * possible adjustment here so that we don't cause a buffer
1177          * overflow later. this adjustment may be too much if we get
1178          * lucky and the allocator gives us an aligned address.
1179          */
1180         if (td->o.odirect || td->o.mem_align || td->o.oatomic ||
1181             td_ioengine_flagged(td, FIO_RAWIO))
1182                 td->orig_buffer_size += page_mask + td->o.mem_align;
1183
1184         if (td->o.mem_type == MEM_SHMHUGE || td->o.mem_type == MEM_MMAPHUGE) {
1185                 unsigned long bs;
1186
1187                 bs = td->orig_buffer_size + td->o.hugepage_size - 1;
1188                 td->orig_buffer_size = bs & ~(td->o.hugepage_size - 1);
1189         }
1190
1191         if (td->orig_buffer_size != (size_t) td->orig_buffer_size) {
1192                 log_err("fio: IO memory too large. Reduce max_bs or iodepth\n");
1193                 return 1;
1194         }
1195
1196         if (data_xfer && allocate_io_mem(td))
1197                 return 1;
1198
1199         if (td->o.odirect || td->o.mem_align || td->o.oatomic ||
1200             td_ioengine_flagged(td, FIO_RAWIO))
1201                 p = PAGE_ALIGN(td->orig_buffer) + td->o.mem_align;
1202         else
1203                 p = td->orig_buffer;
1204
1205         cl_align = os_cache_line_size();
1206
1207         for (i = 0; i < max_units; i++) {
1208                 void *ptr;
1209
1210                 if (td->terminate)
1211                         return 1;
1212
1213                 ptr = fio_memalign(cl_align, sizeof(*io_u));
1214                 if (!ptr) {
1215                         log_err("fio: unable to allocate aligned memory\n");
1216                         break;
1217                 }
1218
1219                 io_u = ptr;
1220                 memset(io_u, 0, sizeof(*io_u));
1221                 INIT_FLIST_HEAD(&io_u->verify_list);
1222                 dprint(FD_MEM, "io_u alloc %p, index %u\n", io_u, i);
1223
1224                 if (data_xfer) {
1225                         io_u->buf = p;
1226                         dprint(FD_MEM, "io_u %p, mem %p\n", io_u, io_u->buf);
1227
1228                         if (td_write(td))
1229                                 io_u_fill_buffer(td, io_u, min_write, max_bs);
1230                         if (td_write(td) && td->o.verify_pattern_bytes) {
1231                                 /*
1232                                  * Fill the buffer with the pattern if we are
1233                                  * going to be doing writes.
1234                                  */
1235                                 fill_verify_pattern(td, io_u->buf, max_bs, io_u, 0, 0);
1236                         }
1237                 }
1238
1239                 io_u->index = i;
1240                 io_u->flags = IO_U_F_FREE;
1241                 io_u_qpush(&td->io_u_freelist, io_u);
1242
1243                 /*
1244                  * io_u never leaves this stack, used for iteration of all
1245                  * io_u buffers.
1246                  */
1247                 io_u_qpush(&td->io_u_all, io_u);
1248
1249                 if (td->io_ops->io_u_init) {
1250                         int ret = td->io_ops->io_u_init(td, io_u);
1251
1252                         if (ret) {
1253                                 log_err("fio: failed to init engine data: %d\n", ret);
1254                                 return 1;
1255                         }
1256                 }
1257
1258                 p += max_bs;
1259         }
1260
1261         if (init_file_completion_logging(td, max_units))
1262                 return 1;
1263
1264         return 0;
1265 }
1266
1267 static int switch_ioscheduler(struct thread_data *td)
1268 {
1269 #ifdef FIO_HAVE_IOSCHED_SWITCH
1270         char tmp[256], tmp2[128];
1271         FILE *f;
1272         int ret;
1273
1274         if (td_ioengine_flagged(td, FIO_DISKLESSIO))
1275                 return 0;
1276
1277         sprintf(tmp, "%s/queue/scheduler", td->sysfs_root);
1278
1279         f = fopen(tmp, "r+");
1280         if (!f) {
1281                 if (errno == ENOENT) {
1282                         log_err("fio: os or kernel doesn't support IO scheduler"
1283                                 " switching\n");
1284                         return 0;
1285                 }
1286                 td_verror(td, errno, "fopen iosched");
1287                 return 1;
1288         }
1289
1290         /*
1291          * Set io scheduler.
1292          */
1293         ret = fwrite(td->o.ioscheduler, strlen(td->o.ioscheduler), 1, f);
1294         if (ferror(f) || ret != 1) {
1295                 td_verror(td, errno, "fwrite");
1296                 fclose(f);
1297                 return 1;
1298         }
1299
1300         rewind(f);
1301
1302         /*
1303          * Read back and check that the selected scheduler is now the default.
1304          */
1305         memset(tmp, 0, sizeof(tmp));
1306         ret = fread(tmp, sizeof(tmp), 1, f);
1307         if (ferror(f) || ret < 0) {
1308                 td_verror(td, errno, "fread");
1309                 fclose(f);
1310                 return 1;
1311         }
1312         /*
1313          * either a list of io schedulers or "none\n" is expected.
1314          */
1315         tmp[strlen(tmp) - 1] = '\0';
1316
1317         /*
1318          * Write to "none" entry doesn't fail, so check the result here.
1319          */
1320         if (!strcmp(tmp, "none")) {
1321                 log_err("fio: io scheduler is not tunable\n");
1322                 fclose(f);
1323                 return 0;
1324         }
1325
1326         sprintf(tmp2, "[%s]", td->o.ioscheduler);
1327         if (!strstr(tmp, tmp2)) {
1328                 log_err("fio: io scheduler %s not found\n", td->o.ioscheduler);
1329                 td_verror(td, EINVAL, "iosched_switch");
1330                 fclose(f);
1331                 return 1;
1332         }
1333
1334         fclose(f);
1335         return 0;
1336 #else
1337         return 0;
1338 #endif
1339 }
1340
1341 static bool keep_running(struct thread_data *td)
1342 {
1343         unsigned long long limit;
1344
1345         if (td->done)
1346                 return false;
1347         if (td->o.time_based)
1348                 return true;
1349         if (td->o.loops) {
1350                 td->o.loops--;
1351                 return true;
1352         }
1353         if (exceeds_number_ios(td))
1354                 return false;
1355
1356         if (td->o.io_limit)
1357                 limit = td->o.io_limit;
1358         else
1359                 limit = td->o.size;
1360
1361         if (limit != -1ULL && ddir_rw_sum(td->io_bytes) < limit) {
1362                 uint64_t diff;
1363
1364                 /*
1365                  * If the difference is less than the minimum IO size, we
1366                  * are done.
1367                  */
1368                 diff = limit - ddir_rw_sum(td->io_bytes);
1369                 if (diff < td_max_bs(td))
1370                         return false;
1371
1372                 if (fio_files_done(td) && !td->o.io_limit)
1373                         return false;
1374
1375                 return true;
1376         }
1377
1378         return false;
1379 }
1380
1381 static int exec_string(struct thread_options *o, const char *string, const char *mode)
1382 {
1383         size_t newlen = strlen(string) + strlen(o->name) + strlen(mode) + 9 + 1;
1384         int ret;
1385         char *str;
1386
1387         str = malloc(newlen);
1388         sprintf(str, "%s &> %s.%s.txt", string, o->name, mode);
1389
1390         log_info("%s : Saving output of %s in %s.%s.txt\n",o->name, mode, o->name, mode);
1391         ret = system(str);
1392         if (ret == -1)
1393                 log_err("fio: exec of cmd <%s> failed\n", str);
1394
1395         free(str);
1396         return ret;
1397 }
1398
1399 /*
1400  * Dry run to compute correct state of numberio for verification.
1401  */
1402 static uint64_t do_dry_run(struct thread_data *td)
1403 {
1404         td_set_runstate(td, TD_RUNNING);
1405
1406         while ((td->o.read_iolog_file && !flist_empty(&td->io_log_list)) ||
1407                 (!flist_empty(&td->trim_list)) || !io_complete_bytes_exceeded(td)) {
1408                 struct io_u *io_u;
1409                 int ret;
1410
1411                 if (td->terminate || td->done)
1412                         break;
1413
1414                 io_u = get_io_u(td);
1415                 if (IS_ERR_OR_NULL(io_u))
1416                         break;
1417
1418                 io_u_set(td, io_u, IO_U_F_FLIGHT);
1419                 io_u->error = 0;
1420                 io_u->resid = 0;
1421                 if (ddir_rw(acct_ddir(io_u)))
1422                         td->io_issues[acct_ddir(io_u)]++;
1423                 if (ddir_rw(io_u->ddir)) {
1424                         io_u_mark_depth(td, 1);
1425                         td->ts.total_io_u[io_u->ddir]++;
1426                 }
1427
1428                 if (td_write(td) && io_u->ddir == DDIR_WRITE &&
1429                     td->o.do_verify &&
1430                     td->o.verify != VERIFY_NONE &&
1431                     !td->o.experimental_verify)
1432                         log_io_piece(td, io_u);
1433
1434                 ret = io_u_sync_complete(td, io_u);
1435                 (void) ret;
1436         }
1437
1438         return td->bytes_done[DDIR_WRITE] + td->bytes_done[DDIR_TRIM];
1439 }
1440
1441 struct fork_data {
1442         struct thread_data *td;
1443         struct sk_out *sk_out;
1444 };
1445
1446 /*
1447  * Entry point for the thread based jobs. The process based jobs end up
1448  * here as well, after a little setup.
1449  */
1450 static void *thread_main(void *data)
1451 {
1452         struct fork_data *fd = data;
1453         unsigned long long elapsed_us[DDIR_RWDIR_CNT] = { 0, };
1454         struct thread_data *td = fd->td;
1455         struct thread_options *o = &td->o;
1456         struct sk_out *sk_out = fd->sk_out;
1457         int deadlock_loop_cnt;
1458         int clear_state;
1459         int ret;
1460
1461         sk_out_assign(sk_out);
1462         free(fd);
1463
1464         if (!o->use_thread) {
1465                 setsid();
1466                 td->pid = getpid();
1467         } else
1468                 td->pid = gettid();
1469
1470         fio_local_clock_init(o->use_thread);
1471
1472         dprint(FD_PROCESS, "jobs pid=%d started\n", (int) td->pid);
1473
1474         if (is_backend)
1475                 fio_server_send_start(td);
1476
1477         INIT_FLIST_HEAD(&td->io_log_list);
1478         INIT_FLIST_HEAD(&td->io_hist_list);
1479         INIT_FLIST_HEAD(&td->verify_list);
1480         INIT_FLIST_HEAD(&td->trim_list);
1481         INIT_FLIST_HEAD(&td->next_rand_list);
1482         td->io_hist_tree = RB_ROOT;
1483
1484         ret = mutex_cond_init_pshared(&td->io_u_lock, &td->free_cond);
1485         if (ret) {
1486                 td_verror(td, ret, "mutex_cond_init_pshared");
1487                 goto err;
1488         }
1489         ret = cond_init_pshared(&td->verify_cond);
1490         if (ret) {
1491                 td_verror(td, ret, "mutex_cond_pshared");
1492                 goto err;
1493         }
1494
1495         td_set_runstate(td, TD_INITIALIZED);
1496         dprint(FD_MUTEX, "up startup_mutex\n");
1497         fio_mutex_up(startup_mutex);
1498         dprint(FD_MUTEX, "wait on td->mutex\n");
1499         fio_mutex_down(td->mutex);
1500         dprint(FD_MUTEX, "done waiting on td->mutex\n");
1501
1502         /*
1503          * A new gid requires privilege, so we need to do this before setting
1504          * the uid.
1505          */
1506         if (o->gid != -1U && setgid(o->gid)) {
1507                 td_verror(td, errno, "setgid");
1508                 goto err;
1509         }
1510         if (o->uid != -1U && setuid(o->uid)) {
1511                 td_verror(td, errno, "setuid");
1512                 goto err;
1513         }
1514
1515         /*
1516          * Do this early, we don't want the compress threads to be limited
1517          * to the same CPUs as the IO workers. So do this before we set
1518          * any potential CPU affinity
1519          */
1520         if (iolog_compress_init(td, sk_out))
1521                 goto err;
1522
1523         /*
1524          * If we have a gettimeofday() thread, make sure we exclude that
1525          * thread from this job
1526          */
1527         if (o->gtod_cpu)
1528                 fio_cpu_clear(&o->cpumask, o->gtod_cpu);
1529
1530         /*
1531          * Set affinity first, in case it has an impact on the memory
1532          * allocations.
1533          */
1534         if (fio_option_is_set(o, cpumask)) {
1535                 if (o->cpus_allowed_policy == FIO_CPUS_SPLIT) {
1536                         ret = fio_cpus_split(&o->cpumask, td->thread_number - 1);
1537                         if (!ret) {
1538                                 log_err("fio: no CPUs set\n");
1539                                 log_err("fio: Try increasing number of available CPUs\n");
1540                                 td_verror(td, EINVAL, "cpus_split");
1541                                 goto err;
1542                         }
1543                 }
1544                 ret = fio_setaffinity(td->pid, o->cpumask);
1545                 if (ret == -1) {
1546                         td_verror(td, errno, "cpu_set_affinity");
1547                         goto err;
1548                 }
1549         }
1550
1551 #ifdef CONFIG_LIBNUMA
1552         /* numa node setup */
1553         if (fio_option_is_set(o, numa_cpunodes) ||
1554             fio_option_is_set(o, numa_memnodes)) {
1555                 struct bitmask *mask;
1556
1557                 if (numa_available() < 0) {
1558                         td_verror(td, errno, "Does not support NUMA API\n");
1559                         goto err;
1560                 }
1561
1562                 if (fio_option_is_set(o, numa_cpunodes)) {
1563                         mask = numa_parse_nodestring(o->numa_cpunodes);
1564                         ret = numa_run_on_node_mask(mask);
1565                         numa_free_nodemask(mask);
1566                         if (ret == -1) {
1567                                 td_verror(td, errno, \
1568                                         "numa_run_on_node_mask failed\n");
1569                                 goto err;
1570                         }
1571                 }
1572
1573                 if (fio_option_is_set(o, numa_memnodes)) {
1574                         mask = NULL;
1575                         if (o->numa_memnodes)
1576                                 mask = numa_parse_nodestring(o->numa_memnodes);
1577
1578                         switch (o->numa_mem_mode) {
1579                         case MPOL_INTERLEAVE:
1580                                 numa_set_interleave_mask(mask);
1581                                 break;
1582                         case MPOL_BIND:
1583                                 numa_set_membind(mask);
1584                                 break;
1585                         case MPOL_LOCAL:
1586                                 numa_set_localalloc();
1587                                 break;
1588                         case MPOL_PREFERRED:
1589                                 numa_set_preferred(o->numa_mem_prefer_node);
1590                                 break;
1591                         case MPOL_DEFAULT:
1592                         default:
1593                                 break;
1594                         }
1595
1596                         if (mask)
1597                                 numa_free_nodemask(mask);
1598
1599                 }
1600         }
1601 #endif
1602
1603         if (fio_pin_memory(td))
1604                 goto err;
1605
1606         /*
1607          * May alter parameters that init_io_u() will use, so we need to
1608          * do this first.
1609          */
1610         if (init_iolog(td))
1611                 goto err;
1612
1613         if (init_io_u(td))
1614                 goto err;
1615
1616         if (o->verify_async && verify_async_init(td))
1617                 goto err;
1618
1619         if (fio_option_is_set(o, ioprio) ||
1620             fio_option_is_set(o, ioprio_class)) {
1621                 ret = ioprio_set(IOPRIO_WHO_PROCESS, 0, o->ioprio_class, o->ioprio);
1622                 if (ret == -1) {
1623                         td_verror(td, errno, "ioprio_set");
1624                         goto err;
1625                 }
1626         }
1627
1628         if (o->cgroup && cgroup_setup(td, cgroup_list, &cgroup_mnt))
1629                 goto err;
1630
1631         errno = 0;
1632         if (nice(o->nice) == -1 && errno != 0) {
1633                 td_verror(td, errno, "nice");
1634                 goto err;
1635         }
1636
1637         if (o->ioscheduler && switch_ioscheduler(td))
1638                 goto err;
1639
1640         if (!o->create_serialize && setup_files(td))
1641                 goto err;
1642
1643         if (td_io_init(td))
1644                 goto err;
1645
1646         if (init_random_map(td))
1647                 goto err;
1648
1649         if (o->exec_prerun && exec_string(o, o->exec_prerun, (const char *)"prerun"))
1650                 goto err;
1651
1652         if (o->pre_read) {
1653                 if (pre_read_files(td) < 0)
1654                         goto err;
1655         }
1656
1657         fio_verify_init(td);
1658
1659         if (rate_submit_init(td, sk_out))
1660                 goto err;
1661
1662         set_epoch_time(td, o->log_unix_epoch);
1663         fio_getrusage(&td->ru_start);
1664         memcpy(&td->bw_sample_time, &td->epoch, sizeof(td->epoch));
1665         memcpy(&td->iops_sample_time, &td->epoch, sizeof(td->epoch));
1666         memcpy(&td->ss.prev_time, &td->epoch, sizeof(td->epoch));
1667
1668         if (o->ratemin[DDIR_READ] || o->ratemin[DDIR_WRITE] ||
1669                         o->ratemin[DDIR_TRIM]) {
1670                 memcpy(&td->lastrate[DDIR_READ], &td->bw_sample_time,
1671                                         sizeof(td->bw_sample_time));
1672                 memcpy(&td->lastrate[DDIR_WRITE], &td->bw_sample_time,
1673                                         sizeof(td->bw_sample_time));
1674                 memcpy(&td->lastrate[DDIR_TRIM], &td->bw_sample_time,
1675                                         sizeof(td->bw_sample_time));
1676         }
1677
1678         clear_state = 0;
1679         while (keep_running(td)) {
1680                 uint64_t verify_bytes;
1681
1682                 fio_gettime(&td->start, NULL);
1683                 memcpy(&td->tv_cache, &td->start, sizeof(td->start));
1684
1685                 if (clear_state) {
1686                         clear_io_state(td, 0);
1687
1688                         if (o->unlink_each_loop && unlink_all_files(td))
1689                                 break;
1690                 }
1691
1692                 prune_io_piece_log(td);
1693
1694                 if (td->o.verify_only && (td_write(td) || td_rw(td)))
1695                         verify_bytes = do_dry_run(td);
1696                 else {
1697                         uint64_t bytes_done[DDIR_RWDIR_CNT];
1698
1699                         do_io(td, bytes_done);
1700
1701                         if (!ddir_rw_sum(bytes_done)) {
1702                                 fio_mark_td_terminate(td);
1703                                 verify_bytes = 0;
1704                         } else {
1705                                 verify_bytes = bytes_done[DDIR_WRITE] +
1706                                                 bytes_done[DDIR_TRIM];
1707                         }
1708                 }
1709
1710                 /*
1711                  * If we took too long to shut down, the main thread could
1712                  * already consider us reaped/exited. If that happens, break
1713                  * out and clean up.
1714                  */
1715                 if (td->runstate >= TD_EXITED)
1716                         break;
1717
1718                 clear_state = 1;
1719
1720                 /*
1721                  * Make sure we've successfully updated the rusage stats
1722                  * before waiting on the stat mutex. Otherwise we could have
1723                  * the stat thread holding stat mutex and waiting for
1724                  * the rusage_sem, which would never get upped because
1725                  * this thread is waiting for the stat mutex.
1726                  */
1727                 deadlock_loop_cnt = 0;
1728                 do {
1729                         check_update_rusage(td);
1730                         if (!fio_mutex_down_trylock(stat_mutex))
1731                                 break;
1732                         usleep(1000);
1733                         if (deadlock_loop_cnt++ > 5000) {
1734                                 log_err("fio seems to be stuck grabbing stat_mutex, forcibly exiting\n");
1735                                 td->error = EDEADLK;
1736                                 goto err;
1737                         }
1738                 } while (1);
1739
1740                 if (td_read(td) && td->io_bytes[DDIR_READ])
1741                         update_runtime(td, elapsed_us, DDIR_READ);
1742                 if (td_write(td) && td->io_bytes[DDIR_WRITE])
1743                         update_runtime(td, elapsed_us, DDIR_WRITE);
1744                 if (td_trim(td) && td->io_bytes[DDIR_TRIM])
1745                         update_runtime(td, elapsed_us, DDIR_TRIM);
1746                 fio_gettime(&td->start, NULL);
1747                 fio_mutex_up(stat_mutex);
1748
1749                 if (td->error || td->terminate)
1750                         break;
1751
1752                 if (!o->do_verify ||
1753                     o->verify == VERIFY_NONE ||
1754                     td_ioengine_flagged(td, FIO_UNIDIR))
1755                         continue;
1756
1757                 clear_io_state(td, 0);
1758
1759                 fio_gettime(&td->start, NULL);
1760
1761                 do_verify(td, verify_bytes);
1762
1763                 /*
1764                  * See comment further up for why this is done here.
1765                  */
1766                 check_update_rusage(td);
1767
1768                 fio_mutex_down(stat_mutex);
1769                 update_runtime(td, elapsed_us, DDIR_READ);
1770                 fio_gettime(&td->start, NULL);
1771                 fio_mutex_up(stat_mutex);
1772
1773                 if (td->error || td->terminate)
1774                         break;
1775         }
1776
1777         td_set_runstate(td, TD_FINISHING);
1778
1779         update_rusage_stat(td);
1780         td->ts.total_run_time = mtime_since_now(&td->epoch);
1781         td->ts.io_bytes[DDIR_READ] = td->io_bytes[DDIR_READ];
1782         td->ts.io_bytes[DDIR_WRITE] = td->io_bytes[DDIR_WRITE];
1783         td->ts.io_bytes[DDIR_TRIM] = td->io_bytes[DDIR_TRIM];
1784
1785         if (td->o.verify_state_save && !(td->flags & TD_F_VSTATE_SAVED) &&
1786             (td->o.verify != VERIFY_NONE && td_write(td)))
1787                 verify_save_state(td->thread_number);
1788
1789         fio_unpin_memory(td);
1790
1791         td_writeout_logs(td, true);
1792
1793         iolog_compress_exit(td);
1794         rate_submit_exit(td);
1795
1796         if (o->exec_postrun)
1797                 exec_string(o, o->exec_postrun, (const char *)"postrun");
1798
1799         if (exitall_on_terminate || (o->exitall_error && td->error))
1800                 fio_terminate_threads(td->groupid);
1801
1802 err:
1803         if (td->error)
1804                 log_info("fio: pid=%d, err=%d/%s\n", (int) td->pid, td->error,
1805                                                         td->verror);
1806
1807         if (o->verify_async)
1808                 verify_async_exit(td);
1809
1810         close_and_free_files(td);
1811         cleanup_io_u(td);
1812         close_ioengine(td);
1813         cgroup_shutdown(td, &cgroup_mnt);
1814         verify_free_state(td);
1815
1816         if (td->zone_state_index) {
1817                 int i;
1818
1819                 for (i = 0; i < DDIR_RWDIR_CNT; i++)
1820                         free(td->zone_state_index[i]);
1821                 free(td->zone_state_index);
1822                 td->zone_state_index = NULL;
1823         }
1824
1825         if (fio_option_is_set(o, cpumask)) {
1826                 ret = fio_cpuset_exit(&o->cpumask);
1827                 if (ret)
1828                         td_verror(td, ret, "fio_cpuset_exit");
1829         }
1830
1831         /*
1832          * do this very late, it will log file closing as well
1833          */
1834         if (o->write_iolog_file)
1835                 write_iolog_close(td);
1836
1837         fio_mutex_remove(td->mutex);
1838         td->mutex = NULL;
1839
1840         td_set_runstate(td, TD_EXITED);
1841
1842         /*
1843          * Do this last after setting our runstate to exited, so we
1844          * know that the stat thread is signaled.
1845          */
1846         check_update_rusage(td);
1847
1848         sk_out_drop();
1849         return (void *) (uintptr_t) td->error;
1850 }
1851
1852 static void dump_td_info(struct thread_data *td)
1853 {
1854         log_err("fio: job '%s' (state=%d) hasn't exited in %lu seconds, it "
1855                 "appears to be stuck. Doing forceful exit of this job.\n",
1856                         td->o.name, td->runstate,
1857                         (unsigned long) time_since_now(&td->terminate_time));
1858 }
1859
1860 /*
1861  * Run over the job map and reap the threads that have exited, if any.
1862  */
1863 static void reap_threads(unsigned int *nr_running, uint64_t *t_rate,
1864                          uint64_t *m_rate)
1865 {
1866         struct thread_data *td;
1867         unsigned int cputhreads, realthreads, pending;
1868         int i, status, ret;
1869
1870         /*
1871          * reap exited threads (TD_EXITED -> TD_REAPED)
1872          */
1873         realthreads = pending = cputhreads = 0;
1874         for_each_td(td, i) {
1875                 int flags = 0;
1876
1877                 /*
1878                  * ->io_ops is NULL for a thread that has closed its
1879                  * io engine
1880                  */
1881                 if (td->io_ops && !strcmp(td->io_ops->name, "cpuio"))
1882                         cputhreads++;
1883                 else
1884                         realthreads++;
1885
1886                 if (!td->pid) {
1887                         pending++;
1888                         continue;
1889                 }
1890                 if (td->runstate == TD_REAPED)
1891                         continue;
1892                 if (td->o.use_thread) {
1893                         if (td->runstate == TD_EXITED) {
1894                                 td_set_runstate(td, TD_REAPED);
1895                                 goto reaped;
1896                         }
1897                         continue;
1898                 }
1899
1900                 flags = WNOHANG;
1901                 if (td->runstate == TD_EXITED)
1902                         flags = 0;
1903
1904                 /*
1905                  * check if someone quit or got killed in an unusual way
1906                  */
1907                 ret = waitpid(td->pid, &status, flags);
1908                 if (ret < 0) {
1909                         if (errno == ECHILD) {
1910                                 log_err("fio: pid=%d disappeared %d\n",
1911                                                 (int) td->pid, td->runstate);
1912                                 td->sig = ECHILD;
1913                                 td_set_runstate(td, TD_REAPED);
1914                                 goto reaped;
1915                         }
1916                         perror("waitpid");
1917                 } else if (ret == td->pid) {
1918                         if (WIFSIGNALED(status)) {
1919                                 int sig = WTERMSIG(status);
1920
1921                                 if (sig != SIGTERM && sig != SIGUSR2)
1922                                         log_err("fio: pid=%d, got signal=%d\n",
1923                                                         (int) td->pid, sig);
1924                                 td->sig = sig;
1925                                 td_set_runstate(td, TD_REAPED);
1926                                 goto reaped;
1927                         }
1928                         if (WIFEXITED(status)) {
1929                                 if (WEXITSTATUS(status) && !td->error)
1930                                         td->error = WEXITSTATUS(status);
1931
1932                                 td_set_runstate(td, TD_REAPED);
1933                                 goto reaped;
1934                         }
1935                 }
1936
1937                 /*
1938                  * If the job is stuck, do a forceful timeout of it and
1939                  * move on.
1940                  */
1941                 if (td->terminate &&
1942                     td->runstate < TD_FSYNCING &&
1943                     time_since_now(&td->terminate_time) >= FIO_REAP_TIMEOUT) {
1944                         dump_td_info(td);
1945                         td_set_runstate(td, TD_REAPED);
1946                         goto reaped;
1947                 }
1948
1949                 /*
1950                  * thread is not dead, continue
1951                  */
1952                 pending++;
1953                 continue;
1954 reaped:
1955                 (*nr_running)--;
1956                 (*m_rate) -= ddir_rw_sum(td->o.ratemin);
1957                 (*t_rate) -= ddir_rw_sum(td->o.rate);
1958                 if (!td->pid)
1959                         pending--;
1960
1961                 if (td->error)
1962                         exit_value++;
1963
1964                 done_secs += mtime_since_now(&td->epoch) / 1000;
1965                 profile_td_exit(td);
1966         }
1967
1968         if (*nr_running == cputhreads && !pending && realthreads)
1969                 fio_terminate_threads(TERMINATE_ALL);
1970 }
1971
1972 static bool __check_trigger_file(void)
1973 {
1974         struct stat sb;
1975
1976         if (!trigger_file)
1977                 return false;
1978
1979         if (stat(trigger_file, &sb))
1980                 return false;
1981
1982         if (unlink(trigger_file) < 0)
1983                 log_err("fio: failed to unlink %s: %s\n", trigger_file,
1984                                                         strerror(errno));
1985
1986         return true;
1987 }
1988
1989 static bool trigger_timedout(void)
1990 {
1991         if (trigger_timeout)
1992                 return time_since_genesis() >= trigger_timeout;
1993
1994         return false;
1995 }
1996
1997 void exec_trigger(const char *cmd)
1998 {
1999         int ret;
2000
2001         if (!cmd)
2002                 return;
2003
2004         ret = system(cmd);
2005         if (ret == -1)
2006                 log_err("fio: failed executing %s trigger\n", cmd);
2007 }
2008
2009 void check_trigger_file(void)
2010 {
2011         if (__check_trigger_file() || trigger_timedout()) {
2012                 if (nr_clients)
2013                         fio_clients_send_trigger(trigger_remote_cmd);
2014                 else {
2015                         verify_save_state(IO_LIST_ALL);
2016                         fio_terminate_threads(TERMINATE_ALL);
2017                         exec_trigger(trigger_cmd);
2018                 }
2019         }
2020 }
2021
2022 static int fio_verify_load_state(struct thread_data *td)
2023 {
2024         int ret;
2025
2026         if (!td->o.verify_state)
2027                 return 0;
2028
2029         if (is_backend) {
2030                 void *data;
2031
2032                 ret = fio_server_get_verify_state(td->o.name,
2033                                         td->thread_number - 1, &data);
2034                 if (!ret)
2035                         verify_assign_state(td, data);
2036         } else
2037                 ret = verify_load_state(td, "local");
2038
2039         return ret;
2040 }
2041
2042 static void do_usleep(unsigned int usecs)
2043 {
2044         check_for_running_stats();
2045         check_trigger_file();
2046         usleep(usecs);
2047 }
2048
2049 static bool check_mount_writes(struct thread_data *td)
2050 {
2051         struct fio_file *f;
2052         unsigned int i;
2053
2054         if (!td_write(td) || td->o.allow_mounted_write)
2055                 return false;
2056
2057         for_each_file(td, f, i) {
2058                 if (f->filetype != FIO_TYPE_BLOCK)
2059                         continue;
2060                 if (device_is_mounted(f->file_name))
2061                         goto mounted;
2062         }
2063
2064         return false;
2065 mounted:
2066         log_err("fio: %s appears mounted, and 'allow_mounted_write' isn't set. Aborting.\n", f->file_name);
2067         return true;
2068 }
2069
2070 static bool waitee_running(struct thread_data *me)
2071 {
2072         const char *waitee = me->o.wait_for;
2073         const char *self = me->o.name;
2074         struct thread_data *td;
2075         int i;
2076
2077         if (!waitee)
2078                 return false;
2079
2080         for_each_td(td, i) {
2081                 if (!strcmp(td->o.name, self) || strcmp(td->o.name, waitee))
2082                         continue;
2083
2084                 if (td->runstate < TD_EXITED) {
2085                         dprint(FD_PROCESS, "%s fenced by %s(%s)\n",
2086                                         self, td->o.name,
2087                                         runstate_to_name(td->runstate));
2088                         return true;
2089                 }
2090         }
2091
2092         dprint(FD_PROCESS, "%s: %s completed, can run\n", self, waitee);
2093         return false;
2094 }
2095
2096 /*
2097  * Main function for kicking off and reaping jobs, as needed.
2098  */
2099 static void run_threads(struct sk_out *sk_out)
2100 {
2101         struct thread_data *td;
2102         unsigned int i, todo, nr_running, nr_started;
2103         uint64_t m_rate, t_rate;
2104         uint64_t spent;
2105
2106         if (fio_gtod_offload && fio_start_gtod_thread())
2107                 return;
2108
2109         fio_idle_prof_init();
2110
2111         set_sig_handlers();
2112
2113         nr_thread = nr_process = 0;
2114         for_each_td(td, i) {
2115                 if (check_mount_writes(td))
2116                         return;
2117                 if (td->o.use_thread)
2118                         nr_thread++;
2119                 else
2120                         nr_process++;
2121         }
2122
2123         if (output_format & FIO_OUTPUT_NORMAL) {
2124                 log_info("Starting ");
2125                 if (nr_thread)
2126                         log_info("%d thread%s", nr_thread,
2127                                                 nr_thread > 1 ? "s" : "");
2128                 if (nr_process) {
2129                         if (nr_thread)
2130                                 log_info(" and ");
2131                         log_info("%d process%s", nr_process,
2132                                                 nr_process > 1 ? "es" : "");
2133                 }
2134                 log_info("\n");
2135                 log_info_flush();
2136         }
2137
2138         todo = thread_number;
2139         nr_running = 0;
2140         nr_started = 0;
2141         m_rate = t_rate = 0;
2142
2143         for_each_td(td, i) {
2144                 print_status_init(td->thread_number - 1);
2145
2146                 if (!td->o.create_serialize)
2147                         continue;
2148
2149                 if (fio_verify_load_state(td))
2150                         goto reap;
2151
2152                 /*
2153                  * do file setup here so it happens sequentially,
2154                  * we don't want X number of threads getting their
2155                  * client data interspersed on disk
2156                  */
2157                 if (setup_files(td)) {
2158 reap:
2159                         exit_value++;
2160                         if (td->error)
2161                                 log_err("fio: pid=%d, err=%d/%s\n",
2162                                         (int) td->pid, td->error, td->verror);
2163                         td_set_runstate(td, TD_REAPED);
2164                         todo--;
2165                 } else {
2166                         struct fio_file *f;
2167                         unsigned int j;
2168
2169                         /*
2170                          * for sharing to work, each job must always open
2171                          * its own files. so close them, if we opened them
2172                          * for creation
2173                          */
2174                         for_each_file(td, f, j) {
2175                                 if (fio_file_open(f))
2176                                         td_io_close_file(td, f);
2177                         }
2178                 }
2179         }
2180
2181         /* start idle threads before io threads start to run */
2182         fio_idle_prof_start();
2183
2184         set_genesis_time();
2185
2186         while (todo) {
2187                 struct thread_data *map[REAL_MAX_JOBS];
2188                 struct timeval this_start;
2189                 int this_jobs = 0, left;
2190                 struct fork_data *fd;
2191
2192                 /*
2193                  * create threads (TD_NOT_CREATED -> TD_CREATED)
2194                  */
2195                 for_each_td(td, i) {
2196                         if (td->runstate != TD_NOT_CREATED)
2197                                 continue;
2198
2199                         /*
2200                          * never got a chance to start, killed by other
2201                          * thread for some reason
2202                          */
2203                         if (td->terminate) {
2204                                 todo--;
2205                                 continue;
2206                         }
2207
2208                         if (td->o.start_delay) {
2209                                 spent = utime_since_genesis();
2210
2211                                 if (td->o.start_delay > spent)
2212                                         continue;
2213                         }
2214
2215                         if (td->o.stonewall && (nr_started || nr_running)) {
2216                                 dprint(FD_PROCESS, "%s: stonewall wait\n",
2217                                                         td->o.name);
2218                                 break;
2219                         }
2220
2221                         if (waitee_running(td)) {
2222                                 dprint(FD_PROCESS, "%s: waiting for %s\n",
2223                                                 td->o.name, td->o.wait_for);
2224                                 continue;
2225                         }
2226
2227                         init_disk_util(td);
2228
2229                         td->rusage_sem = fio_mutex_init(FIO_MUTEX_LOCKED);
2230                         td->update_rusage = 0;
2231
2232                         /*
2233                          * Set state to created. Thread will transition
2234                          * to TD_INITIALIZED when it's done setting up.
2235                          */
2236                         td_set_runstate(td, TD_CREATED);
2237                         map[this_jobs++] = td;
2238                         nr_started++;
2239
2240                         fd = calloc(1, sizeof(*fd));
2241                         fd->td = td;
2242                         fd->sk_out = sk_out;
2243
2244                         if (td->o.use_thread) {
2245                                 int ret;
2246
2247                                 dprint(FD_PROCESS, "will pthread_create\n");
2248                                 ret = pthread_create(&td->thread, NULL,
2249                                                         thread_main, fd);
2250                                 if (ret) {
2251                                         log_err("pthread_create: %s\n",
2252                                                         strerror(ret));
2253                                         free(fd);
2254                                         nr_started--;
2255                                         break;
2256                                 }
2257                                 ret = pthread_detach(td->thread);
2258                                 if (ret)
2259                                         log_err("pthread_detach: %s",
2260                                                         strerror(ret));
2261                         } else {
2262                                 pid_t pid;
2263                                 dprint(FD_PROCESS, "will fork\n");
2264                                 pid = fork();
2265                                 if (!pid) {
2266                                         int ret;
2267
2268                                         ret = (int)(uintptr_t)thread_main(fd);
2269                                         _exit(ret);
2270                                 } else if (i == fio_debug_jobno)
2271                                         *fio_debug_jobp = pid;
2272                         }
2273                         dprint(FD_MUTEX, "wait on startup_mutex\n");
2274                         if (fio_mutex_down_timeout(startup_mutex, 10000)) {
2275                                 log_err("fio: job startup hung? exiting.\n");
2276                                 fio_terminate_threads(TERMINATE_ALL);
2277                                 fio_abort = 1;
2278                                 nr_started--;
2279                                 break;
2280                         }
2281                         dprint(FD_MUTEX, "done waiting on startup_mutex\n");
2282                 }
2283
2284                 /*
2285                  * Wait for the started threads to transition to
2286                  * TD_INITIALIZED.
2287                  */
2288                 fio_gettime(&this_start, NULL);
2289                 left = this_jobs;
2290                 while (left && !fio_abort) {
2291                         if (mtime_since_now(&this_start) > JOB_START_TIMEOUT)
2292                                 break;
2293
2294                         do_usleep(100000);
2295
2296                         for (i = 0; i < this_jobs; i++) {
2297                                 td = map[i];
2298                                 if (!td)
2299                                         continue;
2300                                 if (td->runstate == TD_INITIALIZED) {
2301                                         map[i] = NULL;
2302                                         left--;
2303                                 } else if (td->runstate >= TD_EXITED) {
2304                                         map[i] = NULL;
2305                                         left--;
2306                                         todo--;
2307                                         nr_running++; /* work-around... */
2308                                 }
2309                         }
2310                 }
2311
2312                 if (left) {
2313                         log_err("fio: %d job%s failed to start\n", left,
2314                                         left > 1 ? "s" : "");
2315                         for (i = 0; i < this_jobs; i++) {
2316                                 td = map[i];
2317                                 if (!td)
2318                                         continue;
2319                                 kill(td->pid, SIGTERM);
2320                         }
2321                         break;
2322                 }
2323
2324                 /*
2325                  * start created threads (TD_INITIALIZED -> TD_RUNNING).
2326                  */
2327                 for_each_td(td, i) {
2328                         if (td->runstate != TD_INITIALIZED)
2329                                 continue;
2330
2331                         if (in_ramp_time(td))
2332                                 td_set_runstate(td, TD_RAMP);
2333                         else
2334                                 td_set_runstate(td, TD_RUNNING);
2335                         nr_running++;
2336                         nr_started--;
2337                         m_rate += ddir_rw_sum(td->o.ratemin);
2338                         t_rate += ddir_rw_sum(td->o.rate);
2339                         todo--;
2340                         fio_mutex_up(td->mutex);
2341                 }
2342
2343                 reap_threads(&nr_running, &t_rate, &m_rate);
2344
2345                 if (todo)
2346                         do_usleep(100000);
2347         }
2348
2349         while (nr_running) {
2350                 reap_threads(&nr_running, &t_rate, &m_rate);
2351                 do_usleep(10000);
2352         }
2353
2354         fio_idle_prof_stop();
2355
2356         update_io_ticks();
2357 }
2358
2359 static void free_disk_util(void)
2360 {
2361         disk_util_prune_entries();
2362         helper_thread_destroy();
2363 }
2364
2365 int fio_backend(struct sk_out *sk_out)
2366 {
2367         struct thread_data *td;
2368         int i;
2369
2370         if (exec_profile) {
2371                 if (load_profile(exec_profile))
2372                         return 1;
2373                 free(exec_profile);
2374                 exec_profile = NULL;
2375         }
2376         if (!thread_number)
2377                 return 0;
2378
2379         if (write_bw_log) {
2380                 struct log_params p = {
2381                         .log_type = IO_LOG_TYPE_BW,
2382                 };
2383
2384                 setup_log(&agg_io_log[DDIR_READ], &p, "agg-read_bw.log");
2385                 setup_log(&agg_io_log[DDIR_WRITE], &p, "agg-write_bw.log");
2386                 setup_log(&agg_io_log[DDIR_TRIM], &p, "agg-trim_bw.log");
2387         }
2388
2389         startup_mutex = fio_mutex_init(FIO_MUTEX_LOCKED);
2390         if (startup_mutex == NULL)
2391                 return 1;
2392
2393         set_genesis_time();
2394         stat_init();
2395         helper_thread_create(startup_mutex, sk_out);
2396
2397         cgroup_list = smalloc(sizeof(*cgroup_list));
2398         INIT_FLIST_HEAD(cgroup_list);
2399
2400         run_threads(sk_out);
2401
2402         helper_thread_exit();
2403
2404         if (!fio_abort) {
2405                 __show_run_stats();
2406                 if (write_bw_log) {
2407                         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
2408                                 struct io_log *log = agg_io_log[i];
2409
2410                                 flush_log(log, false);
2411                                 free_log(log);
2412                         }
2413                 }
2414         }
2415
2416         for_each_td(td, i) {
2417                 if (td->ss.dur) {
2418                         if (td->ss.iops_data != NULL) {
2419                                 free(td->ss.iops_data);
2420                                 free(td->ss.bw_data);
2421                         }
2422                 }
2423                 fio_options_free(td);
2424                 if (td->rusage_sem) {
2425                         fio_mutex_remove(td->rusage_sem);
2426                         td->rusage_sem = NULL;
2427                 }
2428         }
2429
2430         free_disk_util();
2431         cgroup_kill(cgroup_list);
2432         sfree(cgroup_list);
2433         sfree(cgroup_mnt);
2434
2435         fio_mutex_remove(startup_mutex);
2436         stat_exit();
2437         return exit_value;
2438 }