client/server: track and handle command timeouts
[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 <limits.h>
28 #include <signal.h>
29 #include <time.h>
30 #include <locale.h>
31 #include <assert.h>
32 #include <time.h>
33 #include <sys/stat.h>
34 #include <sys/wait.h>
35 #include <sys/ipc.h>
36 #include <sys/shm.h>
37 #include <sys/mman.h>
38
39 #include "fio.h"
40 #include "hash.h"
41 #include "smalloc.h"
42 #include "verify.h"
43 #include "trim.h"
44 #include "diskutil.h"
45 #include "cgroup.h"
46 #include "profile.h"
47 #include "lib/rand.h"
48 #include "memalign.h"
49 #include "server.h"
50
51 unsigned long page_mask;
52 unsigned long page_size;
53
54 #define PAGE_ALIGN(buf) \
55         (char *) (((unsigned long) (buf) + page_mask) & ~page_mask)
56
57 int groupid = 0;
58 int thread_number = 0;
59 int nr_process = 0;
60 int nr_thread = 0;
61 int shm_id = 0;
62 int temp_stall_ts;
63 unsigned long done_secs = 0;
64
65 static struct fio_mutex *startup_mutex;
66 static struct fio_mutex *writeout_mutex;
67 static volatile int fio_abort;
68 static int exit_value;
69 static pthread_t gtod_thread;
70 static pthread_t disk_util_thread;
71 static struct flist_head *cgroup_list;
72 static char *cgroup_mnt;
73
74 unsigned long arch_flags = 0;
75
76 struct io_log *agg_io_log[2];
77
78 #define JOB_START_TIMEOUT       (5 * 1000)
79
80 static const char *fio_os_strings[os_nr] = {
81         "Invalid",
82         "Linux",
83         "AIX",
84         "FreeBSD",
85         "HP-UX",
86         "OSX",
87         "NetBSD",
88         "Solaris",
89         "Windows"
90 };
91
92 static const char *fio_arch_strings[arch_nr] = {
93         "Invalid",
94         "x86-64",
95         "x86",
96         "ppc",
97         "ia64",
98         "s390",
99         "alpha",
100         "sparc",
101         "sparc64",
102         "arm",
103         "sh",
104         "hppa",
105         "generic"
106 };
107
108 const char *fio_get_os_string(int nr)
109 {
110         if (nr < os_nr)
111                 return fio_os_strings[nr];
112
113         return NULL;
114 }
115
116 const char *fio_get_arch_string(int nr)
117 {
118         if (nr < arch_nr)
119                 return fio_arch_strings[nr];
120
121         return NULL;
122 }
123
124 void td_set_runstate(struct thread_data *td, int runstate)
125 {
126         if (td->runstate == runstate)
127                 return;
128
129         dprint(FD_PROCESS, "pid=%d: runstate %d -> %d\n", (int) td->pid,
130                                                 td->runstate, runstate);
131         td->runstate = runstate;
132 }
133
134 void fio_terminate_threads(int group_id)
135 {
136         struct thread_data *td;
137         int i;
138
139         dprint(FD_PROCESS, "terminate group_id=%d\n", group_id);
140
141         for_each_td(td, i) {
142                 if (group_id == TERMINATE_ALL || groupid == td->groupid) {
143                         dprint(FD_PROCESS, "setting terminate on %s/%d\n",
144                                                 td->o.name, (int) td->pid);
145                         td->terminate = 1;
146                         td->o.start_delay = 0;
147
148                         /*
149                          * if the thread is running, just let it exit
150                          */
151                         if (!td->pid)
152                                 continue;
153                         else if (td->runstate < TD_RAMP)
154                                 kill(td->pid, SIGTERM);
155                         else {
156                                 struct ioengine_ops *ops = td->io_ops;
157
158                                 if (ops && (ops->flags & FIO_SIGTERM))
159                                         kill(td->pid, SIGTERM);
160                         }
161                 }
162         }
163 }
164
165 static void sig_int(int sig)
166 {
167         if (threads) {
168                 log_info("\nfio: terminating on signal %d\n", sig);
169                 exit_backend = 1;
170                 fflush(stdout);
171                 exit_value = 128;
172                 fio_terminate_threads(TERMINATE_ALL);
173         }
174 }
175
176 static void *disk_thread_main(void *data)
177 {
178         fio_mutex_up(startup_mutex);
179
180         while (threads) {
181                 usleep(DISK_UTIL_MSEC * 1000);
182                 if (!threads)
183                         break;
184                 update_io_ticks();
185
186                 if (!is_backend)
187                         print_thread_status();
188         }
189
190         return NULL;
191 }
192
193 static int create_disk_util_thread(void)
194 {
195         int ret;
196
197         ret = pthread_create(&disk_util_thread, NULL, disk_thread_main, NULL);
198         if (ret) {
199                 log_err("Can't create disk util thread: %s\n", strerror(ret));
200                 return 1;
201         }
202
203         ret = pthread_detach(disk_util_thread);
204         if (ret) {
205                 log_err("Can't detatch disk util thread: %s\n", strerror(ret));
206                 return 1;
207         }
208
209         dprint(FD_MUTEX, "wait on startup_mutex\n");
210         fio_mutex_down(startup_mutex);
211         dprint(FD_MUTEX, "done waiting on startup_mutex\n");
212         return 0;
213 }
214
215 static void set_sig_handlers(void)
216 {
217         struct sigaction act;
218
219         memset(&act, 0, sizeof(act));
220         act.sa_handler = sig_int;
221         act.sa_flags = SA_RESTART;
222         sigaction(SIGINT, &act, NULL);
223
224         memset(&act, 0, sizeof(act));
225         act.sa_handler = sig_int;
226         act.sa_flags = SA_RESTART;
227         sigaction(SIGTERM, &act, NULL);
228
229         if (is_backend) {
230                 memset(&act, 0, sizeof(act));
231                 act.sa_handler = sig_int;
232                 act.sa_flags = SA_RESTART;
233                 sigaction(SIGPIPE, &act, NULL);
234         }
235 }
236
237 /*
238  * Check if we are above the minimum rate given.
239  */
240 static int __check_min_rate(struct thread_data *td, struct timeval *now,
241                             enum fio_ddir ddir)
242 {
243         unsigned long long bytes = 0;
244         unsigned long iops = 0;
245         unsigned long spent;
246         unsigned long rate;
247         unsigned int ratemin = 0;
248         unsigned int rate_iops = 0;
249         unsigned int rate_iops_min = 0;
250
251         assert(ddir_rw(ddir));
252
253         if (!td->o.ratemin[ddir] && !td->o.rate_iops_min[ddir])
254                 return 0;
255
256         /*
257          * allow a 2 second settle period in the beginning
258          */
259         if (mtime_since(&td->start, now) < 2000)
260                 return 0;
261
262         iops += td->this_io_blocks[ddir];
263         bytes += td->this_io_bytes[ddir];
264         ratemin += td->o.ratemin[ddir];
265         rate_iops += td->o.rate_iops[ddir];
266         rate_iops_min += td->o.rate_iops_min[ddir];
267
268         /*
269          * if rate blocks is set, sample is running
270          */
271         if (td->rate_bytes[ddir] || td->rate_blocks[ddir]) {
272                 spent = mtime_since(&td->lastrate[ddir], now);
273                 if (spent < td->o.ratecycle)
274                         return 0;
275
276                 if (td->o.rate[ddir]) {
277                         /*
278                          * check bandwidth specified rate
279                          */
280                         if (bytes < td->rate_bytes[ddir]) {
281                                 log_err("%s: min rate %u not met\n", td->o.name,
282                                                                 ratemin);
283                                 return 1;
284                         } else {
285                                 rate = ((bytes - td->rate_bytes[ddir]) * 1000) / spent;
286                                 if (rate < ratemin ||
287                                     bytes < td->rate_bytes[ddir]) {
288                                         log_err("%s: min rate %u not met, got"
289                                                 " %luKB/sec\n", td->o.name,
290                                                         ratemin, rate);
291                                         return 1;
292                                 }
293                         }
294                 } else {
295                         /*
296                          * checks iops specified rate
297                          */
298                         if (iops < rate_iops) {
299                                 log_err("%s: min iops rate %u not met\n",
300                                                 td->o.name, rate_iops);
301                                 return 1;
302                         } else {
303                                 rate = ((iops - td->rate_blocks[ddir]) * 1000) / spent;
304                                 if (rate < rate_iops_min ||
305                                     iops < td->rate_blocks[ddir]) {
306                                         log_err("%s: min iops rate %u not met,"
307                                                 " got %lu\n", td->o.name,
308                                                         rate_iops_min, rate);
309                                 }
310                         }
311                 }
312         }
313
314         td->rate_bytes[ddir] = bytes;
315         td->rate_blocks[ddir] = iops;
316         memcpy(&td->lastrate[ddir], now, sizeof(*now));
317         return 0;
318 }
319
320 static int check_min_rate(struct thread_data *td, struct timeval *now,
321                           unsigned long *bytes_done)
322 {
323         int ret = 0;
324
325         if (bytes_done[0])
326                 ret |= __check_min_rate(td, now, 0);
327         if (bytes_done[1])
328                 ret |= __check_min_rate(td, now, 1);
329
330         return ret;
331 }
332
333 static inline int runtime_exceeded(struct thread_data *td, struct timeval *t)
334 {
335         if (!td->o.timeout)
336                 return 0;
337         if (mtime_since(&td->epoch, t) >= td->o.timeout * 1000)
338                 return 1;
339
340         return 0;
341 }
342
343 /*
344  * When job exits, we can cancel the in-flight IO if we are using async
345  * io. Attempt to do so.
346  */
347 static void cleanup_pending_aio(struct thread_data *td)
348 {
349         struct flist_head *entry, *n;
350         struct io_u *io_u;
351         int r;
352
353         /*
354          * get immediately available events, if any
355          */
356         r = io_u_queued_complete(td, 0, NULL);
357         if (r < 0)
358                 return;
359
360         /*
361          * now cancel remaining active events
362          */
363         if (td->io_ops->cancel) {
364                 flist_for_each_safe(entry, n, &td->io_u_busylist) {
365                         io_u = flist_entry(entry, struct io_u, list);
366
367                         /*
368                          * if the io_u isn't in flight, then that generally
369                          * means someone leaked an io_u. complain but fix
370                          * it up, so we don't stall here.
371                          */
372                         if ((io_u->flags & IO_U_F_FLIGHT) == 0) {
373                                 log_err("fio: non-busy IO on busy list\n");
374                                 put_io_u(td, io_u);
375                         } else {
376                                 r = td->io_ops->cancel(td, io_u);
377                                 if (!r)
378                                         put_io_u(td, io_u);
379                         }
380                 }
381         }
382
383         if (td->cur_depth)
384                 r = io_u_queued_complete(td, td->cur_depth, NULL);
385 }
386
387 /*
388  * Helper to handle the final sync of a file. Works just like the normal
389  * io path, just does everything sync.
390  */
391 static int fio_io_sync(struct thread_data *td, struct fio_file *f)
392 {
393         struct io_u *io_u = __get_io_u(td);
394         int ret;
395
396         if (!io_u)
397                 return 1;
398
399         io_u->ddir = DDIR_SYNC;
400         io_u->file = f;
401
402         if (td_io_prep(td, io_u)) {
403                 put_io_u(td, io_u);
404                 return 1;
405         }
406
407 requeue:
408         ret = td_io_queue(td, io_u);
409         if (ret < 0) {
410                 td_verror(td, io_u->error, "td_io_queue");
411                 put_io_u(td, io_u);
412                 return 1;
413         } else if (ret == FIO_Q_QUEUED) {
414                 if (io_u_queued_complete(td, 1, NULL) < 0)
415                         return 1;
416         } else if (ret == FIO_Q_COMPLETED) {
417                 if (io_u->error) {
418                         td_verror(td, io_u->error, "td_io_queue");
419                         return 1;
420                 }
421
422                 if (io_u_sync_complete(td, io_u, NULL) < 0)
423                         return 1;
424         } else if (ret == FIO_Q_BUSY) {
425                 if (td_io_commit(td))
426                         return 1;
427                 goto requeue;
428         }
429
430         return 0;
431 }
432
433 static inline void __update_tv_cache(struct thread_data *td)
434 {
435         fio_gettime(&td->tv_cache, NULL);
436 }
437
438 static inline void update_tv_cache(struct thread_data *td)
439 {
440         if ((++td->tv_cache_nr & td->tv_cache_mask) == td->tv_cache_mask)
441                 __update_tv_cache(td);
442 }
443
444 static int break_on_this_error(struct thread_data *td, int *retptr)
445 {
446         int ret = *retptr;
447
448         if (ret < 0 || td->error) {
449                 int err;
450
451                 if (!td->o.continue_on_error)
452                         return 1;
453
454                 if (ret < 0)
455                         err = -ret;
456                 else
457                         err = td->error;
458
459                 if (td_non_fatal_error(err)) {
460                         /*
461                          * Continue with the I/Os in case of
462                          * a non fatal error.
463                          */
464                         update_error_count(td, err);
465                         td_clear_error(td);
466                         *retptr = 0;
467                         return 0;
468                 } else if (td->o.fill_device && err == ENOSPC) {
469                         /*
470                          * We expect to hit this error if
471                          * fill_device option is set.
472                          */
473                         td_clear_error(td);
474                         td->terminate = 1;
475                         return 1;
476                 } else {
477                         /*
478                          * Stop the I/O in case of a fatal
479                          * error.
480                          */
481                         update_error_count(td, err);
482                         return 1;
483                 }
484         }
485
486         return 0;
487 }
488
489 /*
490  * The main verify engine. Runs over the writes we previously submitted,
491  * reads the blocks back in, and checks the crc/md5 of the data.
492  */
493 static void do_verify(struct thread_data *td)
494 {
495         struct fio_file *f;
496         struct io_u *io_u;
497         int ret, min_events;
498         unsigned int i;
499
500         dprint(FD_VERIFY, "starting loop\n");
501
502         /*
503          * sync io first and invalidate cache, to make sure we really
504          * read from disk.
505          */
506         for_each_file(td, f, i) {
507                 if (!fio_file_open(f))
508                         continue;
509                 if (fio_io_sync(td, f))
510                         break;
511                 if (file_invalidate_cache(td, f))
512                         break;
513         }
514
515         if (td->error)
516                 return;
517
518         td_set_runstate(td, TD_VERIFYING);
519
520         io_u = NULL;
521         while (!td->terminate) {
522                 int ret2, full;
523
524                 update_tv_cache(td);
525
526                 if (runtime_exceeded(td, &td->tv_cache)) {
527                         __update_tv_cache(td);
528                         if (runtime_exceeded(td, &td->tv_cache)) {
529                                 td->terminate = 1;
530                                 break;
531                         }
532                 }
533
534                 io_u = __get_io_u(td);
535                 if (!io_u)
536                         break;
537
538                 if (get_next_verify(td, io_u)) {
539                         put_io_u(td, io_u);
540                         break;
541                 }
542
543                 if (td_io_prep(td, io_u)) {
544                         put_io_u(td, io_u);
545                         break;
546                 }
547
548                 if (td->o.verify_async)
549                         io_u->end_io = verify_io_u_async;
550                 else
551                         io_u->end_io = verify_io_u;
552
553                 ret = td_io_queue(td, io_u);
554                 switch (ret) {
555                 case FIO_Q_COMPLETED:
556                         if (io_u->error) {
557                                 ret = -io_u->error;
558                                 clear_io_u(td, io_u);
559                         } else if (io_u->resid) {
560                                 int bytes = io_u->xfer_buflen - io_u->resid;
561
562                                 /*
563                                  * zero read, fail
564                                  */
565                                 if (!bytes) {
566                                         td_verror(td, EIO, "full resid");
567                                         put_io_u(td, io_u);
568                                         break;
569                                 }
570
571                                 io_u->xfer_buflen = io_u->resid;
572                                 io_u->xfer_buf += bytes;
573                                 io_u->offset += bytes;
574
575                                 if (ddir_rw(io_u->ddir))
576                                         td->ts.short_io_u[io_u->ddir]++;
577
578                                 f = io_u->file;
579                                 if (io_u->offset == f->real_file_size)
580                                         goto sync_done;
581
582                                 requeue_io_u(td, &io_u);
583                         } else {
584 sync_done:
585                                 ret = io_u_sync_complete(td, io_u, NULL);
586                                 if (ret < 0)
587                                         break;
588                         }
589                         continue;
590                 case FIO_Q_QUEUED:
591                         break;
592                 case FIO_Q_BUSY:
593                         requeue_io_u(td, &io_u);
594                         ret2 = td_io_commit(td);
595                         if (ret2 < 0)
596                                 ret = ret2;
597                         break;
598                 default:
599                         assert(ret < 0);
600                         td_verror(td, -ret, "td_io_queue");
601                         break;
602                 }
603
604                 if (break_on_this_error(td, &ret))
605                         break;
606
607                 /*
608                  * if we can queue more, do so. but check if there are
609                  * completed io_u's first. Note that we can get BUSY even
610                  * without IO queued, if the system is resource starved.
611                  */
612                 full = queue_full(td) || (ret == FIO_Q_BUSY && td->cur_depth);
613                 if (full || !td->o.iodepth_batch_complete) {
614                         min_events = min(td->o.iodepth_batch_complete,
615                                          td->cur_depth);
616                         if (full && !min_events && td->o.iodepth_batch_complete != 0)
617                                 min_events = 1;
618
619                         do {
620                                 /*
621                                  * Reap required number of io units, if any,
622                                  * and do the verification on them through
623                                  * the callback handler
624                                  */
625                                 if (io_u_queued_complete(td, min_events, NULL) < 0) {
626                                         ret = -1;
627                                         break;
628                                 }
629                         } while (full && (td->cur_depth > td->o.iodepth_low));
630                 }
631                 if (ret < 0)
632                         break;
633         }
634
635         if (!td->error) {
636                 min_events = td->cur_depth;
637
638                 if (min_events)
639                         ret = io_u_queued_complete(td, min_events, NULL);
640         } else
641                 cleanup_pending_aio(td);
642
643         td_set_runstate(td, TD_RUNNING);
644
645         dprint(FD_VERIFY, "exiting loop\n");
646 }
647
648 /*
649  * Main IO worker function. It retrieves io_u's to process and queues
650  * and reaps them, checking for rate and errors along the way.
651  */
652 static void do_io(struct thread_data *td)
653 {
654         unsigned int i;
655         int ret = 0;
656
657         if (in_ramp_time(td))
658                 td_set_runstate(td, TD_RAMP);
659         else
660                 td_set_runstate(td, TD_RUNNING);
661
662         while ( (td->o.read_iolog_file && !flist_empty(&td->io_log_list)) ||
663                 (!flist_empty(&td->trim_list)) ||
664                 ((td->this_io_bytes[0] + td->this_io_bytes[1]) < td->o.size) ) {
665                 struct timeval comp_time;
666                 unsigned long bytes_done[2] = { 0, 0 };
667                 int min_evts = 0;
668                 struct io_u *io_u;
669                 int ret2, full;
670
671                 if (td->terminate)
672                         break;
673
674                 update_tv_cache(td);
675
676                 if (runtime_exceeded(td, &td->tv_cache)) {
677                         __update_tv_cache(td);
678                         if (runtime_exceeded(td, &td->tv_cache)) {
679                                 td->terminate = 1;
680                                 break;
681                         }
682                 }
683
684                 io_u = get_io_u(td);
685                 if (!io_u)
686                         break;
687
688                 /*
689                  * Add verification end_io handler, if asked to verify
690                  * a previously written file.
691                  */
692                 if (td->o.verify != VERIFY_NONE && io_u->ddir == DDIR_READ &&
693                     !td_rw(td)) {
694                         if (td->o.verify_async)
695                                 io_u->end_io = verify_io_u_async;
696                         else
697                                 io_u->end_io = verify_io_u;
698                         td_set_runstate(td, TD_VERIFYING);
699                 } else if (in_ramp_time(td))
700                         td_set_runstate(td, TD_RAMP);
701                 else
702                         td_set_runstate(td, TD_RUNNING);
703
704                 ret = td_io_queue(td, io_u);
705                 switch (ret) {
706                 case FIO_Q_COMPLETED:
707                         if (io_u->error) {
708                                 ret = -io_u->error;
709                                 clear_io_u(td, io_u);
710                         } else if (io_u->resid) {
711                                 int bytes = io_u->xfer_buflen - io_u->resid;
712                                 struct fio_file *f = io_u->file;
713
714                                 /*
715                                  * zero read, fail
716                                  */
717                                 if (!bytes) {
718                                         td_verror(td, EIO, "full resid");
719                                         put_io_u(td, io_u);
720                                         break;
721                                 }
722
723                                 io_u->xfer_buflen = io_u->resid;
724                                 io_u->xfer_buf += bytes;
725                                 io_u->offset += bytes;
726
727                                 if (ddir_rw(io_u->ddir))
728                                         td->ts.short_io_u[io_u->ddir]++;
729
730                                 if (io_u->offset == f->real_file_size)
731                                         goto sync_done;
732
733                                 requeue_io_u(td, &io_u);
734                         } else {
735 sync_done:
736                                 if (__should_check_rate(td, 0) ||
737                                     __should_check_rate(td, 1))
738                                         fio_gettime(&comp_time, NULL);
739
740                                 ret = io_u_sync_complete(td, io_u, bytes_done);
741                                 if (ret < 0)
742                                         break;
743                         }
744                         break;
745                 case FIO_Q_QUEUED:
746                         /*
747                          * if the engine doesn't have a commit hook,
748                          * the io_u is really queued. if it does have such
749                          * a hook, it has to call io_u_queued() itself.
750                          */
751                         if (td->io_ops->commit == NULL)
752                                 io_u_queued(td, io_u);
753                         break;
754                 case FIO_Q_BUSY:
755                         requeue_io_u(td, &io_u);
756                         ret2 = td_io_commit(td);
757                         if (ret2 < 0)
758                                 ret = ret2;
759                         break;
760                 default:
761                         assert(ret < 0);
762                         put_io_u(td, io_u);
763                         break;
764                 }
765
766                 if (break_on_this_error(td, &ret))
767                         break;
768
769                 /*
770                  * See if we need to complete some commands. Note that we
771                  * can get BUSY even without IO queued, if the system is
772                  * resource starved.
773                  */
774                 full = queue_full(td) || (ret == FIO_Q_BUSY && td->cur_depth);
775                 if (full || !td->o.iodepth_batch_complete) {
776                         min_evts = min(td->o.iodepth_batch_complete,
777                                         td->cur_depth);
778                         if (full && !min_evts && td->o.iodepth_batch_complete != 0)
779                                 min_evts = 1;
780
781                         if (__should_check_rate(td, 0) ||
782                             __should_check_rate(td, 1))
783                                 fio_gettime(&comp_time, NULL);
784
785                         do {
786                                 ret = io_u_queued_complete(td, min_evts, bytes_done);
787                                 if (ret < 0)
788                                         break;
789
790                         } while (full && (td->cur_depth > td->o.iodepth_low));
791                 }
792
793                 if (ret < 0)
794                         break;
795                 if (!(bytes_done[0] + bytes_done[1]))
796                         continue;
797
798                 if (!in_ramp_time(td) && should_check_rate(td, bytes_done)) {
799                         if (check_min_rate(td, &comp_time, bytes_done)) {
800                                 if (exitall_on_terminate)
801                                         fio_terminate_threads(td->groupid);
802                                 td_verror(td, EIO, "check_min_rate");
803                                 break;
804                         }
805                 }
806
807                 if (td->o.thinktime) {
808                         unsigned long long b;
809
810                         b = td->io_blocks[0] + td->io_blocks[1];
811                         if (!(b % td->o.thinktime_blocks)) {
812                                 int left;
813
814                                 if (td->o.thinktime_spin)
815                                         usec_spin(td->o.thinktime_spin);
816
817                                 left = td->o.thinktime - td->o.thinktime_spin;
818                                 if (left)
819                                         usec_sleep(td, left);
820                         }
821                 }
822         }
823
824         if (td->trim_entries)
825                 printf("trim entries %ld\n", td->trim_entries);
826
827         if (td->o.fill_device && td->error == ENOSPC) {
828                 td->error = 0;
829                 td->terminate = 1;
830         }
831         if (!td->error) {
832                 struct fio_file *f;
833
834                 i = td->cur_depth;
835                 if (i) {
836                         ret = io_u_queued_complete(td, i, NULL);
837                         if (td->o.fill_device && td->error == ENOSPC)
838                                 td->error = 0;
839                 }
840
841                 if (should_fsync(td) && td->o.end_fsync) {
842                         td_set_runstate(td, TD_FSYNCING);
843
844                         for_each_file(td, f, i) {
845                                 if (!fio_file_open(f))
846                                         continue;
847                                 fio_io_sync(td, f);
848                         }
849                 }
850         } else
851                 cleanup_pending_aio(td);
852
853         /*
854          * stop job if we failed doing any IO
855          */
856         if ((td->this_io_bytes[0] + td->this_io_bytes[1]) == 0)
857                 td->done = 1;
858 }
859
860 static void cleanup_io_u(struct thread_data *td)
861 {
862         struct flist_head *entry, *n;
863         struct io_u *io_u;
864
865         flist_for_each_safe(entry, n, &td->io_u_freelist) {
866                 io_u = flist_entry(entry, struct io_u, list);
867
868                 flist_del(&io_u->list);
869                 fio_memfree(io_u, sizeof(*io_u));
870         }
871
872         free_io_mem(td);
873 }
874
875 static int init_io_u(struct thread_data *td)
876 {
877         struct io_u *io_u;
878         unsigned int max_bs;
879         int cl_align, i, max_units;
880         char *p;
881
882         max_units = td->o.iodepth;
883         max_bs = max(td->o.max_bs[DDIR_READ], td->o.max_bs[DDIR_WRITE]);
884         td->orig_buffer_size = (unsigned long long) max_bs
885                                         * (unsigned long long) max_units;
886
887         if (td->o.mem_type == MEM_SHMHUGE || td->o.mem_type == MEM_MMAPHUGE) {
888                 unsigned long bs;
889
890                 bs = td->orig_buffer_size + td->o.hugepage_size - 1;
891                 td->orig_buffer_size = bs & ~(td->o.hugepage_size - 1);
892         }
893
894         if (td->orig_buffer_size != (size_t) td->orig_buffer_size) {
895                 log_err("fio: IO memory too large. Reduce max_bs or iodepth\n");
896                 return 1;
897         }
898
899         if (allocate_io_mem(td))
900                 return 1;
901
902         if (td->o.odirect || td->o.mem_align ||
903             (td->io_ops->flags & FIO_RAWIO))
904                 p = PAGE_ALIGN(td->orig_buffer) + td->o.mem_align;
905         else
906                 p = td->orig_buffer;
907
908         cl_align = os_cache_line_size();
909
910         for (i = 0; i < max_units; i++) {
911                 void *ptr;
912
913                 if (td->terminate)
914                         return 1;
915
916                 ptr = fio_memalign(cl_align, sizeof(*io_u));
917                 if (!ptr) {
918                         log_err("fio: unable to allocate aligned memory\n");
919                         break;
920                 }
921
922                 io_u = ptr;
923                 memset(io_u, 0, sizeof(*io_u));
924                 INIT_FLIST_HEAD(&io_u->list);
925                 dprint(FD_MEM, "io_u alloc %p, index %u\n", io_u, i);
926
927                 if (!(td->io_ops->flags & FIO_NOIO)) {
928                         io_u->buf = p + max_bs * i;
929                         dprint(FD_MEM, "io_u %p, mem %p\n", io_u, io_u->buf);
930
931                         if (td_write(td))
932                                 io_u_fill_buffer(td, io_u, max_bs);
933                         if (td_write(td) && td->o.verify_pattern_bytes) {
934                                 /*
935                                  * Fill the buffer with the pattern if we are
936                                  * going to be doing writes.
937                                  */
938                                 fill_pattern(td, io_u->buf, max_bs, io_u, 0, 0);
939                         }
940                 }
941
942                 io_u->index = i;
943                 io_u->flags = IO_U_F_FREE;
944                 flist_add(&io_u->list, &td->io_u_freelist);
945         }
946
947         return 0;
948 }
949
950 static int switch_ioscheduler(struct thread_data *td)
951 {
952         char tmp[256], tmp2[128];
953         FILE *f;
954         int ret;
955
956         if (td->io_ops->flags & FIO_DISKLESSIO)
957                 return 0;
958
959         sprintf(tmp, "%s/queue/scheduler", td->sysfs_root);
960
961         f = fopen(tmp, "r+");
962         if (!f) {
963                 if (errno == ENOENT) {
964                         log_err("fio: os or kernel doesn't support IO scheduler"
965                                 " switching\n");
966                         return 0;
967                 }
968                 td_verror(td, errno, "fopen iosched");
969                 return 1;
970         }
971
972         /*
973          * Set io scheduler.
974          */
975         ret = fwrite(td->o.ioscheduler, strlen(td->o.ioscheduler), 1, f);
976         if (ferror(f) || ret != 1) {
977                 td_verror(td, errno, "fwrite");
978                 fclose(f);
979                 return 1;
980         }
981
982         rewind(f);
983
984         /*
985          * Read back and check that the selected scheduler is now the default.
986          */
987         ret = fread(tmp, 1, sizeof(tmp), f);
988         if (ferror(f) || ret < 0) {
989                 td_verror(td, errno, "fread");
990                 fclose(f);
991                 return 1;
992         }
993
994         sprintf(tmp2, "[%s]", td->o.ioscheduler);
995         if (!strstr(tmp, tmp2)) {
996                 log_err("fio: io scheduler %s not found\n", td->o.ioscheduler);
997                 td_verror(td, EINVAL, "iosched_switch");
998                 fclose(f);
999                 return 1;
1000         }
1001
1002         fclose(f);
1003         return 0;
1004 }
1005
1006 static int keep_running(struct thread_data *td)
1007 {
1008         unsigned long long io_done;
1009
1010         if (td->done)
1011                 return 0;
1012         if (td->o.time_based)
1013                 return 1;
1014         if (td->o.loops) {
1015                 td->o.loops--;
1016                 return 1;
1017         }
1018
1019         io_done = td->io_bytes[DDIR_READ] + td->io_bytes[DDIR_WRITE]
1020                         + td->io_skip_bytes;
1021         if (io_done < td->o.size)
1022                 return 1;
1023
1024         return 0;
1025 }
1026
1027 static void reset_io_counters(struct thread_data *td)
1028 {
1029         td->stat_io_bytes[0] = td->stat_io_bytes[1] = 0;
1030         td->this_io_bytes[0] = td->this_io_bytes[1] = 0;
1031         td->stat_io_blocks[0] = td->stat_io_blocks[1] = 0;
1032         td->this_io_blocks[0] = td->this_io_blocks[1] = 0;
1033         td->zone_bytes = 0;
1034         td->rate_bytes[0] = td->rate_bytes[1] = 0;
1035         td->rate_blocks[0] = td->rate_blocks[1] = 0;
1036
1037         td->last_was_sync = 0;
1038
1039         /*
1040          * reset file done count if we are to start over
1041          */
1042         if (td->o.time_based || td->o.loops)
1043                 td->nr_done_files = 0;
1044 }
1045
1046 void reset_all_stats(struct thread_data *td)
1047 {
1048         struct timeval tv;
1049         int i;
1050
1051         reset_io_counters(td);
1052
1053         for (i = 0; i < 2; i++) {
1054                 td->io_bytes[i] = 0;
1055                 td->io_blocks[i] = 0;
1056                 td->io_issues[i] = 0;
1057                 td->ts.total_io_u[i] = 0;
1058         }
1059
1060         fio_gettime(&tv, NULL);
1061         td->ts.runtime[0] = 0;
1062         td->ts.runtime[1] = 0;
1063         memcpy(&td->epoch, &tv, sizeof(tv));
1064         memcpy(&td->start, &tv, sizeof(tv));
1065 }
1066
1067 static void clear_io_state(struct thread_data *td)
1068 {
1069         struct fio_file *f;
1070         unsigned int i;
1071
1072         reset_io_counters(td);
1073
1074         close_files(td);
1075         for_each_file(td, f, i)
1076                 fio_file_clear_done(f);
1077
1078         /*
1079          * Set the same seed to get repeatable runs
1080          */
1081         td_fill_rand_seeds(td);
1082 }
1083
1084 static int exec_string(const char *string)
1085 {
1086         int ret, newlen = strlen(string) + 1 + 8;
1087         char *str;
1088
1089         str = malloc(newlen);
1090         sprintf(str, "sh -c %s", string);
1091
1092         ret = system(str);
1093         if (ret == -1)
1094                 log_err("fio: exec of cmd <%s> failed\n", str);
1095
1096         free(str);
1097         return ret;
1098 }
1099
1100 /*
1101  * Entry point for the thread based jobs. The process based jobs end up
1102  * here as well, after a little setup.
1103  */
1104 static void *thread_main(void *data)
1105 {
1106         unsigned long long elapsed;
1107         struct thread_data *td = data;
1108         pthread_condattr_t attr;
1109         int clear_state;
1110
1111         if (!td->o.use_thread) {
1112                 setsid();
1113                 td->pid = getpid();
1114         } else
1115                 td->pid = gettid();
1116
1117         dprint(FD_PROCESS, "jobs pid=%d started\n", (int) td->pid);
1118
1119         INIT_FLIST_HEAD(&td->io_u_freelist);
1120         INIT_FLIST_HEAD(&td->io_u_busylist);
1121         INIT_FLIST_HEAD(&td->io_u_requeues);
1122         INIT_FLIST_HEAD(&td->io_log_list);
1123         INIT_FLIST_HEAD(&td->io_hist_list);
1124         INIT_FLIST_HEAD(&td->verify_list);
1125         INIT_FLIST_HEAD(&td->trim_list);
1126         pthread_mutex_init(&td->io_u_lock, NULL);
1127         td->io_hist_tree = RB_ROOT;
1128
1129         pthread_condattr_init(&attr);
1130         pthread_cond_init(&td->verify_cond, &attr);
1131         pthread_cond_init(&td->free_cond, &attr);
1132
1133         td_set_runstate(td, TD_INITIALIZED);
1134         dprint(FD_MUTEX, "up startup_mutex\n");
1135         fio_mutex_up(startup_mutex);
1136         dprint(FD_MUTEX, "wait on td->mutex\n");
1137         fio_mutex_down(td->mutex);
1138         dprint(FD_MUTEX, "done waiting on td->mutex\n");
1139
1140         /*
1141          * the ->mutex mutex is now no longer used, close it to avoid
1142          * eating a file descriptor
1143          */
1144         fio_mutex_remove(td->mutex);
1145
1146         /*
1147          * A new gid requires privilege, so we need to do this before setting
1148          * the uid.
1149          */
1150         if (td->o.gid != -1U && setgid(td->o.gid)) {
1151                 td_verror(td, errno, "setgid");
1152                 goto err;
1153         }
1154         if (td->o.uid != -1U && setuid(td->o.uid)) {
1155                 td_verror(td, errno, "setuid");
1156                 goto err;
1157         }
1158
1159         /*
1160          * If we have a gettimeofday() thread, make sure we exclude that
1161          * thread from this job
1162          */
1163         if (td->o.gtod_cpu)
1164                 fio_cpu_clear(&td->o.cpumask, td->o.gtod_cpu);
1165
1166         /*
1167          * Set affinity first, in case it has an impact on the memory
1168          * allocations.
1169          */
1170         if (td->o.cpumask_set && fio_setaffinity(td->pid, td->o.cpumask) == -1) {
1171                 td_verror(td, errno, "cpu_set_affinity");
1172                 goto err;
1173         }
1174
1175         /*
1176          * May alter parameters that init_io_u() will use, so we need to
1177          * do this first.
1178          */
1179         if (init_iolog(td))
1180                 goto err;
1181
1182         if (init_io_u(td))
1183                 goto err;
1184
1185         if (td->o.verify_async && verify_async_init(td))
1186                 goto err;
1187
1188         if (td->ioprio_set) {
1189                 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, td->ioprio) == -1) {
1190                         td_verror(td, errno, "ioprio_set");
1191                         goto err;
1192                 }
1193         }
1194
1195         if (td->o.cgroup_weight && cgroup_setup(td, cgroup_list, &cgroup_mnt))
1196                 goto err;
1197
1198         if (nice(td->o.nice) == -1) {
1199                 td_verror(td, errno, "nice");
1200                 goto err;
1201         }
1202
1203         if (td->o.ioscheduler && switch_ioscheduler(td))
1204                 goto err;
1205
1206         if (!td->o.create_serialize && setup_files(td))
1207                 goto err;
1208
1209         if (td_io_init(td))
1210                 goto err;
1211
1212         if (init_random_map(td))
1213                 goto err;
1214
1215         if (td->o.exec_prerun) {
1216                 if (exec_string(td->o.exec_prerun))
1217                         goto err;
1218         }
1219
1220         if (td->o.pre_read) {
1221                 if (pre_read_files(td) < 0)
1222                         goto err;
1223         }
1224
1225         fio_gettime(&td->epoch, NULL);
1226         getrusage(RUSAGE_SELF, &td->ru_start);
1227
1228         clear_state = 0;
1229         while (keep_running(td)) {
1230                 fio_gettime(&td->start, NULL);
1231                 memcpy(&td->bw_sample_time, &td->start, sizeof(td->start));
1232                 memcpy(&td->iops_sample_time, &td->start, sizeof(td->start));
1233                 memcpy(&td->tv_cache, &td->start, sizeof(td->start));
1234
1235                 if (td->o.ratemin[0] || td->o.ratemin[1])
1236                         memcpy(&td->lastrate, &td->bw_sample_time,
1237                                                         sizeof(td->lastrate));
1238
1239                 if (clear_state)
1240                         clear_io_state(td);
1241
1242                 prune_io_piece_log(td);
1243
1244                 do_io(td);
1245
1246                 clear_state = 1;
1247
1248                 if (td_read(td) && td->io_bytes[DDIR_READ]) {
1249                         elapsed = utime_since_now(&td->start);
1250                         td->ts.runtime[DDIR_READ] += elapsed;
1251                 }
1252                 if (td_write(td) && td->io_bytes[DDIR_WRITE]) {
1253                         elapsed = utime_since_now(&td->start);
1254                         td->ts.runtime[DDIR_WRITE] += elapsed;
1255                 }
1256
1257                 if (td->error || td->terminate)
1258                         break;
1259
1260                 if (!td->o.do_verify ||
1261                     td->o.verify == VERIFY_NONE ||
1262                     (td->io_ops->flags & FIO_UNIDIR))
1263                         continue;
1264
1265                 clear_io_state(td);
1266
1267                 fio_gettime(&td->start, NULL);
1268
1269                 do_verify(td);
1270
1271                 td->ts.runtime[DDIR_READ] += utime_since_now(&td->start);
1272
1273                 if (td->error || td->terminate)
1274                         break;
1275         }
1276
1277         update_rusage_stat(td);
1278         td->ts.runtime[0] = (td->ts.runtime[0] + 999) / 1000;
1279         td->ts.runtime[1] = (td->ts.runtime[1] + 999) / 1000;
1280         td->ts.total_run_time = mtime_since_now(&td->epoch);
1281         td->ts.io_bytes[0] = td->io_bytes[0];
1282         td->ts.io_bytes[1] = td->io_bytes[1];
1283
1284         fio_mutex_down(writeout_mutex);
1285         if (td->bw_log) {
1286                 if (td->o.bw_log_file) {
1287                         finish_log_named(td, td->bw_log,
1288                                                 td->o.bw_log_file, "bw");
1289                 } else
1290                         finish_log(td, td->bw_log, "bw");
1291         }
1292         if (td->lat_log) {
1293                 if (td->o.lat_log_file) {
1294                         finish_log_named(td, td->lat_log,
1295                                                 td->o.lat_log_file, "lat");
1296                 } else
1297                         finish_log(td, td->lat_log, "lat");
1298         }
1299         if (td->slat_log) {
1300                 if (td->o.lat_log_file) {
1301                         finish_log_named(td, td->slat_log,
1302                                                 td->o.lat_log_file, "slat");
1303                 } else
1304                         finish_log(td, td->slat_log, "slat");
1305         }
1306         if (td->clat_log) {
1307                 if (td->o.lat_log_file) {
1308                         finish_log_named(td, td->clat_log,
1309                                                 td->o.lat_log_file, "clat");
1310                 } else
1311                         finish_log(td, td->clat_log, "clat");
1312         }
1313         if (td->iops_log) {
1314                 if (td->o.iops_log_file) {
1315                         finish_log_named(td, td->iops_log,
1316                                                 td->o.iops_log_file, "iops");
1317                 } else
1318                         finish_log(td, td->iops_log, "iops");
1319         }
1320
1321         fio_mutex_up(writeout_mutex);
1322         if (td->o.exec_postrun)
1323                 exec_string(td->o.exec_postrun);
1324
1325         if (exitall_on_terminate)
1326                 fio_terminate_threads(td->groupid);
1327
1328 err:
1329         if (td->error)
1330                 log_info("fio: pid=%d, err=%d/%s\n", (int) td->pid, td->error,
1331                                                         td->verror);
1332
1333         if (td->o.verify_async)
1334                 verify_async_exit(td);
1335
1336         close_and_free_files(td);
1337         close_ioengine(td);
1338         cleanup_io_u(td);
1339         cgroup_shutdown(td, &cgroup_mnt);
1340
1341         if (td->o.cpumask_set) {
1342                 int ret = fio_cpuset_exit(&td->o.cpumask);
1343
1344                 td_verror(td, ret, "fio_cpuset_exit");
1345         }
1346
1347         /*
1348          * do this very late, it will log file closing as well
1349          */
1350         if (td->o.write_iolog_file)
1351                 write_iolog_close(td);
1352
1353         options_mem_free(td);
1354         td_set_runstate(td, TD_EXITED);
1355         return (void *) (unsigned long) td->error;
1356 }
1357
1358 /*
1359  * We cannot pass the td data into a forked process, so attach the td and
1360  * pass it to the thread worker.
1361  */
1362 static int fork_main(int shmid, int offset)
1363 {
1364         struct thread_data *td;
1365         void *data, *ret;
1366
1367 #ifndef __hpux
1368         data = shmat(shmid, NULL, 0);
1369         if (data == (void *) -1) {
1370                 int __err = errno;
1371
1372                 perror("shmat");
1373                 return __err;
1374         }
1375 #else
1376         /*
1377          * HP-UX inherits shm mappings?
1378          */
1379         data = threads;
1380 #endif
1381
1382         td = data + offset * sizeof(struct thread_data);
1383         ret = thread_main(td);
1384         shmdt(data);
1385         return (int) (unsigned long) ret;
1386 }
1387
1388 /*
1389  * Run over the job map and reap the threads that have exited, if any.
1390  */
1391 static void reap_threads(int *nr_running, int *t_rate, int *m_rate)
1392 {
1393         struct thread_data *td;
1394         int i, cputhreads, realthreads, pending, status, ret;
1395
1396         /*
1397          * reap exited threads (TD_EXITED -> TD_REAPED)
1398          */
1399         realthreads = pending = cputhreads = 0;
1400         for_each_td(td, i) {
1401                 int flags = 0;
1402
1403                 /*
1404                  * ->io_ops is NULL for a thread that has closed its
1405                  * io engine
1406                  */
1407                 if (td->io_ops && !strcmp(td->io_ops->name, "cpuio"))
1408                         cputhreads++;
1409                 else
1410                         realthreads++;
1411
1412                 if (!td->pid) {
1413                         pending++;
1414                         continue;
1415                 }
1416                 if (td->runstate == TD_REAPED)
1417                         continue;
1418                 if (td->o.use_thread) {
1419                         if (td->runstate == TD_EXITED) {
1420                                 td_set_runstate(td, TD_REAPED);
1421                                 goto reaped;
1422                         }
1423                         continue;
1424                 }
1425
1426                 flags = WNOHANG;
1427                 if (td->runstate == TD_EXITED)
1428                         flags = 0;
1429
1430                 /*
1431                  * check if someone quit or got killed in an unusual way
1432                  */
1433                 ret = waitpid(td->pid, &status, flags);
1434                 if (ret < 0) {
1435                         if (errno == ECHILD) {
1436                                 log_err("fio: pid=%d disappeared %d\n",
1437                                                 (int) td->pid, td->runstate);
1438                                 td_set_runstate(td, TD_REAPED);
1439                                 goto reaped;
1440                         }
1441                         perror("waitpid");
1442                 } else if (ret == td->pid) {
1443                         if (WIFSIGNALED(status)) {
1444                                 int sig = WTERMSIG(status);
1445
1446                                 if (sig != SIGTERM)
1447                                         log_err("fio: pid=%d, got signal=%d\n",
1448                                                         (int) td->pid, sig);
1449                                 td_set_runstate(td, TD_REAPED);
1450                                 goto reaped;
1451                         }
1452                         if (WIFEXITED(status)) {
1453                                 if (WEXITSTATUS(status) && !td->error)
1454                                         td->error = WEXITSTATUS(status);
1455
1456                                 td_set_runstate(td, TD_REAPED);
1457                                 goto reaped;
1458                         }
1459                 }
1460
1461                 /*
1462                  * thread is not dead, continue
1463                  */
1464                 pending++;
1465                 continue;
1466 reaped:
1467                 (*nr_running)--;
1468                 (*m_rate) -= (td->o.ratemin[0] + td->o.ratemin[1]);
1469                 (*t_rate) -= (td->o.rate[0] + td->o.rate[1]);
1470                 if (!td->pid)
1471                         pending--;
1472
1473                 if (td->error)
1474                         exit_value++;
1475
1476                 done_secs += mtime_since_now(&td->epoch) / 1000;
1477         }
1478
1479         if (*nr_running == cputhreads && !pending && realthreads)
1480                 fio_terminate_threads(TERMINATE_ALL);
1481 }
1482
1483 static void *gtod_thread_main(void *data)
1484 {
1485         fio_mutex_up(startup_mutex);
1486
1487         /*
1488          * As long as we have jobs around, update the clock. It would be nice
1489          * to have some way of NOT hammering that CPU with gettimeofday(),
1490          * but I'm not sure what to use outside of a simple CPU nop to relax
1491          * it - we don't want to lose precision.
1492          */
1493         while (threads) {
1494                 fio_gtod_update();
1495                 nop;
1496         }
1497
1498         return NULL;
1499 }
1500
1501 static int fio_start_gtod_thread(void)
1502 {
1503         pthread_attr_t attr;
1504         int ret;
1505
1506         pthread_attr_init(&attr);
1507         pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN);
1508         ret = pthread_create(&gtod_thread, &attr, gtod_thread_main, NULL);
1509         pthread_attr_destroy(&attr);
1510         if (ret) {
1511                 log_err("Can't create gtod thread: %s\n", strerror(ret));
1512                 return 1;
1513         }
1514
1515         ret = pthread_detach(gtod_thread);
1516         if (ret) {
1517                 log_err("Can't detatch gtod thread: %s\n", strerror(ret));
1518                 return 1;
1519         }
1520
1521         dprint(FD_MUTEX, "wait on startup_mutex\n");
1522         fio_mutex_down(startup_mutex);
1523         dprint(FD_MUTEX, "done waiting on startup_mutex\n");
1524         return 0;
1525 }
1526
1527 /*
1528  * Main function for kicking off and reaping jobs, as needed.
1529  */
1530 static void run_threads(void)
1531 {
1532         struct thread_data *td;
1533         unsigned long spent;
1534         int i, todo, nr_running, m_rate, t_rate, nr_started;
1535
1536         if (fio_pin_memory())
1537                 return;
1538
1539         if (fio_gtod_offload && fio_start_gtod_thread())
1540                 return;
1541
1542         set_sig_handlers();
1543
1544         if (!terse_output) {
1545                 log_info("Starting ");
1546                 if (nr_thread)
1547                         log_info("%d thread%s", nr_thread,
1548                                                 nr_thread > 1 ? "s" : "");
1549                 if (nr_process) {
1550                         if (nr_thread)
1551                                 printf(" and ");
1552                         log_info("%d process%s", nr_process,
1553                                                 nr_process > 1 ? "es" : "");
1554                 }
1555                 log_info("\n");
1556                 fflush(stdout);
1557         }
1558
1559         todo = thread_number;
1560         nr_running = 0;
1561         nr_started = 0;
1562         m_rate = t_rate = 0;
1563
1564         for_each_td(td, i) {
1565                 print_status_init(td->thread_number - 1);
1566
1567                 if (!td->o.create_serialize)
1568                         continue;
1569
1570                 /*
1571                  * do file setup here so it happens sequentially,
1572                  * we don't want X number of threads getting their
1573                  * client data interspersed on disk
1574                  */
1575                 if (setup_files(td)) {
1576                         exit_value++;
1577                         if (td->error)
1578                                 log_err("fio: pid=%d, err=%d/%s\n",
1579                                         (int) td->pid, td->error, td->verror);
1580                         td_set_runstate(td, TD_REAPED);
1581                         todo--;
1582                 } else {
1583                         struct fio_file *f;
1584                         unsigned int j;
1585
1586                         /*
1587                          * for sharing to work, each job must always open
1588                          * its own files. so close them, if we opened them
1589                          * for creation
1590                          */
1591                         for_each_file(td, f, j) {
1592                                 if (fio_file_open(f))
1593                                         td_io_close_file(td, f);
1594                         }
1595                 }
1596         }
1597
1598         set_genesis_time();
1599
1600         while (todo) {
1601                 struct thread_data *map[REAL_MAX_JOBS];
1602                 struct timeval this_start;
1603                 int this_jobs = 0, left;
1604
1605                 /*
1606                  * create threads (TD_NOT_CREATED -> TD_CREATED)
1607                  */
1608                 for_each_td(td, i) {
1609                         if (td->runstate != TD_NOT_CREATED)
1610                                 continue;
1611
1612                         /*
1613                          * never got a chance to start, killed by other
1614                          * thread for some reason
1615                          */
1616                         if (td->terminate) {
1617                                 todo--;
1618                                 continue;
1619                         }
1620
1621                         if (td->o.start_delay) {
1622                                 spent = mtime_since_genesis();
1623
1624                                 if (td->o.start_delay * 1000 > spent)
1625                                         continue;
1626                         }
1627
1628                         if (td->o.stonewall && (nr_started || nr_running)) {
1629                                 dprint(FD_PROCESS, "%s: stonewall wait\n",
1630                                                         td->o.name);
1631                                 break;
1632                         }
1633
1634                         init_disk_util(td);
1635
1636                         /*
1637                          * Set state to created. Thread will transition
1638                          * to TD_INITIALIZED when it's done setting up.
1639                          */
1640                         td_set_runstate(td, TD_CREATED);
1641                         map[this_jobs++] = td;
1642                         nr_started++;
1643
1644                         if (td->o.use_thread) {
1645                                 int ret;
1646
1647                                 dprint(FD_PROCESS, "will pthread_create\n");
1648                                 ret = pthread_create(&td->thread, NULL,
1649                                                         thread_main, td);
1650                                 if (ret) {
1651                                         log_err("pthread_create: %s\n",
1652                                                         strerror(ret));
1653                                         nr_started--;
1654                                         break;
1655                                 }
1656                                 ret = pthread_detach(td->thread);
1657                                 if (ret)
1658                                         log_err("pthread_detach: %s",
1659                                                         strerror(ret));
1660                         } else {
1661                                 pid_t pid;
1662                                 dprint(FD_PROCESS, "will fork\n");
1663                                 pid = fork();
1664                                 if (!pid) {
1665                                         int ret = fork_main(shm_id, i);
1666
1667                                         _exit(ret);
1668                                 } else if (i == fio_debug_jobno)
1669                                         *fio_debug_jobp = pid;
1670                         }
1671                         dprint(FD_MUTEX, "wait on startup_mutex\n");
1672                         if (fio_mutex_down_timeout(startup_mutex, 10)) {
1673                                 log_err("fio: job startup hung? exiting.\n");
1674                                 fio_terminate_threads(TERMINATE_ALL);
1675                                 fio_abort = 1;
1676                                 nr_started--;
1677                                 break;
1678                         }
1679                         dprint(FD_MUTEX, "done waiting on startup_mutex\n");
1680                 }
1681
1682                 /*
1683                  * Wait for the started threads to transition to
1684                  * TD_INITIALIZED.
1685                  */
1686                 fio_gettime(&this_start, NULL);
1687                 left = this_jobs;
1688                 while (left && !fio_abort) {
1689                         if (mtime_since_now(&this_start) > JOB_START_TIMEOUT)
1690                                 break;
1691
1692                         usleep(100000);
1693
1694                         for (i = 0; i < this_jobs; i++) {
1695                                 td = map[i];
1696                                 if (!td)
1697                                         continue;
1698                                 if (td->runstate == TD_INITIALIZED) {
1699                                         map[i] = NULL;
1700                                         left--;
1701                                 } else if (td->runstate >= TD_EXITED) {
1702                                         map[i] = NULL;
1703                                         left--;
1704                                         todo--;
1705                                         nr_running++; /* work-around... */
1706                                 }
1707                         }
1708                 }
1709
1710                 if (left) {
1711                         log_err("fio: %d jobs failed to start\n", left);
1712                         for (i = 0; i < this_jobs; i++) {
1713                                 td = map[i];
1714                                 if (!td)
1715                                         continue;
1716                                 kill(td->pid, SIGTERM);
1717                         }
1718                         break;
1719                 }
1720
1721                 /*
1722                  * start created threads (TD_INITIALIZED -> TD_RUNNING).
1723                  */
1724                 for_each_td(td, i) {
1725                         if (td->runstate != TD_INITIALIZED)
1726                                 continue;
1727
1728                         if (in_ramp_time(td))
1729                                 td_set_runstate(td, TD_RAMP);
1730                         else
1731                                 td_set_runstate(td, TD_RUNNING);
1732                         nr_running++;
1733                         nr_started--;
1734                         m_rate += td->o.ratemin[0] + td->o.ratemin[1];
1735                         t_rate += td->o.rate[0] + td->o.rate[1];
1736                         todo--;
1737                         fio_mutex_up(td->mutex);
1738                 }
1739
1740                 reap_threads(&nr_running, &t_rate, &m_rate);
1741
1742                 if (todo) {
1743                         if (is_backend)
1744                                 fio_server_idle_loop();
1745                         else
1746                                 usleep(100000);
1747                 }
1748         }
1749
1750         while (nr_running) {
1751                 reap_threads(&nr_running, &t_rate, &m_rate);
1752
1753                 if (is_backend)
1754                         fio_server_idle_loop();
1755                 else
1756                         usleep(10000);
1757         }
1758
1759         update_io_ticks();
1760         fio_unpin_memory();
1761 }
1762
1763 int exec_run(void)
1764 {
1765         if (nr_clients)
1766                 return fio_handle_clients();
1767         if (exec_profile && load_profile(exec_profile))
1768                 return 1;
1769
1770         if (!thread_number)
1771                 return 0;
1772
1773         if (write_bw_log) {
1774                 setup_log(&agg_io_log[DDIR_READ]);
1775                 setup_log(&agg_io_log[DDIR_WRITE]);
1776         }
1777
1778         startup_mutex = fio_mutex_init(0);
1779         if (startup_mutex == NULL)
1780                 return 1;
1781         writeout_mutex = fio_mutex_init(1);
1782         if (writeout_mutex == NULL)
1783                 return 1;
1784
1785         set_genesis_time();
1786         create_disk_util_thread();
1787
1788         cgroup_list = smalloc(sizeof(*cgroup_list));
1789         INIT_FLIST_HEAD(cgroup_list);
1790
1791         run_threads();
1792
1793         if (!fio_abort) {
1794                 show_run_stats();
1795                 if (write_bw_log) {
1796                         __finish_log(agg_io_log[DDIR_READ], "agg-read_bw.log");
1797                         __finish_log(agg_io_log[DDIR_WRITE],
1798                                         "agg-write_bw.log");
1799                 }
1800         }
1801
1802         cgroup_kill(cgroup_list);
1803         sfree(cgroup_list);
1804         sfree(cgroup_mnt);
1805
1806         fio_mutex_remove(startup_mutex);
1807         fio_mutex_remove(writeout_mutex);
1808         return exit_value;
1809 }
1810
1811 void reset_fio_state(void)
1812 {
1813         groupid = 0;
1814         thread_number = 0;
1815         nr_process = 0;
1816         nr_thread = 0;
1817         done_secs = 0;
1818 }
1819
1820 static int endian_check(void)
1821 {
1822         union {
1823                 uint8_t c[8];
1824                 uint64_t v;
1825         } u;
1826         int le = 0, be = 0;
1827
1828         u.v = 0x12;
1829         if (u.c[7] == 0x12)
1830                 be = 1;
1831         else if (u.c[0] == 0x12)
1832                 le = 1;
1833
1834 #if defined(FIO_LITTLE_ENDIAN)
1835         if (be)
1836                 return 1;
1837 #elif defined(FIO_BIG_ENDIAN)
1838         if (le)
1839                 return 1;
1840 #else
1841         return 1;
1842 #endif
1843
1844         if (!le && !be)
1845                 return 1;
1846
1847         return 0;
1848 }
1849
1850 int main(int argc, char *argv[], char *envp[])
1851 {
1852         long ps;
1853
1854         if (endian_check()) {
1855                 log_err("fio: endianness settings appear wrong.\n");
1856                 log_err("fio: please report this to fio@vger.kernel.org\n");
1857                 return 1;
1858         }
1859
1860         arch_init(envp);
1861
1862         sinit();
1863
1864         /*
1865          * We need locale for number printing, if it isn't set then just
1866          * go with the US format.
1867          */
1868         if (!getenv("LC_NUMERIC"))
1869                 setlocale(LC_NUMERIC, "en_US");
1870
1871         ps = sysconf(_SC_PAGESIZE);
1872         if (ps < 0) {
1873                 log_err("Failed to get page size\n");
1874                 return 1;
1875         }
1876
1877         page_size = ps;
1878         page_mask = ps - 1;
1879
1880         fio_keywords_init();
1881
1882         if (parse_options(argc, argv))
1883                 return 1;
1884
1885         return exec_run();
1886 }