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