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