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