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