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