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