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