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