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