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