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