9594f80582266ce8a8a5794ea9c52fb02a6adb1d
[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 "os.h"
39
40 static unsigned long page_mask;
41 #define ALIGN(buf)      \
42         (char *) (((unsigned long) (buf) + page_mask) & ~page_mask)
43
44 int groupid = 0;
45 int thread_number = 0;
46 int shm_id = 0;
47 int temp_stall_ts;
48
49 static volatile int startup_sem;
50 static volatile int fio_abort;
51 static int exit_value;
52
53 struct io_log *agg_io_log[2];
54
55 #define TERMINATE_ALL           (-1)
56 #define JOB_START_TIMEOUT       (5 * 1000)
57
58 static inline void td_set_runstate(struct thread_data *td, int runstate)
59 {
60         td->runstate = runstate;
61 }
62
63 static void terminate_threads(int group_id, int forced_kill)
64 {
65         struct thread_data *td;
66         int i;
67
68         for_each_td(td, i) {
69                 if (group_id == TERMINATE_ALL || groupid == td->groupid) {
70                         td->terminate = 1;
71                         td->start_delay = 0;
72                         if (forced_kill)
73                                 td_set_runstate(td, TD_EXITED);
74                 }
75         }
76 }
77
78 static void sig_handler(int sig)
79 {
80         switch (sig) {
81                 case SIGALRM:
82                         update_io_ticks();
83                         disk_util_timer_arm();
84                         print_thread_status();
85                         break;
86                 default:
87                         printf("\nfio: terminating on signal %d\n", sig);
88                         fflush(stdout);
89                         terminate_threads(TERMINATE_ALL, 0);
90                         break;
91         }
92 }
93
94 /*
95  * Check if we are above the minimum rate given.
96  */
97 static int check_min_rate(struct thread_data *td, struct timeval *now)
98 {
99         unsigned long spent;
100         unsigned long rate;
101         int ddir = td->ddir;
102
103         /*
104          * allow a 2 second settle period in the beginning
105          */
106         if (mtime_since(&td->start, now) < 2000)
107                 return 0;
108
109         /*
110          * if rate blocks is set, sample is running
111          */
112         if (td->rate_bytes) {
113                 spent = mtime_since(&td->lastrate, now);
114                 if (spent < td->ratecycle)
115                         return 0;
116
117                 rate = (td->this_io_bytes[ddir] - td->rate_bytes) / spent;
118                 if (rate < td->ratemin) {
119                         fprintf(f_out, "%s: min rate %u not met, got %luKiB/sec\n", td->name, td->ratemin, rate);
120                         return 1;
121                 }
122         }
123
124         td->rate_bytes = td->this_io_bytes[ddir];
125         memcpy(&td->lastrate, now, sizeof(*now));
126         return 0;
127 }
128
129 static inline int runtime_exceeded(struct thread_data *td, struct timeval *t)
130 {
131         if (!td->timeout)
132                 return 0;
133         if (mtime_since(&td->epoch, t) >= td->timeout * 1000)
134                 return 1;
135
136         return 0;
137 }
138
139 /*
140  * When job exits, we can cancel the in-flight IO if we are using async
141  * io. Attempt to do so.
142  */
143 static void cleanup_pending_aio(struct thread_data *td)
144 {
145         struct list_head *entry, *n;
146         struct io_u *io_u;
147         int r;
148
149         /*
150          * get immediately available events, if any
151          */
152         r = io_u_queued_complete(td, 0, NULL);
153         if (r < 0)
154                 return;
155
156         /*
157          * now cancel remaining active events
158          */
159         if (td->io_ops->cancel) {
160                 list_for_each_safe(entry, n, &td->io_u_busylist) {
161                         io_u = list_entry(entry, struct io_u, list);
162
163                         r = td->io_ops->cancel(td, io_u);
164                         if (!r)
165                                 put_io_u(td, io_u);
166                 }
167         }
168
169         if (td->cur_depth)
170                 r = io_u_queued_complete(td, td->cur_depth, NULL);
171 }
172
173 /*
174  * Helper to handle the final sync of a file. Works just like the normal
175  * io path, just does everything sync.
176  */
177 static int fio_io_sync(struct thread_data *td, struct fio_file *f)
178 {
179         struct io_u *io_u = __get_io_u(td);
180         int ret;
181
182         if (!io_u)
183                 return 1;
184
185         io_u->ddir = DDIR_SYNC;
186         io_u->file = f;
187
188         if (td_io_prep(td, io_u)) {
189                 put_io_u(td, io_u);
190                 return 1;
191         }
192
193 requeue:
194         ret = td_io_queue(td, io_u);
195         if (ret < 0) {
196                 td_verror(td, io_u->error);
197                 put_io_u(td, io_u);
198                 return 1;
199         } else if (ret == FIO_Q_QUEUED) {
200                 if (io_u_queued_complete(td, 1, NULL) < 0)
201                         return 1;
202         } else if (ret == FIO_Q_COMPLETED) {
203                 if (io_u->error) {
204                         td_verror(td, io_u->error);
205                         return 1;
206                 }
207
208                 if (io_u_sync_complete(td, io_u, NULL) < 0)
209                         return 1;
210         } else if (ret == FIO_Q_BUSY) {
211                 if (td_io_commit(td))
212                         return 1;
213                 goto requeue;
214         }
215
216         return 0;
217 }
218
219 /*
220  * The main verify engine. Runs over the writes we previusly submitted,
221  * reads the blocks back in, and checks the crc/md5 of the data.
222  */
223 static void do_verify(struct thread_data *td)
224 {
225         struct fio_file *f;
226         struct io_u *io_u;
227         int ret, i, min_events;
228
229         /*
230          * sync io first and invalidate cache, to make sure we really
231          * read from disk.
232          */
233         for_each_file(td, f, i) {
234                 if (fio_io_sync(td, f))
235                         break;
236                 if (file_invalidate_cache(td, f))
237                         break;
238         }
239
240         if (td->error)
241                 return;
242
243         td_set_runstate(td, TD_VERIFYING);
244
245         io_u = NULL;
246         while (!td->terminate) {
247                 io_u = __get_io_u(td);
248                 if (!io_u)
249                         break;
250
251                 if (runtime_exceeded(td, &io_u->start_time)) {
252                         put_io_u(td, io_u);
253                         break;
254                 }
255
256                 if (get_next_verify(td, io_u)) {
257                         put_io_u(td, io_u);
258                         break;
259                 }
260
261                 if (td_io_prep(td, io_u)) {
262                         put_io_u(td, io_u);
263                         break;
264                 }
265 requeue:
266                 ret = td_io_queue(td, io_u);
267
268                 switch (ret) {
269                 case FIO_Q_COMPLETED:
270                         if (io_u->error)
271                                 ret = -io_u->error;
272                         if (io_u->xfer_buflen != io_u->resid && io_u->resid) {
273                                 int bytes = io_u->xfer_buflen - io_u->resid;
274
275                                 io_u->xfer_buflen = io_u->resid;
276                                 io_u->xfer_buf += bytes;
277                                 goto requeue;
278                         }
279                         ret = io_u_sync_complete(td, io_u, verify_io_u);
280                         if (ret < 0)
281                                 break;
282                         continue;
283                 case FIO_Q_QUEUED:
284                         break;
285                 case FIO_Q_BUSY:
286                         requeue_io_u(td, &io_u);
287                         ret = td_io_commit(td);
288                         break;
289                 default:
290                         assert(ret < 0);
291                         td_verror(td, -ret);
292                         break;
293                 }
294
295                 if (ret < 0 || td->error)
296                         break;
297
298                 /*
299                  * if we can queue more, do so. but check if there are
300                  * completed io_u's first.
301                  */
302                 min_events = 0;
303                 if (queue_full(td) || ret == FIO_Q_BUSY) {
304                         min_events = 1;
305
306                         if (td->cur_depth > td->iodepth_low)
307                                 min_events = td->cur_depth - td->iodepth_low;
308                 }
309
310                 /*
311                  * Reap required number of io units, if any, and do the
312                  * verification on them through the callback handler
313                  */
314                 if (io_u_queued_complete(td, min_events, verify_io_u) < 0)
315                         break;
316         }
317
318         if (td->cur_depth)
319                 cleanup_pending_aio(td);
320
321         td_set_runstate(td, TD_RUNNING);
322 }
323
324 /*
325  * Not really an io thread, all it does is burn CPU cycles in the specified
326  * manner.
327  */
328 static void do_cpuio(struct thread_data *td)
329 {
330         struct timeval e;
331         int split = 100 / td->cpuload;
332         int i = 0;
333
334         while (!td->terminate) {
335                 fio_gettime(&e, NULL);
336
337                 if (runtime_exceeded(td, &e))
338                         break;
339
340                 if (!(i % split))
341                         __usec_sleep(10000);
342                 else
343                         usec_sleep(td, 10000);
344
345                 i++;
346         }
347 }
348
349 /*
350  * Main IO worker function. It retrieves io_u's to process and queues
351  * and reaps them, checking for rate and errors along the way.
352  */
353 static void do_io(struct thread_data *td)
354 {
355         struct timeval s;
356         unsigned long usec;
357         int i, ret = 0;
358
359         td_set_runstate(td, TD_RUNNING);
360
361         while ((td->this_io_bytes[0] + td->this_io_bytes[1]) < td->io_size) {
362                 struct timeval comp_time;
363                 long bytes_done = 0;
364                 int min_evts = 0;
365                 struct io_u *io_u;
366
367                 if (td->terminate)
368                         break;
369
370                 io_u = get_io_u(td);
371                 if (!io_u)
372                         break;
373
374                 memcpy(&s, &io_u->start_time, sizeof(s));
375
376                 if (runtime_exceeded(td, &s)) {
377                         put_io_u(td, io_u);
378                         break;
379                 }
380 requeue:
381                 ret = td_io_queue(td, io_u);
382
383                 switch (ret) {
384                 case FIO_Q_COMPLETED:
385                         if (io_u->error) {
386                                 ret = io_u->error;
387                                 break;
388                         }
389                         if (io_u->xfer_buflen != io_u->resid && io_u->resid) {
390                                 int bytes = io_u->xfer_buflen - io_u->resid;
391
392                                 io_u->xfer_buflen = io_u->resid;
393                                 io_u->xfer_buf += bytes;
394                                 goto requeue;
395                         }
396                         fio_gettime(&comp_time, NULL);
397                         bytes_done = io_u_sync_complete(td, io_u, NULL);
398                         if (bytes_done < 0)
399                                 ret = bytes_done;
400                         break;
401                 case FIO_Q_QUEUED:
402                         /*
403                          * if the engine doesn't have a commit hook,
404                          * the io_u is really queued. if it does have such
405                          * a hook, it has to call io_u_queued() itself.
406                          */
407                         if (td->io_ops->commit == NULL)
408                                 io_u_queued(td, io_u);
409                         break;
410                 case FIO_Q_BUSY:
411                         requeue_io_u(td, &io_u);
412                         ret = td_io_commit(td);
413                         break;
414                 default:
415                         assert(ret < 0);
416                         put_io_u(td, io_u);
417                         break;
418                 }
419
420                 if (ret < 0 || td->error)
421                         break;
422
423                 /*
424                  * See if we need to complete some commands
425                  */
426                 if (ret == FIO_Q_QUEUED || ret == FIO_Q_BUSY) {
427                         min_evts = 0;
428                         if (queue_full(td) || ret == FIO_Q_BUSY) {
429                                 min_evts = 1;
430
431                                 if (td->cur_depth > td->iodepth_low)
432                                         min_evts = td->cur_depth - td->iodepth_low;
433                         }
434
435                         fio_gettime(&comp_time, NULL);
436                         bytes_done = io_u_queued_complete(td, min_evts, NULL);
437                         if (bytes_done < 0)
438                                 break;
439                 }
440
441                 if (!bytes_done)
442                         continue;
443
444                 /*
445                  * the rate is batched for now, it should work for batches
446                  * of completions except the very first one which may look
447                  * a little bursty
448                  */
449                 usec = utime_since(&s, &comp_time);
450
451                 rate_throttle(td, usec, bytes_done, td->ddir);
452
453                 if (check_min_rate(td, &comp_time)) {
454                         if (exitall_on_terminate)
455                                 terminate_threads(td->groupid, 0);
456                         td_verror(td, ENODATA);
457                         break;
458                 }
459
460                 if (td->thinktime) {
461                         unsigned long long b;
462
463                         b = td->io_blocks[0] + td->io_blocks[1];
464                         if (!(b % td->thinktime_blocks)) {
465                                 int left;
466
467                                 if (td->thinktime_spin)
468                                         __usec_sleep(td->thinktime_spin);
469
470                                 left = td->thinktime - td->thinktime_spin;
471                                 if (left)
472                                         usec_sleep(td, left);
473                         }
474                 }
475         }
476
477         if (!td->error) {
478                 struct fio_file *f;
479
480                 if (td->cur_depth)
481                         cleanup_pending_aio(td);
482
483                 if (should_fsync(td) && td->end_fsync) {
484                         td_set_runstate(td, TD_FSYNCING);
485                         for_each_file(td, f, i)
486                                 fio_io_sync(td, f);
487                 }
488         }
489 }
490
491 static void cleanup_io_u(struct thread_data *td)
492 {
493         struct list_head *entry, *n;
494         struct io_u *io_u;
495
496         list_for_each_safe(entry, n, &td->io_u_freelist) {
497                 io_u = list_entry(entry, struct io_u, list);
498
499                 list_del(&io_u->list);
500                 free(io_u);
501         }
502
503         free_io_mem(td);
504 }
505
506 /*
507  * "randomly" fill the buffer contents
508  */
509 static void fill_rand_buf(struct io_u *io_u, int max_bs)
510 {
511         int *ptr = io_u->buf;
512
513         while ((void *) ptr - io_u->buf < max_bs) {
514                 *ptr = rand() * 0x9e370001;
515                 ptr++;
516         }
517 }
518
519 static int init_io_u(struct thread_data *td)
520 {
521         struct io_u *io_u;
522         unsigned int max_bs;
523         int i, max_units;
524         char *p;
525
526         if (td->io_ops->flags & FIO_CPUIO)
527                 return 0;
528
529         if (td->io_ops->flags & FIO_SYNCIO)
530                 max_units = 1;
531         else
532                 max_units = td->iodepth;
533
534         max_bs = max(td->max_bs[DDIR_READ], td->max_bs[DDIR_WRITE]);
535         td->orig_buffer_size = max_bs * max_units;
536
537         if (td->mem_type == MEM_SHMHUGE || td->mem_type == MEM_MMAPHUGE)
538                 td->orig_buffer_size = (td->orig_buffer_size + td->hugepage_size - 1) & ~(td->hugepage_size - 1);
539         else
540                 td->orig_buffer_size += page_mask;
541
542         if (allocate_io_mem(td))
543                 return 1;
544
545         p = ALIGN(td->orig_buffer);
546         for (i = 0; i < max_units; i++) {
547                 io_u = malloc(sizeof(*io_u));
548                 memset(io_u, 0, sizeof(*io_u));
549                 INIT_LIST_HEAD(&io_u->list);
550
551                 io_u->buf = p + max_bs * i;
552                 if (td_write(td) || td_rw(td))
553                         fill_rand_buf(io_u, max_bs);
554
555                 io_u->index = i;
556                 list_add(&io_u->list, &td->io_u_freelist);
557         }
558
559         return 0;
560 }
561
562 static int switch_ioscheduler(struct thread_data *td)
563 {
564         char tmp[256], tmp2[128];
565         FILE *f;
566         int ret;
567
568         if (td->io_ops->flags & FIO_CPUIO)
569                 return 0;
570
571         sprintf(tmp, "%s/queue/scheduler", td->sysfs_root);
572
573         f = fopen(tmp, "r+");
574         if (!f) {
575                 td_verror(td, errno);
576                 return 1;
577         }
578
579         /*
580          * Set io scheduler.
581          */
582         ret = fwrite(td->ioscheduler, strlen(td->ioscheduler), 1, f);
583         if (ferror(f) || ret != 1) {
584                 td_verror(td, errno);
585                 fclose(f);
586                 return 1;
587         }
588
589         rewind(f);
590
591         /*
592          * Read back and check that the selected scheduler is now the default.
593          */
594         ret = fread(tmp, 1, sizeof(tmp), f);
595         if (ferror(f) || ret < 0) {
596                 td_verror(td, errno);
597                 fclose(f);
598                 return 1;
599         }
600
601         sprintf(tmp2, "[%s]", td->ioscheduler);
602         if (!strstr(tmp, tmp2)) {
603                 log_err("fio: io scheduler %s not found\n", td->ioscheduler);
604                 td_verror(td, EINVAL);
605                 fclose(f);
606                 return 1;
607         }
608
609         fclose(f);
610         return 0;
611 }
612
613 static void clear_io_state(struct thread_data *td)
614 {
615         struct fio_file *f;
616         int i;
617
618         td->ts.stat_io_bytes[0] = td->ts.stat_io_bytes[1] = 0;
619         td->this_io_bytes[0] = td->this_io_bytes[1] = 0;
620         td->zone_bytes = 0;
621
622         td->last_was_sync = 0;
623
624         for_each_file(td, f, i) {
625                 f->last_completed_pos = 0;
626
627                 f->last_pos = 0;
628                 if (td->io_ops->flags & FIO_SYNCIO)
629                         lseek(f->fd, SEEK_SET, 0);
630
631                 if (f->file_map)
632                         memset(f->file_map, 0, f->num_maps * sizeof(long));
633         }
634 }
635
636 /*
637  * Entry point for the thread based jobs. The process based jobs end up
638  * here as well, after a little setup.
639  */
640 static void *thread_main(void *data)
641 {
642         unsigned long long runtime[2];
643         struct thread_data *td = data;
644
645         if (!td->use_thread)
646                 setsid();
647
648         td->pid = getpid();
649
650         INIT_LIST_HEAD(&td->io_u_freelist);
651         INIT_LIST_HEAD(&td->io_u_busylist);
652         INIT_LIST_HEAD(&td->io_u_requeues);
653         INIT_LIST_HEAD(&td->io_hist_list);
654         INIT_LIST_HEAD(&td->io_log_list);
655
656         if (init_io_u(td))
657                 goto err;
658
659         if (fio_setaffinity(td) == -1) {
660                 td_verror(td, errno);
661                 goto err;
662         }
663
664         if (init_iolog(td))
665                 goto err;
666
667         if (td->ioprio) {
668                 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, td->ioprio) == -1) {
669                         td_verror(td, errno);
670                         goto err;
671                 }
672         }
673
674         if (nice(td->nice) == -1) {
675                 td_verror(td, errno);
676                 goto err;
677         }
678
679         if (init_random_state(td))
680                 goto err;
681
682         if (td->ioscheduler && switch_ioscheduler(td))
683                 goto err;
684
685         td_set_runstate(td, TD_INITIALIZED);
686         fio_sem_up(&startup_sem);
687         fio_sem_down(&td->mutex);
688
689         if (!td->create_serialize && setup_files(td))
690                 goto err;
691         if (open_files(td))
692                 goto err;
693
694         /*
695          * Do this late, as some IO engines would like to have the
696          * files setup prior to initializing structures.
697          */
698         if (td_io_init(td))
699                 goto err;
700
701         if (td->exec_prerun) {
702                 if (system(td->exec_prerun) < 0)
703                         goto err;
704         }
705
706         fio_gettime(&td->epoch, NULL);
707         getrusage(RUSAGE_SELF, &td->ts.ru_start);
708
709         runtime[0] = runtime[1] = 0;
710         while (td->loops--) {
711                 fio_gettime(&td->start, NULL);
712                 memcpy(&td->ts.stat_sample_time, &td->start, sizeof(td->start));
713
714                 if (td->ratemin)
715                         memcpy(&td->lastrate, &td->ts.stat_sample_time, sizeof(td->lastrate));
716
717                 clear_io_state(td);
718                 prune_io_piece_log(td);
719
720                 if (td->io_ops->flags & FIO_CPUIO)
721                         do_cpuio(td);
722                 else
723                         do_io(td);
724
725                 runtime[td->ddir] += utime_since_now(&td->start);
726                 if (td_rw(td) && td->io_bytes[td->ddir ^ 1])
727                         runtime[td->ddir ^ 1] = runtime[td->ddir];
728
729                 if (td->error || td->terminate)
730                         break;
731
732                 if (td->verify == VERIFY_NONE)
733                         continue;
734
735                 clear_io_state(td);
736                 fio_gettime(&td->start, NULL);
737
738                 do_verify(td);
739
740                 runtime[DDIR_READ] += utime_since_now(&td->start);
741
742                 if (td->error || td->terminate)
743                         break;
744         }
745
746         update_rusage_stat(td);
747         fio_gettime(&td->end_time, NULL);
748         td->runtime[0] = runtime[0] / 1000;
749         td->runtime[1] = runtime[1] / 1000;
750
751         if (td->ts.bw_log)
752                 finish_log(td, td->ts.bw_log, "bw");
753         if (td->ts.slat_log)
754                 finish_log(td, td->ts.slat_log, "slat");
755         if (td->ts.clat_log)
756                 finish_log(td, td->ts.clat_log, "clat");
757         if (td->write_iolog_file)
758                 write_iolog_close(td);
759         if (td->exec_postrun) {
760                 if (system(td->exec_postrun) < 0)
761                         log_err("fio: postrun %s failed\n", td->exec_postrun);
762         }
763
764         if (exitall_on_terminate)
765                 terminate_threads(td->groupid, 0);
766
767 err:
768         if (td->error)
769                 printf("fio: pid=%d, err=%d/%s\n", td->pid, td->error, td->verror);
770         close_files(td);
771         close_ioengine(td);
772         cleanup_io_u(td);
773         td_set_runstate(td, TD_EXITED);
774         return (void *) (unsigned long) td->error;
775 }
776
777 /*
778  * We cannot pass the td data into a forked process, so attach the td and
779  * pass it to the thread worker.
780  */
781 static int fork_main(int shmid, int offset)
782 {
783         struct thread_data *td;
784         void *data, *ret;
785
786         data = shmat(shmid, NULL, 0);
787         if (data == (void *) -1) {
788                 int __err = errno;
789
790                 perror("shmat");
791                 return __err;
792         }
793
794         td = data + offset * sizeof(struct thread_data);
795         ret = thread_main(td);
796         shmdt(data);
797         return (int) (unsigned long) ret;
798 }
799
800 /*
801  * Run over the job map and reap the threads that have exited, if any.
802  */
803 static void reap_threads(int *nr_running, int *t_rate, int *m_rate)
804 {
805         struct thread_data *td;
806         int i, cputhreads, pending, status, ret;
807
808         /*
809          * reap exited threads (TD_EXITED -> TD_REAPED)
810          */
811         pending = cputhreads = 0;
812         for_each_td(td, i) {
813                 /*
814                  * ->io_ops is NULL for a thread that has closed its
815                  * io engine
816                  */
817                 if (td->io_ops && td->io_ops->flags & FIO_CPUIO)
818                         cputhreads++;
819
820                 if (td->runstate < TD_EXITED) {
821                         /*
822                          * check if someone quit or got killed in an unusual way
823                          */
824                         ret = waitpid(td->pid, &status, WNOHANG);
825                         if (ret < 0)
826                                 perror("waitpid");
827                         else if ((ret == td->pid) && WIFSIGNALED(status)) {
828                                 int sig = WTERMSIG(status);
829
830                                 log_err("fio: pid=%d, got signal=%d\n", td->pid, sig);
831                                 td_set_runstate(td, TD_REAPED);
832                                 goto reaped;
833                         }
834                 }
835
836                 if (td->runstate != TD_EXITED) {
837                         if (td->runstate < TD_RUNNING)
838                                 pending++;
839
840                         continue;
841                 }
842
843                 if (td->error)
844                         exit_value++;
845
846                 td_set_runstate(td, TD_REAPED);
847
848                 if (td->use_thread) {
849                         long ret;
850
851                         if (pthread_join(td->thread, (void *) &ret))
852                                 perror("thread_join");
853                 } else {
854                         int status;
855
856                         ret = waitpid(td->pid, &status, 0);
857                         if (ret < 0)
858                                 perror("waitpid");
859                         else if (WIFEXITED(status) && WEXITSTATUS(status)) {
860                                 if (!exit_value)
861                                         exit_value++;
862                         }
863                 }
864
865 reaped:
866                 (*nr_running)--;
867                 (*m_rate) -= td->ratemin;
868                 (*t_rate) -= td->rate;
869         }
870
871         if (*nr_running == cputhreads && !pending)
872                 terminate_threads(TERMINATE_ALL, 0);
873 }
874
875 /*
876  * Main function for kicking off and reaping jobs, as needed.
877  */
878 static void run_threads(void)
879 {
880         struct thread_data *td;
881         unsigned long spent;
882         int i, todo, nr_running, m_rate, t_rate, nr_started;
883
884         if (fio_pin_memory())
885                 return;
886
887         if (!terse_output) {
888                 printf("Starting %d thread%s\n", thread_number, thread_number > 1 ? "s" : "");
889                 fflush(stdout);
890         }
891
892         signal(SIGINT, sig_handler);
893         signal(SIGALRM, sig_handler);
894
895         todo = thread_number;
896         nr_running = 0;
897         nr_started = 0;
898         m_rate = t_rate = 0;
899
900         for_each_td(td, i) {
901                 print_status_init(td->thread_number - 1);
902
903                 if (!td->create_serialize) {
904                         init_disk_util(td);
905                         continue;
906                 }
907
908                 /*
909                  * do file setup here so it happens sequentially,
910                  * we don't want X number of threads getting their
911                  * client data interspersed on disk
912                  */
913                 if (setup_files(td)) {
914                         exit_value++;
915                         if (td->error)
916                                 log_err("fio: pid=%d, err=%d/%s\n", td->pid, td->error, td->verror);
917                         td_set_runstate(td, TD_REAPED);
918                         todo--;
919                 }
920
921                 init_disk_util(td);
922         }
923
924         while (todo) {
925                 struct thread_data *map[MAX_JOBS];
926                 struct timeval this_start;
927                 int this_jobs = 0, left;
928
929                 /*
930                  * create threads (TD_NOT_CREATED -> TD_CREATED)
931                  */
932                 for_each_td(td, i) {
933                         if (td->runstate != TD_NOT_CREATED)
934                                 continue;
935
936                         /*
937                          * never got a chance to start, killed by other
938                          * thread for some reason
939                          */
940                         if (td->terminate) {
941                                 todo--;
942                                 continue;
943                         }
944
945                         if (td->start_delay) {
946                                 spent = mtime_since_genesis();
947
948                                 if (td->start_delay * 1000 > spent)
949                                         continue;
950                         }
951
952                         if (td->stonewall && (nr_started || nr_running))
953                                 break;
954
955                         /*
956                          * Set state to created. Thread will transition
957                          * to TD_INITIALIZED when it's done setting up.
958                          */
959                         td_set_runstate(td, TD_CREATED);
960                         map[this_jobs++] = td;
961                         fio_sem_init(&startup_sem, 1);
962                         nr_started++;
963
964                         if (td->use_thread) {
965                                 if (pthread_create(&td->thread, NULL, thread_main, td)) {
966                                         perror("thread_create");
967                                         nr_started--;
968                                 }
969                         } else {
970                                 if (fork())
971                                         fio_sem_down(&startup_sem);
972                                 else {
973                                         int ret = fork_main(shm_id, i);
974
975                                         exit(ret);
976                                 }
977                         }
978                 }
979
980                 /*
981                  * Wait for the started threads to transition to
982                  * TD_INITIALIZED.
983                  */
984                 fio_gettime(&this_start, NULL);
985                 left = this_jobs;
986                 while (left && !fio_abort) {
987                         if (mtime_since_now(&this_start) > JOB_START_TIMEOUT)
988                                 break;
989
990                         usleep(100000);
991
992                         for (i = 0; i < this_jobs; i++) {
993                                 td = map[i];
994                                 if (!td)
995                                         continue;
996                                 if (td->runstate == TD_INITIALIZED) {
997                                         map[i] = NULL;
998                                         left--;
999                                 } else if (td->runstate >= TD_EXITED) {
1000                                         map[i] = NULL;
1001                                         left--;
1002                                         todo--;
1003                                         nr_running++; /* work-around... */
1004                                 }
1005                         }
1006                 }
1007
1008                 if (left) {
1009                         log_err("fio: %d jobs failed to start\n", left);
1010                         for (i = 0; i < this_jobs; i++) {
1011                                 td = map[i];
1012                                 if (!td)
1013                                         continue;
1014                                 kill(td->pid, SIGTERM);
1015                         }
1016                         break;
1017                 }
1018
1019                 /*
1020                  * start created threads (TD_INITIALIZED -> TD_RUNNING).
1021                  */
1022                 for_each_td(td, i) {
1023                         if (td->runstate != TD_INITIALIZED)
1024                                 continue;
1025
1026                         td_set_runstate(td, TD_RUNNING);
1027                         nr_running++;
1028                         nr_started--;
1029                         m_rate += td->ratemin;
1030                         t_rate += td->rate;
1031                         todo--;
1032                         fio_sem_up(&td->mutex);
1033                 }
1034
1035                 reap_threads(&nr_running, &t_rate, &m_rate);
1036
1037                 if (todo)
1038                         usleep(100000);
1039         }
1040
1041         while (nr_running) {
1042                 reap_threads(&nr_running, &t_rate, &m_rate);
1043                 usleep(10000);
1044         }
1045
1046         update_io_ticks();
1047         fio_unpin_memory();
1048 }
1049
1050 int main(int argc, char *argv[])
1051 {
1052         long ps;
1053
1054         /*
1055          * We need locale for number printing, if it isn't set then just
1056          * go with the US format.
1057          */
1058         if (!getenv("LC_NUMERIC"))
1059                 setlocale(LC_NUMERIC, "en_US");
1060
1061         if (parse_options(argc, argv))
1062                 return 1;
1063
1064         if (!thread_number) {
1065                 log_err("Nothing to do\n");
1066                 return 1;
1067         }
1068
1069         ps = sysconf(_SC_PAGESIZE);
1070         if (ps < 0) {
1071                 log_err("Failed to get page size\n");
1072                 return 1;
1073         }
1074
1075         page_mask = ps - 1;
1076
1077         if (write_bw_log) {
1078                 setup_log(&agg_io_log[DDIR_READ]);
1079                 setup_log(&agg_io_log[DDIR_WRITE]);
1080         }
1081
1082         disk_util_timer_arm();
1083
1084         run_threads();
1085
1086         if (!fio_abort) {
1087                 show_run_stats();
1088                 if (write_bw_log) {
1089                         __finish_log(agg_io_log[DDIR_READ],"agg-read_bw.log");
1090                         __finish_log(agg_io_log[DDIR_WRITE],"agg-write_bw.log");
1091                 }
1092         }
1093
1094         return exit_value;
1095 }