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