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