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