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