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