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