7a420daf909afb84009792d63d2b146d85ce520d
[fio.git] / fio.c
1 /*
2  * fio - the flexible io tester
3  *
4  * Copyright (C) 2005 Jens Axboe <axboe@suse.de>
5  * Copyright (C) 2006 Jens Axboe <axboe@kernel.dk>
6  *
7  * The license below covers all files distributed with fio unless otherwise
8  * noted in the file itself.
9  *
10  *  This program is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License version 2 as
12  *  published by the Free Software Foundation.
13  *
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License
20  *  along with this program; if not, write to the Free Software
21  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  *
23  */
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <string.h>
27 #include <signal.h>
28 #include <time.h>
29 #include <locale.h>
30 #include <assert.h>
31 #include <sys/stat.h>
32 #include <sys/wait.h>
33 #include <sys/ipc.h>
34 #include <sys/shm.h>
35 #include <sys/mman.h>
36
37 #include "fio.h"
38 #include "hash.h"
39 #include "smalloc.h"
40
41 unsigned long page_mask;
42 unsigned long page_size;
43 #define ALIGN(buf)      \
44         (char *) (((unsigned long) (buf) + page_mask) & ~page_mask)
45
46 int groupid = 0;
47 int thread_number = 0;
48 int nr_process = 0;
49 int nr_thread = 0;
50 int shm_id = 0;
51 int temp_stall_ts;
52 unsigned long done_secs = 0;
53
54 static struct fio_mutex *startup_mutex;
55 static volatile int fio_abort;
56 static int exit_value;
57 static struct itimerval itimer;
58
59 struct io_log *agg_io_log[2];
60
61 #define TERMINATE_ALL           (-1)
62 #define JOB_START_TIMEOUT       (5 * 1000)
63
64 static inline void td_set_runstate(struct thread_data *td, int runstate)
65 {
66         if (td->runstate == runstate)
67                 return;
68
69         dprint(FD_PROCESS, "pid=%d: runstate %d -> %d\n", (int) td->pid,
70                                                 td->runstate, runstate);
71         td->runstate = runstate;
72 }
73
74 static void terminate_threads(int group_id)
75 {
76         struct thread_data *td;
77         int i;
78
79         dprint(FD_PROCESS, "terminate group_id=%d\n", group_id);
80
81         for_each_td(td, i) {
82                 if (group_id == TERMINATE_ALL || groupid == td->groupid) {
83                         dprint(FD_PROCESS, "setting terminate on %s/%d\n",
84                                                 td->o.name, (int) td->pid);
85                         td->terminate = 1;
86                         td->o.start_delay = 0;
87
88                         /*
89                          * if the thread is running, just let it exit
90                          */
91                         if (td->runstate < TD_RUNNING)
92                                 kill(td->pid, SIGQUIT);
93                         else {
94                                 struct ioengine_ops *ops = td->io_ops;
95
96                                 if (ops && (ops->flags & FIO_SIGQUIT))
97                                         kill(td->pid, SIGQUIT);
98                         }
99                 }
100         }
101 }
102
103 static void status_timer_arm(void)
104 {
105         itimer.it_value.tv_sec = 0;
106         itimer.it_value.tv_usec = DISK_UTIL_MSEC * 1000;
107         setitimer(ITIMER_REAL, &itimer, NULL);
108 }
109
110 /*
111  * We need to rearm on BSD/solaris. Switch this to sigaction in the future...
112  */
113 static void set_sig_handlers(void (*sighandler)(int))
114 {
115         signal(SIGINT, sighandler);
116         signal(SIGALRM, sighandler);
117 }
118
119 static void sig_handler(int sig)
120 {
121         set_sig_handlers(sig_handler);
122
123         if (!threads)
124                 return;
125
126         switch (sig) {
127         case SIGALRM:
128                 update_io_ticks();
129                 print_thread_status();
130                 status_timer_arm();
131                 break;
132         default:
133                 printf("\nfio: terminating on signal %d\n", sig);
134                 fflush(stdout);
135                 terminate_threads(TERMINATE_ALL);
136                 break;
137         }
138 }
139
140 /*
141  * Check if we are above the minimum rate given.
142  */
143 static int check_min_rate(struct thread_data *td, struct timeval *now)
144 {
145         unsigned long long bytes = 0;
146         unsigned long iops = 0;
147         unsigned long spent;
148         unsigned long rate;
149
150         /*
151          * No minimum rate set, always ok
152          */
153         if (!td->o.ratemin && !td->o.rate_iops_min)
154                 return 0;
155
156         /*
157          * allow a 2 second settle period in the beginning
158          */
159         if (mtime_since(&td->start, now) < 2000)
160                 return 0;
161
162         if (td_read(td)) {
163                 iops += td->io_blocks[DDIR_READ];
164                 bytes += td->this_io_bytes[DDIR_READ];
165         }
166         if (td_write(td)) {
167                 iops += td->io_blocks[DDIR_WRITE];
168                 bytes += td->this_io_bytes[DDIR_WRITE];
169         }
170
171         /*
172          * if rate blocks is set, sample is running
173          */
174         if (td->rate_bytes || td->rate_blocks) {
175                 spent = mtime_since(&td->lastrate, now);
176                 if (spent < td->o.ratecycle)
177                         return 0;
178
179                 if (td->o.rate) {
180                         /*
181                          * check bandwidth specified rate
182                          */
183                         if (bytes < td->rate_bytes) {
184                                 log_err("%s: min rate %u not met\n", td->o.name,
185                                                                 td->o.ratemin);
186                                 return 1;
187                         } else {
188                                 rate = (bytes - td->rate_bytes) / spent;
189                                 if (rate < td->o.ratemin ||
190                                     bytes < td->rate_bytes) {
191                                         log_err("%s: min rate %u not met, got"
192                                                 " %luKiB/sec\n", td->o.name,
193                                                         td->o.ratemin, rate);
194                                         return 1;
195                                 }
196                         }
197                 } else {
198                         /*
199                          * checks iops specified rate
200                          */
201                         if (iops < td->o.rate_iops) {
202                                 log_err("%s: min iops rate %u not met\n",
203                                                 td->o.name, td->o.rate_iops);
204                                 return 1;
205                         } else {
206                                 rate = (iops - td->rate_blocks) / spent;
207                                 if (rate < td->o.rate_iops_min ||
208                                     iops < td->rate_blocks) {
209                                         log_err("%s: min iops rate %u not met,"
210                                                 " got %lu\n", td->o.name,
211                                                         td->o.rate_iops_min,
212                                                         rate);
213                                 }
214                         }
215                 }
216         }
217
218         td->rate_bytes = bytes;
219         td->rate_blocks = iops;
220         memcpy(&td->lastrate, now, sizeof(*now));
221         return 0;
222 }
223
224 static inline int runtime_exceeded(struct thread_data *td, struct timeval *t)
225 {
226         if (!td->o.timeout)
227                 return 0;
228         if (mtime_since(&td->epoch, t) >= td->o.timeout * 1000)
229                 return 1;
230
231         return 0;
232 }
233
234 /*
235  * When job exits, we can cancel the in-flight IO if we are using async
236  * io. Attempt to do so.
237  */
238 static void cleanup_pending_aio(struct thread_data *td)
239 {
240         struct list_head *entry, *n;
241         struct io_u *io_u;
242         int r;
243
244         /*
245          * get immediately available events, if any
246          */
247         r = io_u_queued_complete(td, 0);
248         if (r < 0)
249                 return;
250
251         /*
252          * now cancel remaining active events
253          */
254         if (td->io_ops->cancel) {
255                 list_for_each_safe(entry, n, &td->io_u_busylist) {
256                         io_u = list_entry(entry, struct io_u, list);
257
258                         /*
259                          * if the io_u isn't in flight, then that generally
260                          * means someone leaked an io_u. complain but fix
261                          * it up, so we don't stall here.
262                          */
263                         if ((io_u->flags & IO_U_F_FLIGHT) == 0) {
264                                 log_err("fio: non-busy IO on busy list\n");
265                                 put_io_u(td, io_u);
266                         } else {
267                                 r = td->io_ops->cancel(td, io_u);
268                                 if (!r)
269                                         put_io_u(td, io_u);
270                         }
271                 }
272         }
273
274         if (td->cur_depth)
275                 r = io_u_queued_complete(td, td->cur_depth);
276 }
277
278 /*
279  * Helper to handle the final sync of a file. Works just like the normal
280  * io path, just does everything sync.
281  */
282 static int fio_io_sync(struct thread_data *td, struct fio_file *f)
283 {
284         struct io_u *io_u = __get_io_u(td);
285         int ret;
286
287         if (!io_u)
288                 return 1;
289
290         io_u->ddir = DDIR_SYNC;
291         io_u->file = f;
292
293         if (td_io_prep(td, io_u)) {
294                 put_io_u(td, io_u);
295                 return 1;
296         }
297
298 requeue:
299         ret = td_io_queue(td, io_u);
300         if (ret < 0) {
301                 td_verror(td, io_u->error, "td_io_queue");
302                 put_io_u(td, io_u);
303                 return 1;
304         } else if (ret == FIO_Q_QUEUED) {
305                 if (io_u_queued_complete(td, 1) < 0)
306                         return 1;
307         } else if (ret == FIO_Q_COMPLETED) {
308                 if (io_u->error) {
309                         td_verror(td, io_u->error, "td_io_queue");
310                         return 1;
311                 }
312
313                 if (io_u_sync_complete(td, io_u) < 0)
314                         return 1;
315         } else if (ret == FIO_Q_BUSY) {
316                 if (td_io_commit(td))
317                         return 1;
318                 goto requeue;
319         }
320
321         return 0;
322 }
323
324 /*
325  * The main verify engine. Runs over the writes we previously submitted,
326  * reads the blocks back in, and checks the crc/md5 of the data.
327  */
328 static void do_verify(struct thread_data *td)
329 {
330         struct fio_file *f;
331         struct io_u *io_u;
332         int ret, min_events;
333         unsigned int i;
334
335         /*
336          * sync io first and invalidate cache, to make sure we really
337          * read from disk.
338          */
339         for_each_file(td, f, i) {
340                 if (!(f->flags & FIO_FILE_OPEN))
341                         continue;
342                 if (fio_io_sync(td, f))
343                         break;
344                 if (file_invalidate_cache(td, f))
345                         break;
346         }
347
348         if (td->error)
349                 return;
350
351         td_set_runstate(td, TD_VERIFYING);
352
353         io_u = NULL;
354         while (!td->terminate) {
355                 int ret2;
356
357                 io_u = __get_io_u(td);
358                 if (!io_u)
359                         break;
360
361                 if (runtime_exceeded(td, &io_u->start_time)) {
362                         put_io_u(td, io_u);
363                         td->terminate = 1;
364                         break;
365                 }
366
367                 if (get_next_verify(td, io_u)) {
368                         put_io_u(td, io_u);
369                         break;
370                 }
371
372                 if (td_io_prep(td, io_u)) {
373                         put_io_u(td, io_u);
374                         break;
375                 }
376
377                 io_u->end_io = verify_io_u;
378
379                 ret = td_io_queue(td, io_u);
380                 switch (ret) {
381                 case FIO_Q_COMPLETED:
382                         if (io_u->error)
383                                 ret = -io_u->error;
384                         else if (io_u->resid) {
385                                 int bytes = io_u->xfer_buflen - io_u->resid;
386                                 struct fio_file *f = io_u->file;
387
388                                 /*
389                                  * zero read, fail
390                                  */
391                                 if (!bytes) {
392                                         td_verror(td, ENODATA, "full resid");
393                                         put_io_u(td, io_u);
394                                         break;
395                                 }
396
397                                 io_u->xfer_buflen = io_u->resid;
398                                 io_u->xfer_buf += bytes;
399                                 io_u->offset += bytes;
400
401                                 td->ts.short_io_u[io_u->ddir]++;
402
403                                 if (io_u->offset == f->real_file_size)
404                                         goto sync_done;
405
406                                 requeue_io_u(td, &io_u);
407                         } else {
408 sync_done:
409                                 ret = io_u_sync_complete(td, io_u);
410                                 if (ret < 0)
411                                         break;
412                         }
413                         continue;
414                 case FIO_Q_QUEUED:
415                         break;
416                 case FIO_Q_BUSY:
417                         requeue_io_u(td, &io_u);
418                         ret2 = td_io_commit(td);
419                         if (ret2 < 0)
420                                 ret = ret2;
421                         break;
422                 default:
423                         assert(ret < 0);
424                         td_verror(td, -ret, "td_io_queue");
425                         break;
426                 }
427
428                 if (ret < 0 || td->error)
429                         break;
430
431                 /*
432                  * if we can queue more, do so. but check if there are
433                  * completed io_u's first.
434                  */
435                 min_events = 0;
436                 if (queue_full(td) || ret == FIO_Q_BUSY) {
437                         if (td->cur_depth >= td->o.iodepth_low)
438                                 min_events = td->cur_depth - td->o.iodepth_low;
439                         if (!min_events)
440                                 min_events = 1;
441                 }
442
443                 /*
444                  * Reap required number of io units, if any, and do the
445                  * verification on them through the callback handler
446                  */
447                 if (io_u_queued_complete(td, min_events) < 0)
448                         break;
449         }
450
451         if (!td->error) {
452                 min_events = td->cur_depth;
453
454                 if (min_events)
455                         ret = io_u_queued_complete(td, min_events);
456         } else
457                 cleanup_pending_aio(td);
458
459         td_set_runstate(td, TD_RUNNING);
460 }
461
462 /*
463  * Main IO worker function. It retrieves io_u's to process and queues
464  * and reaps them, checking for rate and errors along the way.
465  */
466 static void do_io(struct thread_data *td)
467 {
468         struct timeval s;
469         unsigned long usec;
470         unsigned int i;
471         int ret = 0;
472
473         td_set_runstate(td, TD_RUNNING);
474
475         while ((td->this_io_bytes[0] + td->this_io_bytes[1]) < td->o.size) {
476                 struct timeval comp_time;
477                 long bytes_done = 0;
478                 int min_evts = 0;
479                 struct io_u *io_u;
480                 int ret2;
481
482                 if (td->terminate)
483                         break;
484
485                 io_u = get_io_u(td);
486                 if (!io_u)
487                         break;
488
489                 memcpy(&s, &io_u->start_time, sizeof(s));
490
491                 if (runtime_exceeded(td, &s)) {
492                         put_io_u(td, io_u);
493                         td->terminate = 1;
494                         break;
495                 }
496
497                 /*
498                  * Add verification end_io handler, if asked to verify
499                  * a previously written file.
500                  */
501                 if (td->o.verify != VERIFY_NONE && io_u->ddir == DDIR_READ) {
502                         io_u->end_io = verify_io_u;
503                         td_set_runstate(td, TD_VERIFYING);
504                 } else
505                         td_set_runstate(td, TD_RUNNING);
506
507                 ret = td_io_queue(td, io_u);
508                 switch (ret) {
509                 case FIO_Q_COMPLETED:
510                         if (io_u->error)
511                                 ret = -io_u->error;
512                         else if (io_u->resid) {
513                                 int bytes = io_u->xfer_buflen - io_u->resid;
514                                 struct fio_file *f = io_u->file;
515
516                                 /*
517                                  * zero read, fail
518                                  */
519                                 if (!bytes) {
520                                         td_verror(td, ENODATA, "full resid");
521                                         put_io_u(td, io_u);
522                                         break;
523                                 }
524
525                                 io_u->xfer_buflen = io_u->resid;
526                                 io_u->xfer_buf += bytes;
527                                 io_u->offset += bytes;
528
529                                 td->ts.short_io_u[io_u->ddir]++;
530
531                                 if (io_u->offset == f->real_file_size)
532                                         goto sync_done;
533
534                                 requeue_io_u(td, &io_u);
535                         } else {
536 sync_done:
537                                 fio_gettime(&comp_time, NULL);
538                                 bytes_done = io_u_sync_complete(td, io_u);
539                                 if (bytes_done < 0)
540                                         ret = bytes_done;
541                         }
542                         break;
543                 case FIO_Q_QUEUED:
544                         /*
545                          * if the engine doesn't have a commit hook,
546                          * the io_u is really queued. if it does have such
547                          * a hook, it has to call io_u_queued() itself.
548                          */
549                         if (td->io_ops->commit == NULL)
550                                 io_u_queued(td, io_u);
551                         break;
552                 case FIO_Q_BUSY:
553                         requeue_io_u(td, &io_u);
554                         ret2 = td_io_commit(td);
555                         if (ret2 < 0)
556                                 ret = ret2;
557                         break;
558                 default:
559                         assert(ret < 0);
560                         put_io_u(td, io_u);
561                         break;
562                 }
563
564                 if (ret < 0 || td->error)
565                         break;
566
567                 /*
568                  * See if we need to complete some commands
569                  */
570                 if (queue_full(td) || ret == FIO_Q_BUSY) {
571                         min_evts = 0;
572                         if (td->cur_depth >= td->o.iodepth_low)
573                                 min_evts = td->cur_depth - td->o.iodepth_low;
574                         if (!min_evts)
575                                 min_evts = 1;
576                         fio_gettime(&comp_time, NULL);
577                         bytes_done = io_u_queued_complete(td, min_evts);
578                         if (bytes_done < 0)
579                                 break;
580                 }
581
582                 if (!bytes_done)
583                         continue;
584
585                 /*
586                  * the rate is batched for now, it should work for batches
587                  * of completions except the very first one which may look
588                  * a little bursty
589                  */
590                 usec = utime_since(&s, &comp_time);
591
592                 rate_throttle(td, usec, bytes_done);
593
594                 if (check_min_rate(td, &comp_time)) {
595                         if (exitall_on_terminate)
596                                 terminate_threads(td->groupid);
597                         td_verror(td, ENODATA, "check_min_rate");
598                         break;
599                 }
600
601                 if (td->o.thinktime) {
602                         unsigned long long b;
603
604                         b = td->io_blocks[0] + td->io_blocks[1];
605                         if (!(b % td->o.thinktime_blocks)) {
606                                 int left;
607
608                                 if (td->o.thinktime_spin)
609                                         __usec_sleep(td->o.thinktime_spin);
610
611                                 left = td->o.thinktime - td->o.thinktime_spin;
612                                 if (left)
613                                         usec_sleep(td, left);
614                         }
615                 }
616         }
617
618         if (td->o.fill_device && td->error == ENOSPC) {
619                 td->error = 0;
620                 td->terminate = 1;
621         }
622         if (!td->error) {
623                 struct fio_file *f;
624
625                 i = td->cur_depth;
626                 if (i)
627                         ret = io_u_queued_complete(td, i);
628
629                 if (should_fsync(td) && td->o.end_fsync) {
630                         td_set_runstate(td, TD_FSYNCING);
631
632                         for_each_file(td, f, i) {
633                                 if (!(f->flags & FIO_FILE_OPEN))
634                                         continue;
635                                 fio_io_sync(td, f);
636                         }
637                 }
638         } else
639                 cleanup_pending_aio(td);
640
641         /*
642          * stop job if we failed doing any IO
643          */
644         if ((td->this_io_bytes[0] + td->this_io_bytes[1]) == 0)
645                 td->done = 1;
646 }
647
648 static void cleanup_io_u(struct thread_data *td)
649 {
650         struct list_head *entry, *n;
651         struct io_u *io_u;
652
653         list_for_each_safe(entry, n, &td->io_u_freelist) {
654                 io_u = list_entry(entry, struct io_u, list);
655
656                 list_del(&io_u->list);
657                 free(io_u);
658         }
659
660         free_io_mem(td);
661 }
662
663 static int init_io_u(struct thread_data *td)
664 {
665         struct io_u *io_u;
666         unsigned int max_bs;
667         int i, max_units;
668         char *p;
669
670         max_units = td->o.iodepth;
671         max_bs = max(td->o.max_bs[DDIR_READ], td->o.max_bs[DDIR_WRITE]);
672         td->orig_buffer_size = (unsigned long long) max_bs
673                                         * (unsigned long long) max_units;
674
675         if (td->o.mem_type == MEM_SHMHUGE || td->o.mem_type == MEM_MMAPHUGE) {
676                 unsigned long bs;
677
678                 bs = td->orig_buffer_size + td->o.hugepage_size - 1;
679                 td->orig_buffer_size = bs & ~(td->o.hugepage_size - 1);
680         }
681
682         if (td->orig_buffer_size != (size_t) td->orig_buffer_size) {
683                 log_err("fio: IO memory too large. Reduce max_bs or iodepth\n");
684                 return 1;
685         }
686
687         if (allocate_io_mem(td))
688                 return 1;
689
690         if (td->o.odirect)
691                 p = ALIGN(td->orig_buffer);
692         else
693                 p = td->orig_buffer;
694
695         for (i = 0; i < max_units; i++) {
696                 if (td->terminate)
697                         return 1;
698                 io_u = malloc(sizeof(*io_u));
699                 memset(io_u, 0, sizeof(*io_u));
700                 INIT_LIST_HEAD(&io_u->list);
701
702                 if (!(td->io_ops->flags & FIO_NOIO)) {
703                         io_u->buf = p + max_bs * i;
704
705                         if (td_write(td) && !td->o.refill_buffers)
706                                 io_u_fill_buffer(td, io_u, max_bs);
707                 }
708
709                 io_u->index = i;
710                 io_u->flags = IO_U_F_FREE;
711                 list_add(&io_u->list, &td->io_u_freelist);
712         }
713
714         io_u_init_timeout();
715
716         return 0;
717 }
718
719 static int switch_ioscheduler(struct thread_data *td)
720 {
721         char tmp[256], tmp2[128];
722         FILE *f;
723         int ret;
724
725         if (td->io_ops->flags & FIO_DISKLESSIO)
726                 return 0;
727
728         sprintf(tmp, "%s/queue/scheduler", td->sysfs_root);
729
730         f = fopen(tmp, "r+");
731         if (!f) {
732                 if (errno == ENOENT) {
733                         log_err("fio: os or kernel doesn't support IO scheduler"
734                                 " switching\n");
735                         return 0;
736                 }
737                 td_verror(td, errno, "fopen iosched");
738                 return 1;
739         }
740
741         /*
742          * Set io scheduler.
743          */
744         ret = fwrite(td->o.ioscheduler, strlen(td->o.ioscheduler), 1, f);
745         if (ferror(f) || ret != 1) {
746                 td_verror(td, errno, "fwrite");
747                 fclose(f);
748                 return 1;
749         }
750
751         rewind(f);
752
753         /*
754          * Read back and check that the selected scheduler is now the default.
755          */
756         ret = fread(tmp, 1, sizeof(tmp), f);
757         if (ferror(f) || ret < 0) {
758                 td_verror(td, errno, "fread");
759                 fclose(f);
760                 return 1;
761         }
762
763         sprintf(tmp2, "[%s]", td->o.ioscheduler);
764         if (!strstr(tmp, tmp2)) {
765                 log_err("fio: io scheduler %s not found\n", td->o.ioscheduler);
766                 td_verror(td, EINVAL, "iosched_switch");
767                 fclose(f);
768                 return 1;
769         }
770
771         fclose(f);
772         return 0;
773 }
774
775 static int keep_running(struct thread_data *td)
776 {
777         unsigned long long io_done;
778
779         if (td->done)
780                 return 0;
781         if (td->o.time_based)
782                 return 1;
783         if (td->o.loops) {
784                 td->o.loops--;
785                 return 1;
786         }
787
788         io_done = td->io_bytes[DDIR_READ] + td->io_bytes[DDIR_WRITE]
789                         + td->io_skip_bytes;
790         if (io_done < td->o.size)
791                 return 1;
792
793         return 0;
794 }
795
796 static int clear_io_state(struct thread_data *td)
797 {
798         struct fio_file *f;
799         unsigned int i;
800         int ret;
801
802         td->ts.stat_io_bytes[0] = td->ts.stat_io_bytes[1] = 0;
803         td->this_io_bytes[0] = td->this_io_bytes[1] = 0;
804         td->zone_bytes = 0;
805         td->rate_bytes = 0;
806         td->rate_blocks = 0;
807         td->rw_end_set[0] = td->rw_end_set[1] = 0;
808
809         td->last_was_sync = 0;
810
811         /*
812          * reset file done count if we are to start over
813          */
814         if (td->o.time_based || td->o.loops)
815                 td->nr_done_files = 0;
816
817         close_files(td);
818
819         ret = 0;
820         for_each_file(td, f, i) {
821                 f->flags &= ~FIO_FILE_DONE;
822                 ret = td_io_open_file(td, f);
823                 if (ret)
824                         break;
825         }
826
827         return ret;
828 }
829
830 /*
831  * Entry point for the thread based jobs. The process based jobs end up
832  * here as well, after a little setup.
833  */
834 static void *thread_main(void *data)
835 {
836         unsigned long long runtime[2], elapsed;
837         struct thread_data *td = data;
838         int clear_state;
839
840         if (!td->o.use_thread)
841                 setsid();
842
843         td->pid = getpid();
844
845         dprint(FD_PROCESS, "jobs pid=%d started\n", (int) td->pid);
846
847         INIT_LIST_HEAD(&td->io_u_freelist);
848         INIT_LIST_HEAD(&td->io_u_busylist);
849         INIT_LIST_HEAD(&td->io_u_requeues);
850         INIT_LIST_HEAD(&td->io_log_list);
851         INIT_LIST_HEAD(&td->io_hist_list);
852         td->io_hist_tree = RB_ROOT;
853
854         td_set_runstate(td, TD_INITIALIZED);
855         fio_mutex_up(startup_mutex);
856         fio_mutex_down(td->mutex);
857
858         /*
859          * the ->mutex mutex is now no longer used, close it to avoid
860          * eating a file descriptor
861          */
862         fio_mutex_remove(td->mutex);
863
864         /*
865          * May alter parameters that init_io_u() will use, so we need to
866          * do this first.
867          */
868         if (init_iolog(td))
869                 goto err;
870
871         if (init_io_u(td))
872                 goto err;
873
874         if (td->o.cpumask_set && fio_setaffinity(td) == -1) {
875                 td_verror(td, errno, "cpu_set_affinity");
876                 goto err;
877         }
878
879         if (td->ioprio_set) {
880                 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, td->ioprio) == -1) {
881                         td_verror(td, errno, "ioprio_set");
882                         goto err;
883                 }
884         }
885
886         if (nice(td->o.nice) == -1) {
887                 td_verror(td, errno, "nice");
888                 goto err;
889         }
890
891         if (td->o.ioscheduler && switch_ioscheduler(td))
892                 goto err;
893
894         if (!td->o.create_serialize && setup_files(td))
895                 goto err;
896
897         if (td_io_init(td))
898                 goto err;
899
900         if (open_files(td))
901                 goto err;
902
903         if (init_random_map(td))
904                 goto err;
905
906         if (td->o.exec_prerun) {
907                 if (system(td->o.exec_prerun) < 0)
908                         goto err;
909         }
910
911         fio_gettime(&td->epoch, NULL);
912         memcpy(&td->timeout_end, &td->epoch, sizeof(td->epoch));
913         getrusage(RUSAGE_SELF, &td->ts.ru_start);
914
915         runtime[0] = runtime[1] = 0;
916         clear_state = 0;
917         while (keep_running(td)) {
918                 fio_gettime(&td->start, NULL);
919                 memcpy(&td->ts.stat_sample_time, &td->start, sizeof(td->start));
920
921                 if (td->o.ratemin)
922                         memcpy(&td->lastrate, &td->ts.stat_sample_time,
923                                                         sizeof(td->lastrate));
924
925                 if (clear_state && clear_io_state(td))
926                         break;
927
928                 prune_io_piece_log(td);
929
930                 do_io(td);
931
932                 clear_state = 1;
933
934                 if (td_read(td) && td->io_bytes[DDIR_READ]) {
935                         if (td->rw_end_set[DDIR_READ])
936                                 elapsed = utime_since(&td->start,
937                                                       &td->rw_end[DDIR_READ]);
938                         else
939                                 elapsed = utime_since_now(&td->start);
940
941                         runtime[DDIR_READ] += elapsed;
942                 }
943                 if (td_write(td) && td->io_bytes[DDIR_WRITE]) {
944                         if (td->rw_end_set[DDIR_WRITE])
945                                 elapsed = utime_since(&td->start,
946                                                       &td->rw_end[DDIR_WRITE]);
947                         else
948                                 elapsed = utime_since_now(&td->start);
949
950                         runtime[DDIR_WRITE] += elapsed;
951                 }
952
953                 if (td->error || td->terminate)
954                         break;
955
956                 if (!td->o.do_verify ||
957                     td->o.verify == VERIFY_NONE ||
958                     (td->io_ops->flags & FIO_UNIDIR))
959                         continue;
960
961                 if (clear_io_state(td))
962                         break;
963
964                 fio_gettime(&td->start, NULL);
965
966                 do_verify(td);
967
968                 runtime[DDIR_READ] += utime_since_now(&td->start);
969
970                 if (td->error || td->terminate)
971                         break;
972         }
973
974         update_rusage_stat(td);
975         td->ts.runtime[0] = (runtime[0] + 999) / 1000;
976         td->ts.runtime[1] = (runtime[1] + 999) / 1000;
977         td->ts.total_run_time = mtime_since_now(&td->epoch);
978         td->ts.io_bytes[0] = td->io_bytes[0];
979         td->ts.io_bytes[1] = td->io_bytes[1];
980
981         if (td->ts.bw_log)
982                 finish_log(td, td->ts.bw_log, "bw");
983         if (td->ts.slat_log)
984                 finish_log(td, td->ts.slat_log, "slat");
985         if (td->ts.clat_log)
986                 finish_log(td, td->ts.clat_log, "clat");
987         if (td->o.exec_postrun) {
988                 if (system(td->o.exec_postrun) < 0)
989                         log_err("fio: postrun %s failed\n", td->o.exec_postrun);
990         }
991
992         if (exitall_on_terminate)
993                 terminate_threads(td->groupid);
994
995 err:
996         if (td->error)
997                 printf("fio: pid=%d, err=%d/%s\n", (int) td->pid, td->error,
998                                                         td->verror);
999         close_and_free_files(td);
1000         close_ioengine(td);
1001         cleanup_io_u(td);
1002
1003         /*
1004          * do this very late, it will log file closing as well
1005          */
1006         if (td->o.write_iolog_file)
1007                 write_iolog_close(td);
1008
1009         options_mem_free(td);
1010         td_set_runstate(td, TD_EXITED);
1011         return (void *) (unsigned long) td->error;
1012 }
1013
1014 /*
1015  * We cannot pass the td data into a forked process, so attach the td and
1016  * pass it to the thread worker.
1017  */
1018 static int fork_main(int shmid, int offset)
1019 {
1020         struct thread_data *td;
1021         void *data, *ret;
1022
1023         data = shmat(shmid, NULL, 0);
1024         if (data == (void *) -1) {
1025                 int __err = errno;
1026
1027                 perror("shmat");
1028                 return __err;
1029         }
1030
1031         td = data + offset * sizeof(struct thread_data);
1032         ret = thread_main(td);
1033         shmdt(data);
1034         return (int) (unsigned long) ret;
1035 }
1036
1037 /*
1038  * Run over the job map and reap the threads that have exited, if any.
1039  */
1040 static void reap_threads(int *nr_running, int *t_rate, int *m_rate)
1041 {
1042         struct thread_data *td;
1043         int i, cputhreads, realthreads, pending, status, ret;
1044
1045         /*
1046          * reap exited threads (TD_EXITED -> TD_REAPED)
1047          */
1048         realthreads = pending = cputhreads = 0;
1049         for_each_td(td, i) {
1050                 int flags = 0;
1051
1052                 /*
1053                  * ->io_ops is NULL for a thread that has closed its
1054                  * io engine
1055                  */
1056                 if (td->io_ops && !strcmp(td->io_ops->name, "cpuio"))
1057                         cputhreads++;
1058                 else
1059                         realthreads++;
1060
1061                 if (!td->pid) {
1062                         pending++;
1063                         continue;
1064                 }
1065                 if (td->runstate == TD_REAPED)
1066                         continue;
1067                 if (td->o.use_thread) {
1068                         if (td->runstate == TD_EXITED) {
1069                                 td_set_runstate(td, TD_REAPED);
1070                                 goto reaped;
1071                         }
1072                         continue;
1073                 }
1074
1075                 flags = WNOHANG;
1076                 if (td->runstate == TD_EXITED)
1077                         flags = 0;
1078
1079                 /*
1080                  * check if someone quit or got killed in an unusual way
1081                  */
1082                 ret = waitpid(td->pid, &status, flags);
1083                 if (ret < 0) {
1084                         if (errno == ECHILD) {
1085                                 log_err("fio: pid=%d disappeared %d\n",
1086                                                 (int) td->pid, td->runstate);
1087                                 td_set_runstate(td, TD_REAPED);
1088                                 goto reaped;
1089                         }
1090                         perror("waitpid");
1091                 } else if (ret == td->pid) {
1092                         if (WIFSIGNALED(status)) {
1093                                 int sig = WTERMSIG(status);
1094
1095                                 if (sig != SIGQUIT)
1096                                         log_err("fio: pid=%d, got signal=%d\n",
1097                                                         (int) td->pid, sig);
1098                                 td_set_runstate(td, TD_REAPED);
1099                                 goto reaped;
1100                         }
1101                         if (WIFEXITED(status)) {
1102                                 if (WEXITSTATUS(status) && !td->error)
1103                                         td->error = WEXITSTATUS(status);
1104
1105                                 td_set_runstate(td, TD_REAPED);
1106                                 goto reaped;
1107                         }
1108                 }
1109
1110                 /*
1111                  * thread is not dead, continue
1112                  */
1113                 pending++;
1114                 continue;
1115 reaped:
1116                 (*nr_running)--;
1117                 (*m_rate) -= td->o.ratemin;
1118                 (*t_rate) -= td->o.rate;
1119                 if (!td->pid)
1120                         pending--;
1121
1122                 if (td->error)
1123                         exit_value++;
1124
1125                 done_secs += mtime_since_now(&td->epoch) / 1000;
1126         }
1127
1128         if (*nr_running == cputhreads && !pending && realthreads)
1129                 terminate_threads(TERMINATE_ALL);
1130 }
1131
1132 /*
1133  * Main function for kicking off and reaping jobs, as needed.
1134  */
1135 static void run_threads(void)
1136 {
1137         struct thread_data *td;
1138         unsigned long spent;
1139         int i, todo, nr_running, m_rate, t_rate, nr_started;
1140
1141         if (fio_pin_memory())
1142                 return;
1143
1144         if (!terse_output) {
1145                 printf("Starting ");
1146                 if (nr_thread)
1147                         printf("%d thread%s", nr_thread,
1148                                                 nr_thread > 1 ? "s" : "");
1149                 if (nr_process) {
1150                         if (nr_thread)
1151                                 printf(" and ");
1152                         printf("%d process%s", nr_process,
1153                                                 nr_process > 1 ? "es" : "");
1154                 }
1155                 printf("\n");
1156                 fflush(stdout);
1157         }
1158
1159         set_sig_handlers(sig_handler);
1160
1161         todo = thread_number;
1162         nr_running = 0;
1163         nr_started = 0;
1164         m_rate = t_rate = 0;
1165
1166         for_each_td(td, i) {
1167                 print_status_init(td->thread_number - 1);
1168
1169                 if (!td->o.create_serialize) {
1170                         init_disk_util(td);
1171                         continue;
1172                 }
1173
1174                 /*
1175                  * do file setup here so it happens sequentially,
1176                  * we don't want X number of threads getting their
1177                  * client data interspersed on disk
1178                  */
1179                 if (setup_files(td)) {
1180                         exit_value++;
1181                         if (td->error)
1182                                 log_err("fio: pid=%d, err=%d/%s\n",
1183                                         (int) td->pid, td->error, td->verror);
1184                         td_set_runstate(td, TD_REAPED);
1185                         todo--;
1186                 } else {
1187                         struct fio_file *f;
1188                         unsigned int i;
1189
1190                         /*
1191                          * for sharing to work, each job must always open
1192                          * its own files. so close them, if we opened them
1193                          * for creation
1194                          */
1195                         for_each_file(td, f, i)
1196                                 td_io_close_file(td, f);
1197                 }
1198
1199                 init_disk_util(td);
1200         }
1201
1202         set_genesis_time();
1203
1204         while (todo) {
1205                 struct thread_data *map[MAX_JOBS];
1206                 struct timeval this_start;
1207                 int this_jobs = 0, left;
1208
1209                 /*
1210                  * create threads (TD_NOT_CREATED -> TD_CREATED)
1211                  */
1212                 for_each_td(td, i) {
1213                         if (td->runstate != TD_NOT_CREATED)
1214                                 continue;
1215
1216                         /*
1217                          * never got a chance to start, killed by other
1218                          * thread for some reason
1219                          */
1220                         if (td->terminate) {
1221                                 todo--;
1222                                 continue;
1223                         }
1224
1225                         if (td->o.start_delay) {
1226                                 spent = mtime_since_genesis();
1227
1228                                 if (td->o.start_delay * 1000 > spent)
1229                                         continue;
1230                         }
1231
1232                         if (td->o.stonewall && (nr_started || nr_running)) {
1233                                 dprint(FD_PROCESS, "%s: stonewall wait\n",
1234                                                         td->o.name);
1235                                 break;
1236                         }
1237
1238                         /*
1239                          * Set state to created. Thread will transition
1240                          * to TD_INITIALIZED when it's done setting up.
1241                          */
1242                         td_set_runstate(td, TD_CREATED);
1243                         map[this_jobs++] = td;
1244                         nr_started++;
1245
1246                         if (td->o.use_thread) {
1247                                 dprint(FD_PROCESS, "will pthread_create\n");
1248                                 if (pthread_create(&td->thread, NULL,
1249                                                    thread_main, td)) {
1250                                         perror("pthread_create");
1251                                         nr_started--;
1252                                         break;
1253                                 }
1254                                 if (pthread_detach(td->thread) < 0)
1255                                         perror("pthread_detach");
1256                         } else {
1257                                 pid_t pid;
1258                                 dprint(FD_PROCESS, "will fork\n");
1259                                 pid = fork();
1260                                 if (!pid) {
1261                                         int ret = fork_main(shm_id, i);
1262
1263                                         _exit(ret);
1264                                 } else if (i == fio_debug_jobno)
1265                                         *fio_debug_jobp = pid;
1266                         }
1267                         fio_mutex_down(startup_mutex);
1268                 }
1269
1270                 /*
1271                  * Wait for the started threads to transition to
1272                  * TD_INITIALIZED.
1273                  */
1274                 fio_gettime(&this_start, NULL);
1275                 left = this_jobs;
1276                 while (left && !fio_abort) {
1277                         if (mtime_since_now(&this_start) > JOB_START_TIMEOUT)
1278                                 break;
1279
1280                         usleep(100000);
1281
1282                         for (i = 0; i < this_jobs; i++) {
1283                                 td = map[i];
1284                                 if (!td)
1285                                         continue;
1286                                 if (td->runstate == TD_INITIALIZED) {
1287                                         map[i] = NULL;
1288                                         left--;
1289                                 } else if (td->runstate >= TD_EXITED) {
1290                                         map[i] = NULL;
1291                                         left--;
1292                                         todo--;
1293                                         nr_running++; /* work-around... */
1294                                 }
1295                         }
1296                 }
1297
1298                 if (left) {
1299                         log_err("fio: %d jobs failed to start\n", left);
1300                         for (i = 0; i < this_jobs; i++) {
1301                                 td = map[i];
1302                                 if (!td)
1303                                         continue;
1304                                 kill(td->pid, SIGTERM);
1305                         }
1306                         break;
1307                 }
1308
1309                 /*
1310                  * start created threads (TD_INITIALIZED -> TD_RUNNING).
1311                  */
1312                 for_each_td(td, i) {
1313                         if (td->runstate != TD_INITIALIZED)
1314                                 continue;
1315
1316                         td_set_runstate(td, TD_RUNNING);
1317                         nr_running++;
1318                         nr_started--;
1319                         m_rate += td->o.ratemin;
1320                         t_rate += td->o.rate;
1321                         todo--;
1322                         fio_mutex_up(td->mutex);
1323                 }
1324
1325                 reap_threads(&nr_running, &t_rate, &m_rate);
1326
1327                 if (todo)
1328                         usleep(100000);
1329         }
1330
1331         while (nr_running) {
1332                 reap_threads(&nr_running, &t_rate, &m_rate);
1333                 usleep(10000);
1334         }
1335
1336         update_io_ticks();
1337         fio_unpin_memory();
1338 }
1339
1340 int main(int argc, char *argv[])
1341 {
1342         long ps;
1343
1344         sinit();
1345
1346         /*
1347          * We need locale for number printing, if it isn't set then just
1348          * go with the US format.
1349          */
1350         if (!getenv("LC_NUMERIC"))
1351                 setlocale(LC_NUMERIC, "en_US");
1352
1353         if (parse_options(argc, argv))
1354                 return 1;
1355
1356         if (!thread_number)
1357                 return 0;
1358
1359         ps = sysconf(_SC_PAGESIZE);
1360         if (ps < 0) {
1361                 log_err("Failed to get page size\n");
1362                 return 1;
1363         }
1364
1365         page_size = ps;
1366         page_mask = ps - 1;
1367
1368         if (write_bw_log) {
1369                 setup_log(&agg_io_log[DDIR_READ]);
1370                 setup_log(&agg_io_log[DDIR_WRITE]);
1371         }
1372
1373         startup_mutex = fio_mutex_init(0);
1374
1375         set_genesis_time();
1376
1377         status_timer_arm();
1378
1379         run_threads();
1380
1381         if (!fio_abort) {
1382                 show_run_stats();
1383                 if (write_bw_log) {
1384                         __finish_log(agg_io_log[DDIR_READ], "agg-read_bw.log");
1385                         __finish_log(agg_io_log[DDIR_WRITE],
1386                                         "agg-write_bw.log");
1387                 }
1388         }
1389
1390         fio_mutex_remove(startup_mutex);
1391         return exit_value;
1392 }