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