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