options: make the groups/categories constant
[fio.git] / io_u.c
1 #include <unistd.h>
2 #include <fcntl.h>
3 #include <string.h>
4 #include <signal.h>
5 #include <time.h>
6 #include <assert.h>
7
8 #include "fio.h"
9 #include "hash.h"
10 #include "verify.h"
11 #include "trim.h"
12 #include "lib/rand.h"
13 #include "lib/axmap.h"
14 #include "err.h"
15 #include "lib/pow2.h"
16 #include "minmax.h"
17
18 struct io_completion_data {
19         int nr;                         /* input */
20
21         int error;                      /* output */
22         uint64_t bytes_done[DDIR_RWDIR_CNT];    /* output */
23         struct timeval time;            /* output */
24 };
25
26 /*
27  * The ->io_axmap contains a map of blocks we have or have not done io
28  * to yet. Used to make sure we cover the entire range in a fair fashion.
29  */
30 static bool random_map_free(struct fio_file *f, const uint64_t block)
31 {
32         return !axmap_isset(f->io_axmap, block);
33 }
34
35 /*
36  * Mark a given offset as used in the map.
37  */
38 static void mark_random_map(struct thread_data *td, struct io_u *io_u)
39 {
40         unsigned int min_bs = td->o.rw_min_bs;
41         struct fio_file *f = io_u->file;
42         unsigned int nr_blocks;
43         uint64_t block;
44
45         block = (io_u->offset - f->file_offset) / (uint64_t) min_bs;
46         nr_blocks = (io_u->buflen + min_bs - 1) / min_bs;
47
48         if (!(io_u->flags & IO_U_F_BUSY_OK))
49                 nr_blocks = axmap_set_nr(f->io_axmap, block, nr_blocks);
50
51         if ((nr_blocks * min_bs) < io_u->buflen)
52                 io_u->buflen = nr_blocks * min_bs;
53 }
54
55 static uint64_t last_block(struct thread_data *td, struct fio_file *f,
56                            enum fio_ddir ddir)
57 {
58         uint64_t max_blocks;
59         uint64_t max_size;
60
61         assert(ddir_rw(ddir));
62
63         /*
64          * Hmm, should we make sure that ->io_size <= ->real_file_size?
65          */
66         max_size = f->io_size;
67         if (max_size > f->real_file_size)
68                 max_size = f->real_file_size;
69
70         if (td->o.zone_range)
71                 max_size = td->o.zone_range;
72
73         if (td->o.min_bs[ddir] > td->o.ba[ddir])
74                 max_size -= td->o.min_bs[ddir] - td->o.ba[ddir];
75
76         max_blocks = max_size / (uint64_t) td->o.ba[ddir];
77         if (!max_blocks)
78                 return 0;
79
80         return max_blocks;
81 }
82
83 struct rand_off {
84         struct flist_head list;
85         uint64_t off;
86 };
87
88 static int __get_next_rand_offset(struct thread_data *td, struct fio_file *f,
89                                   enum fio_ddir ddir, uint64_t *b)
90 {
91         uint64_t r;
92
93         if (td->o.random_generator == FIO_RAND_GEN_TAUSWORTHE ||
94             td->o.random_generator == FIO_RAND_GEN_TAUSWORTHE64) {
95                 uint64_t frand_max, lastb;
96
97                 lastb = last_block(td, f, ddir);
98                 if (!lastb)
99                         return 1;
100
101                 frand_max = rand_max(&td->random_state);
102                 r = __rand(&td->random_state);
103
104                 dprint(FD_RANDOM, "off rand %llu\n", (unsigned long long) r);
105
106                 *b = lastb * (r / ((uint64_t) frand_max + 1.0));
107         } else {
108                 uint64_t off = 0;
109
110                 assert(fio_file_lfsr(f));
111
112                 if (lfsr_next(&f->lfsr, &off))
113                         return 1;
114
115                 *b = off;
116         }
117
118         /*
119          * if we are not maintaining a random map, we are done.
120          */
121         if (!file_randommap(td, f))
122                 goto ret;
123
124         /*
125          * calculate map offset and check if it's free
126          */
127         if (random_map_free(f, *b))
128                 goto ret;
129
130         dprint(FD_RANDOM, "get_next_rand_offset: offset %llu busy\n",
131                                                 (unsigned long long) *b);
132
133         *b = axmap_next_free(f->io_axmap, *b);
134         if (*b == (uint64_t) -1ULL)
135                 return 1;
136 ret:
137         return 0;
138 }
139
140 static int __get_next_rand_offset_zipf(struct thread_data *td,
141                                        struct fio_file *f, enum fio_ddir ddir,
142                                        uint64_t *b)
143 {
144         *b = zipf_next(&f->zipf);
145         return 0;
146 }
147
148 static int __get_next_rand_offset_pareto(struct thread_data *td,
149                                          struct fio_file *f, enum fio_ddir ddir,
150                                          uint64_t *b)
151 {
152         *b = pareto_next(&f->zipf);
153         return 0;
154 }
155
156 static int __get_next_rand_offset_gauss(struct thread_data *td,
157                                         struct fio_file *f, enum fio_ddir ddir,
158                                         uint64_t *b)
159 {
160         *b = gauss_next(&f->gauss);
161         return 0;
162 }
163
164
165 static int flist_cmp(void *data, struct flist_head *a, struct flist_head *b)
166 {
167         struct rand_off *r1 = flist_entry(a, struct rand_off, list);
168         struct rand_off *r2 = flist_entry(b, struct rand_off, list);
169
170         return r1->off - r2->off;
171 }
172
173 static int get_off_from_method(struct thread_data *td, struct fio_file *f,
174                                enum fio_ddir ddir, uint64_t *b)
175 {
176         if (td->o.random_distribution == FIO_RAND_DIST_RANDOM)
177                 return __get_next_rand_offset(td, f, ddir, b);
178         else if (td->o.random_distribution == FIO_RAND_DIST_ZIPF)
179                 return __get_next_rand_offset_zipf(td, f, ddir, b);
180         else if (td->o.random_distribution == FIO_RAND_DIST_PARETO)
181                 return __get_next_rand_offset_pareto(td, f, ddir, b);
182         else if (td->o.random_distribution == FIO_RAND_DIST_GAUSS)
183                 return __get_next_rand_offset_gauss(td, f, ddir, b);
184
185         log_err("fio: unknown random distribution: %d\n", td->o.random_distribution);
186         return 1;
187 }
188
189 /*
190  * Sort the reads for a verify phase in batches of verifysort_nr, if
191  * specified.
192  */
193 static inline bool should_sort_io(struct thread_data *td)
194 {
195         if (!td->o.verifysort_nr || !td->o.do_verify)
196                 return false;
197         if (!td_random(td))
198                 return false;
199         if (td->runstate != TD_VERIFYING)
200                 return false;
201         if (td->o.random_generator == FIO_RAND_GEN_TAUSWORTHE ||
202             td->o.random_generator == FIO_RAND_GEN_TAUSWORTHE64)
203                 return false;
204
205         return true;
206 }
207
208 static bool should_do_random(struct thread_data *td, enum fio_ddir ddir)
209 {
210         uint64_t frand_max;
211         unsigned int v;
212         unsigned long r;
213
214         if (td->o.perc_rand[ddir] == 100)
215                 return true;
216
217         frand_max = rand_max(&td->seq_rand_state[ddir]);
218         r = __rand(&td->seq_rand_state[ddir]);
219         v = 1 + (int) (100.0 * (r / (frand_max + 1.0)));
220
221         return v <= td->o.perc_rand[ddir];
222 }
223
224 static int get_next_rand_offset(struct thread_data *td, struct fio_file *f,
225                                 enum fio_ddir ddir, uint64_t *b)
226 {
227         struct rand_off *r;
228         int i, ret = 1;
229
230         if (!should_sort_io(td))
231                 return get_off_from_method(td, f, ddir, b);
232
233         if (!flist_empty(&td->next_rand_list)) {
234 fetch:
235                 r = flist_first_entry(&td->next_rand_list, struct rand_off, list);
236                 flist_del(&r->list);
237                 *b = r->off;
238                 free(r);
239                 return 0;
240         }
241
242         for (i = 0; i < td->o.verifysort_nr; i++) {
243                 r = malloc(sizeof(*r));
244
245                 ret = get_off_from_method(td, f, ddir, &r->off);
246                 if (ret) {
247                         free(r);
248                         break;
249                 }
250
251                 flist_add(&r->list, &td->next_rand_list);
252         }
253
254         if (ret && !i)
255                 return ret;
256
257         assert(!flist_empty(&td->next_rand_list));
258         flist_sort(NULL, &td->next_rand_list, flist_cmp);
259         goto fetch;
260 }
261
262 static int get_next_rand_block(struct thread_data *td, struct fio_file *f,
263                                enum fio_ddir ddir, uint64_t *b)
264 {
265         if (!get_next_rand_offset(td, f, ddir, b))
266                 return 0;
267
268         if (td->o.time_based) {
269                 fio_file_reset(td, f);
270                 if (!get_next_rand_offset(td, f, ddir, b))
271                         return 0;
272         }
273
274         dprint(FD_IO, "%s: rand offset failed, last=%llu, size=%llu\n",
275                         f->file_name, (unsigned long long) f->last_pos[ddir],
276                         (unsigned long long) f->real_file_size);
277         return 1;
278 }
279
280 static int get_next_seq_offset(struct thread_data *td, struct fio_file *f,
281                                enum fio_ddir ddir, uint64_t *offset)
282 {
283         struct thread_options *o = &td->o;
284
285         assert(ddir_rw(ddir));
286
287         if (f->last_pos[ddir] >= f->io_size + get_start_offset(td, f) &&
288             o->time_based)
289                 f->last_pos[ddir] = f->last_pos[ddir] - f->io_size;
290
291         if (f->last_pos[ddir] < f->real_file_size) {
292                 uint64_t pos;
293
294                 if (f->last_pos[ddir] == f->file_offset && o->ddir_seq_add < 0)
295                         f->last_pos[ddir] = f->real_file_size;
296
297                 pos = f->last_pos[ddir] - f->file_offset;
298                 if (pos && o->ddir_seq_add) {
299                         pos += o->ddir_seq_add;
300
301                         /*
302                          * If we reach beyond the end of the file
303                          * with holed IO, wrap around to the
304                          * beginning again.
305                          */
306                         if (pos >= f->real_file_size)
307                                 pos = f->file_offset;
308                 }
309
310                 *offset = pos;
311                 return 0;
312         }
313
314         return 1;
315 }
316
317 static int get_next_block(struct thread_data *td, struct io_u *io_u,
318                           enum fio_ddir ddir, int rw_seq,
319                           unsigned int *is_random)
320 {
321         struct fio_file *f = io_u->file;
322         uint64_t b, offset;
323         int ret;
324
325         assert(ddir_rw(ddir));
326
327         b = offset = -1ULL;
328
329         if (rw_seq) {
330                 if (td_random(td)) {
331                         if (should_do_random(td, ddir)) {
332                                 ret = get_next_rand_block(td, f, ddir, &b);
333                                 *is_random = 1;
334                         } else {
335                                 *is_random = 0;
336                                 io_u_set(io_u, IO_U_F_BUSY_OK);
337                                 ret = get_next_seq_offset(td, f, ddir, &offset);
338                                 if (ret)
339                                         ret = get_next_rand_block(td, f, ddir, &b);
340                         }
341                 } else {
342                         *is_random = 0;
343                         ret = get_next_seq_offset(td, f, ddir, &offset);
344                 }
345         } else {
346                 io_u_set(io_u, IO_U_F_BUSY_OK);
347                 *is_random = 0;
348
349                 if (td->o.rw_seq == RW_SEQ_SEQ) {
350                         ret = get_next_seq_offset(td, f, ddir, &offset);
351                         if (ret) {
352                                 ret = get_next_rand_block(td, f, ddir, &b);
353                                 *is_random = 0;
354                         }
355                 } else if (td->o.rw_seq == RW_SEQ_IDENT) {
356                         if (f->last_start[ddir] != -1ULL)
357                                 offset = f->last_start[ddir] - f->file_offset;
358                         else
359                                 offset = 0;
360                         ret = 0;
361                 } else {
362                         log_err("fio: unknown rw_seq=%d\n", td->o.rw_seq);
363                         ret = 1;
364                 }
365         }
366
367         if (!ret) {
368                 if (offset != -1ULL)
369                         io_u->offset = offset;
370                 else if (b != -1ULL)
371                         io_u->offset = b * td->o.ba[ddir];
372                 else {
373                         log_err("fio: bug in offset generation: offset=%llu, b=%llu\n", (unsigned long long) offset, (unsigned long long) b);
374                         ret = 1;
375                 }
376         }
377
378         return ret;
379 }
380
381 /*
382  * For random io, generate a random new block and see if it's used. Repeat
383  * until we find a free one. For sequential io, just return the end of
384  * the last io issued.
385  */
386 static int __get_next_offset(struct thread_data *td, struct io_u *io_u,
387                              unsigned int *is_random)
388 {
389         struct fio_file *f = io_u->file;
390         enum fio_ddir ddir = io_u->ddir;
391         int rw_seq_hit = 0;
392
393         assert(ddir_rw(ddir));
394
395         if (td->o.ddir_seq_nr && !--td->ddir_seq_nr) {
396                 rw_seq_hit = 1;
397                 td->ddir_seq_nr = td->o.ddir_seq_nr;
398         }
399
400         if (get_next_block(td, io_u, ddir, rw_seq_hit, is_random))
401                 return 1;
402
403         if (io_u->offset >= f->io_size) {
404                 dprint(FD_IO, "get_next_offset: offset %llu >= io_size %llu\n",
405                                         (unsigned long long) io_u->offset,
406                                         (unsigned long long) f->io_size);
407                 return 1;
408         }
409
410         io_u->offset += f->file_offset;
411         if (io_u->offset >= f->real_file_size) {
412                 dprint(FD_IO, "get_next_offset: offset %llu >= size %llu\n",
413                                         (unsigned long long) io_u->offset,
414                                         (unsigned long long) f->real_file_size);
415                 return 1;
416         }
417
418         return 0;
419 }
420
421 static int get_next_offset(struct thread_data *td, struct io_u *io_u,
422                            unsigned int *is_random)
423 {
424         if (td->flags & TD_F_PROFILE_OPS) {
425                 struct prof_io_ops *ops = &td->prof_io_ops;
426
427                 if (ops->fill_io_u_off)
428                         return ops->fill_io_u_off(td, io_u, is_random);
429         }
430
431         return __get_next_offset(td, io_u, is_random);
432 }
433
434 static inline bool io_u_fits(struct thread_data *td, struct io_u *io_u,
435                              unsigned int buflen)
436 {
437         struct fio_file *f = io_u->file;
438
439         return io_u->offset + buflen <= f->io_size + get_start_offset(td, f);
440 }
441
442 static unsigned int __get_next_buflen(struct thread_data *td, struct io_u *io_u,
443                                       unsigned int is_random)
444 {
445         int ddir = io_u->ddir;
446         unsigned int buflen = 0;
447         unsigned int minbs, maxbs;
448         uint64_t frand_max;
449         unsigned long r;
450
451         assert(ddir_rw(ddir));
452
453         if (td->o.bs_is_seq_rand)
454                 ddir = is_random ? DDIR_WRITE: DDIR_READ;
455
456         minbs = td->o.min_bs[ddir];
457         maxbs = td->o.max_bs[ddir];
458
459         if (minbs == maxbs)
460                 return minbs;
461
462         /*
463          * If we can't satisfy the min block size from here, then fail
464          */
465         if (!io_u_fits(td, io_u, minbs))
466                 return 0;
467
468         frand_max = rand_max(&td->bsrange_state);
469         do {
470                 r = __rand(&td->bsrange_state);
471
472                 if (!td->o.bssplit_nr[ddir]) {
473                         buflen = 1 + (unsigned int) ((double) maxbs *
474                                         (r / (frand_max + 1.0)));
475                         if (buflen < minbs)
476                                 buflen = minbs;
477                 } else {
478                         long perc = 0;
479                         unsigned int i;
480
481                         for (i = 0; i < td->o.bssplit_nr[ddir]; i++) {
482                                 struct bssplit *bsp = &td->o.bssplit[ddir][i];
483
484                                 buflen = bsp->bs;
485                                 perc += bsp->perc;
486                                 if ((r <= ((frand_max / 100L) * perc)) &&
487                                     io_u_fits(td, io_u, buflen))
488                                         break;
489                         }
490                 }
491
492                 if (td->o.verify != VERIFY_NONE)
493                         buflen = (buflen + td->o.verify_interval - 1) &
494                                 ~(td->o.verify_interval - 1);
495
496                 if (!td->o.bs_unaligned && is_power_of_2(minbs))
497                         buflen &= ~(minbs - 1);
498
499         } while (!io_u_fits(td, io_u, buflen));
500
501         return buflen;
502 }
503
504 static unsigned int get_next_buflen(struct thread_data *td, struct io_u *io_u,
505                                     unsigned int is_random)
506 {
507         if (td->flags & TD_F_PROFILE_OPS) {
508                 struct prof_io_ops *ops = &td->prof_io_ops;
509
510                 if (ops->fill_io_u_size)
511                         return ops->fill_io_u_size(td, io_u, is_random);
512         }
513
514         return __get_next_buflen(td, io_u, is_random);
515 }
516
517 static void set_rwmix_bytes(struct thread_data *td)
518 {
519         unsigned int diff;
520
521         /*
522          * we do time or byte based switch. this is needed because
523          * buffered writes may issue a lot quicker than they complete,
524          * whereas reads do not.
525          */
526         diff = td->o.rwmix[td->rwmix_ddir ^ 1];
527         td->rwmix_issues = (td->io_issues[td->rwmix_ddir] * diff) / 100;
528 }
529
530 static inline enum fio_ddir get_rand_ddir(struct thread_data *td)
531 {
532         uint64_t frand_max = rand_max(&td->rwmix_state);
533         unsigned int v;
534         unsigned long r;
535
536         r = __rand(&td->rwmix_state);
537         v = 1 + (int) (100.0 * (r / (frand_max + 1.0)));
538
539         if (v <= td->o.rwmix[DDIR_READ])
540                 return DDIR_READ;
541
542         return DDIR_WRITE;
543 }
544
545 int io_u_quiesce(struct thread_data *td)
546 {
547         int completed = 0;
548
549         /*
550          * We are going to sleep, ensure that we flush anything pending as
551          * not to skew our latency numbers.
552          *
553          * Changed to only monitor 'in flight' requests here instead of the
554          * td->cur_depth, b/c td->cur_depth does not accurately represent
555          * io's that have been actually submitted to an async engine,
556          * and cur_depth is meaningless for sync engines.
557          */
558         if (td->io_u_queued || td->cur_depth) {
559                 int fio_unused ret;
560
561                 ret = td_io_commit(td);
562         }
563
564         while (td->io_u_in_flight) {
565                 int fio_unused ret;
566
567                 ret = io_u_queued_complete(td, 1);
568                 if (ret > 0)
569                         completed += ret;
570         }
571
572         return completed;
573 }
574
575 static enum fio_ddir rate_ddir(struct thread_data *td, enum fio_ddir ddir)
576 {
577         enum fio_ddir odir = ddir ^ 1;
578         long usec, now;
579
580         assert(ddir_rw(ddir));
581         now = utime_since_now(&td->start);
582
583         /*
584          * if rate_next_io_time is in the past, need to catch up to rate
585          */
586         if (td->rate_next_io_time[ddir] <= now)
587                 return ddir;
588
589         /*
590          * We are ahead of rate in this direction. See if we
591          * should switch.
592          */
593         if (td_rw(td) && td->o.rwmix[odir]) {
594                 /*
595                  * Other direction is behind rate, switch
596                  */
597                 if (td->rate_next_io_time[odir] <= now)
598                         return odir;
599
600                 /*
601                  * Both directions are ahead of rate. sleep the min
602                  * switch if necissary
603                  */
604                 if (td->rate_next_io_time[ddir] <=
605                         td->rate_next_io_time[odir]) {
606                         usec = td->rate_next_io_time[ddir] - now;
607                 } else {
608                         usec = td->rate_next_io_time[odir] - now;
609                         ddir = odir;
610                 }
611         } else
612                 usec = td->rate_next_io_time[ddir] - now;
613
614         if (td->o.io_submit_mode == IO_MODE_INLINE)
615                 io_u_quiesce(td);
616
617         usec = usec_sleep(td, usec);
618
619         return ddir;
620 }
621
622 /*
623  * Return the data direction for the next io_u. If the job is a
624  * mixed read/write workload, check the rwmix cycle and switch if
625  * necessary.
626  */
627 static enum fio_ddir get_rw_ddir(struct thread_data *td)
628 {
629         enum fio_ddir ddir;
630
631         /*
632          * see if it's time to fsync
633          */
634         if (td->o.fsync_blocks &&
635            !(td->io_issues[DDIR_WRITE] % td->o.fsync_blocks) &&
636              td->io_issues[DDIR_WRITE] && should_fsync(td))
637                 return DDIR_SYNC;
638
639         /*
640          * see if it's time to fdatasync
641          */
642         if (td->o.fdatasync_blocks &&
643            !(td->io_issues[DDIR_WRITE] % td->o.fdatasync_blocks) &&
644              td->io_issues[DDIR_WRITE] && should_fsync(td))
645                 return DDIR_DATASYNC;
646
647         /*
648          * see if it's time to sync_file_range
649          */
650         if (td->sync_file_range_nr &&
651            !(td->io_issues[DDIR_WRITE] % td->sync_file_range_nr) &&
652              td->io_issues[DDIR_WRITE] && should_fsync(td))
653                 return DDIR_SYNC_FILE_RANGE;
654
655         if (td_rw(td)) {
656                 /*
657                  * Check if it's time to seed a new data direction.
658                  */
659                 if (td->io_issues[td->rwmix_ddir] >= td->rwmix_issues) {
660                         /*
661                          * Put a top limit on how many bytes we do for
662                          * one data direction, to avoid overflowing the
663                          * ranges too much
664                          */
665                         ddir = get_rand_ddir(td);
666
667                         if (ddir != td->rwmix_ddir)
668                                 set_rwmix_bytes(td);
669
670                         td->rwmix_ddir = ddir;
671                 }
672                 ddir = td->rwmix_ddir;
673         } else if (td_read(td))
674                 ddir = DDIR_READ;
675         else if (td_write(td))
676                 ddir = DDIR_WRITE;
677         else
678                 ddir = DDIR_TRIM;
679
680         td->rwmix_ddir = rate_ddir(td, ddir);
681         return td->rwmix_ddir;
682 }
683
684 static void set_rw_ddir(struct thread_data *td, struct io_u *io_u)
685 {
686         enum fio_ddir ddir = get_rw_ddir(td);
687
688         if (td_trimwrite(td)) {
689                 struct fio_file *f = io_u->file;
690                 if (f->last_pos[DDIR_WRITE] == f->last_pos[DDIR_TRIM])
691                         ddir = DDIR_TRIM;
692                 else
693                         ddir = DDIR_WRITE;
694         }
695
696         io_u->ddir = io_u->acct_ddir = ddir;
697
698         if (io_u->ddir == DDIR_WRITE && (td->io_ops->flags & FIO_BARRIER) &&
699             td->o.barrier_blocks &&
700            !(td->io_issues[DDIR_WRITE] % td->o.barrier_blocks) &&
701              td->io_issues[DDIR_WRITE])
702                 io_u_set(io_u, IO_U_F_BARRIER);
703 }
704
705 void put_file_log(struct thread_data *td, struct fio_file *f)
706 {
707         unsigned int ret = put_file(td, f);
708
709         if (ret)
710                 td_verror(td, ret, "file close");
711 }
712
713 void put_io_u(struct thread_data *td, struct io_u *io_u)
714 {
715         if (td->parent)
716                 td = td->parent;
717
718         td_io_u_lock(td);
719
720         if (io_u->file && !(io_u->flags & IO_U_F_NO_FILE_PUT))
721                 put_file_log(td, io_u->file);
722
723         io_u->file = NULL;
724         io_u_set(io_u, IO_U_F_FREE);
725
726         if (io_u->flags & IO_U_F_IN_CUR_DEPTH) {
727                 td->cur_depth--;
728                 assert(!(td->flags & TD_F_CHILD));
729         }
730         io_u_qpush(&td->io_u_freelist, io_u);
731         td_io_u_unlock(td);
732         td_io_u_free_notify(td);
733 }
734
735 void clear_io_u(struct thread_data *td, struct io_u *io_u)
736 {
737         io_u_clear(io_u, IO_U_F_FLIGHT);
738         put_io_u(td, io_u);
739 }
740
741 void requeue_io_u(struct thread_data *td, struct io_u **io_u)
742 {
743         struct io_u *__io_u = *io_u;
744         enum fio_ddir ddir = acct_ddir(__io_u);
745
746         dprint(FD_IO, "requeue %p\n", __io_u);
747
748         if (td->parent)
749                 td = td->parent;
750
751         td_io_u_lock(td);
752
753         io_u_set(__io_u, IO_U_F_FREE);
754         if ((__io_u->flags & IO_U_F_FLIGHT) && ddir_rw(ddir))
755                 td->io_issues[ddir]--;
756
757         io_u_clear(__io_u, IO_U_F_FLIGHT);
758         if (__io_u->flags & IO_U_F_IN_CUR_DEPTH) {
759                 td->cur_depth--;
760                 assert(!(td->flags & TD_F_CHILD));
761         }
762
763         io_u_rpush(&td->io_u_requeues, __io_u);
764         td_io_u_unlock(td);
765         td_io_u_free_notify(td);
766         *io_u = NULL;
767 }
768
769 static int fill_io_u(struct thread_data *td, struct io_u *io_u)
770 {
771         unsigned int is_random;
772
773         if (td->io_ops->flags & FIO_NOIO)
774                 goto out;
775
776         set_rw_ddir(td, io_u);
777
778         /*
779          * fsync() or fdatasync() or trim etc, we are done
780          */
781         if (!ddir_rw(io_u->ddir))
782                 goto out;
783
784         /*
785          * See if it's time to switch to a new zone
786          */
787         if (td->zone_bytes >= td->o.zone_size && td->o.zone_skip) {
788                 struct fio_file *f = io_u->file;
789
790                 td->zone_bytes = 0;
791                 f->file_offset += td->o.zone_range + td->o.zone_skip;
792
793                 /*
794                  * Wrap from the beginning, if we exceed the file size
795                  */
796                 if (f->file_offset >= f->real_file_size)
797                         f->file_offset = f->real_file_size - f->file_offset;
798                 f->last_pos[io_u->ddir] = f->file_offset;
799                 td->io_skip_bytes += td->o.zone_skip;
800         }
801
802         /*
803          * No log, let the seq/rand engine retrieve the next buflen and
804          * position.
805          */
806         if (get_next_offset(td, io_u, &is_random)) {
807                 dprint(FD_IO, "io_u %p, failed getting offset\n", io_u);
808                 return 1;
809         }
810
811         io_u->buflen = get_next_buflen(td, io_u, is_random);
812         if (!io_u->buflen) {
813                 dprint(FD_IO, "io_u %p, failed getting buflen\n", io_u);
814                 return 1;
815         }
816
817         if (io_u->offset + io_u->buflen > io_u->file->real_file_size) {
818                 dprint(FD_IO, "io_u %p, offset too large\n", io_u);
819                 dprint(FD_IO, "  off=%llu/%lu > %llu\n",
820                         (unsigned long long) io_u->offset, io_u->buflen,
821                         (unsigned long long) io_u->file->real_file_size);
822                 return 1;
823         }
824
825         /*
826          * mark entry before potentially trimming io_u
827          */
828         if (td_random(td) && file_randommap(td, io_u->file))
829                 mark_random_map(td, io_u);
830
831 out:
832         dprint_io_u(io_u, "fill_io_u");
833         td->zone_bytes += io_u->buflen;
834         return 0;
835 }
836
837 static void __io_u_mark_map(unsigned int *map, unsigned int nr)
838 {
839         int idx = 0;
840
841         switch (nr) {
842         default:
843                 idx = 6;
844                 break;
845         case 33 ... 64:
846                 idx = 5;
847                 break;
848         case 17 ... 32:
849                 idx = 4;
850                 break;
851         case 9 ... 16:
852                 idx = 3;
853                 break;
854         case 5 ... 8:
855                 idx = 2;
856                 break;
857         case 1 ... 4:
858                 idx = 1;
859         case 0:
860                 break;
861         }
862
863         map[idx]++;
864 }
865
866 void io_u_mark_submit(struct thread_data *td, unsigned int nr)
867 {
868         __io_u_mark_map(td->ts.io_u_submit, nr);
869         td->ts.total_submit++;
870 }
871
872 void io_u_mark_complete(struct thread_data *td, unsigned int nr)
873 {
874         __io_u_mark_map(td->ts.io_u_complete, nr);
875         td->ts.total_complete++;
876 }
877
878 void io_u_mark_depth(struct thread_data *td, unsigned int nr)
879 {
880         int idx = 0;
881
882         switch (td->cur_depth) {
883         default:
884                 idx = 6;
885                 break;
886         case 32 ... 63:
887                 idx = 5;
888                 break;
889         case 16 ... 31:
890                 idx = 4;
891                 break;
892         case 8 ... 15:
893                 idx = 3;
894                 break;
895         case 4 ... 7:
896                 idx = 2;
897                 break;
898         case 2 ... 3:
899                 idx = 1;
900         case 1:
901                 break;
902         }
903
904         td->ts.io_u_map[idx] += nr;
905 }
906
907 static void io_u_mark_lat_usec(struct thread_data *td, unsigned long usec)
908 {
909         int idx = 0;
910
911         assert(usec < 1000);
912
913         switch (usec) {
914         case 750 ... 999:
915                 idx = 9;
916                 break;
917         case 500 ... 749:
918                 idx = 8;
919                 break;
920         case 250 ... 499:
921                 idx = 7;
922                 break;
923         case 100 ... 249:
924                 idx = 6;
925                 break;
926         case 50 ... 99:
927                 idx = 5;
928                 break;
929         case 20 ... 49:
930                 idx = 4;
931                 break;
932         case 10 ... 19:
933                 idx = 3;
934                 break;
935         case 4 ... 9:
936                 idx = 2;
937                 break;
938         case 2 ... 3:
939                 idx = 1;
940         case 0 ... 1:
941                 break;
942         }
943
944         assert(idx < FIO_IO_U_LAT_U_NR);
945         td->ts.io_u_lat_u[idx]++;
946 }
947
948 static void io_u_mark_lat_msec(struct thread_data *td, unsigned long msec)
949 {
950         int idx = 0;
951
952         switch (msec) {
953         default:
954                 idx = 11;
955                 break;
956         case 1000 ... 1999:
957                 idx = 10;
958                 break;
959         case 750 ... 999:
960                 idx = 9;
961                 break;
962         case 500 ... 749:
963                 idx = 8;
964                 break;
965         case 250 ... 499:
966                 idx = 7;
967                 break;
968         case 100 ... 249:
969                 idx = 6;
970                 break;
971         case 50 ... 99:
972                 idx = 5;
973                 break;
974         case 20 ... 49:
975                 idx = 4;
976                 break;
977         case 10 ... 19:
978                 idx = 3;
979                 break;
980         case 4 ... 9:
981                 idx = 2;
982                 break;
983         case 2 ... 3:
984                 idx = 1;
985         case 0 ... 1:
986                 break;
987         }
988
989         assert(idx < FIO_IO_U_LAT_M_NR);
990         td->ts.io_u_lat_m[idx]++;
991 }
992
993 static void io_u_mark_latency(struct thread_data *td, unsigned long usec)
994 {
995         if (usec < 1000)
996                 io_u_mark_lat_usec(td, usec);
997         else
998                 io_u_mark_lat_msec(td, usec / 1000);
999 }
1000
1001 /*
1002  * Get next file to service by choosing one at random
1003  */
1004 static struct fio_file *get_next_file_rand(struct thread_data *td,
1005                                            enum fio_file_flags goodf,
1006                                            enum fio_file_flags badf)
1007 {
1008         uint64_t frand_max = rand_max(&td->next_file_state);
1009         struct fio_file *f;
1010         int fno;
1011
1012         do {
1013                 int opened = 0;
1014                 unsigned long r;
1015
1016                 r = __rand(&td->next_file_state);
1017                 fno = (unsigned int) ((double) td->o.nr_files
1018                                 * (r / (frand_max + 1.0)));
1019
1020                 f = td->files[fno];
1021                 if (fio_file_done(f))
1022                         continue;
1023
1024                 if (!fio_file_open(f)) {
1025                         int err;
1026
1027                         if (td->nr_open_files >= td->o.open_files)
1028                                 return ERR_PTR(-EBUSY);
1029
1030                         err = td_io_open_file(td, f);
1031                         if (err)
1032                                 continue;
1033                         opened = 1;
1034                 }
1035
1036                 if ((!goodf || (f->flags & goodf)) && !(f->flags & badf)) {
1037                         dprint(FD_FILE, "get_next_file_rand: %p\n", f);
1038                         return f;
1039                 }
1040                 if (opened)
1041                         td_io_close_file(td, f);
1042         } while (1);
1043 }
1044
1045 /*
1046  * Get next file to service by doing round robin between all available ones
1047  */
1048 static struct fio_file *get_next_file_rr(struct thread_data *td, int goodf,
1049                                          int badf)
1050 {
1051         unsigned int old_next_file = td->next_file;
1052         struct fio_file *f;
1053
1054         do {
1055                 int opened = 0;
1056
1057                 f = td->files[td->next_file];
1058
1059                 td->next_file++;
1060                 if (td->next_file >= td->o.nr_files)
1061                         td->next_file = 0;
1062
1063                 dprint(FD_FILE, "trying file %s %x\n", f->file_name, f->flags);
1064                 if (fio_file_done(f)) {
1065                         f = NULL;
1066                         continue;
1067                 }
1068
1069                 if (!fio_file_open(f)) {
1070                         int err;
1071
1072                         if (td->nr_open_files >= td->o.open_files)
1073                                 return ERR_PTR(-EBUSY);
1074
1075                         err = td_io_open_file(td, f);
1076                         if (err) {
1077                                 dprint(FD_FILE, "error %d on open of %s\n",
1078                                         err, f->file_name);
1079                                 f = NULL;
1080                                 continue;
1081                         }
1082                         opened = 1;
1083                 }
1084
1085                 dprint(FD_FILE, "goodf=%x, badf=%x, ff=%x\n", goodf, badf,
1086                                                                 f->flags);
1087                 if ((!goodf || (f->flags & goodf)) && !(f->flags & badf))
1088                         break;
1089
1090                 if (opened)
1091                         td_io_close_file(td, f);
1092
1093                 f = NULL;
1094         } while (td->next_file != old_next_file);
1095
1096         dprint(FD_FILE, "get_next_file_rr: %p\n", f);
1097         return f;
1098 }
1099
1100 static struct fio_file *__get_next_file(struct thread_data *td)
1101 {
1102         struct fio_file *f;
1103
1104         assert(td->o.nr_files <= td->files_index);
1105
1106         if (td->nr_done_files >= td->o.nr_files) {
1107                 dprint(FD_FILE, "get_next_file: nr_open=%d, nr_done=%d,"
1108                                 " nr_files=%d\n", td->nr_open_files,
1109                                                   td->nr_done_files,
1110                                                   td->o.nr_files);
1111                 return NULL;
1112         }
1113
1114         f = td->file_service_file;
1115         if (f && fio_file_open(f) && !fio_file_closing(f)) {
1116                 if (td->o.file_service_type == FIO_FSERVICE_SEQ)
1117                         goto out;
1118                 if (td->file_service_left--)
1119                         goto out;
1120         }
1121
1122         if (td->o.file_service_type == FIO_FSERVICE_RR ||
1123             td->o.file_service_type == FIO_FSERVICE_SEQ)
1124                 f = get_next_file_rr(td, FIO_FILE_open, FIO_FILE_closing);
1125         else
1126                 f = get_next_file_rand(td, FIO_FILE_open, FIO_FILE_closing);
1127
1128         if (IS_ERR(f))
1129                 return f;
1130
1131         td->file_service_file = f;
1132         td->file_service_left = td->file_service_nr - 1;
1133 out:
1134         if (f)
1135                 dprint(FD_FILE, "get_next_file: %p [%s]\n", f, f->file_name);
1136         else
1137                 dprint(FD_FILE, "get_next_file: NULL\n");
1138         return f;
1139 }
1140
1141 static struct fio_file *get_next_file(struct thread_data *td)
1142 {
1143         if (td->flags & TD_F_PROFILE_OPS) {
1144                 struct prof_io_ops *ops = &td->prof_io_ops;
1145
1146                 if (ops->get_next_file)
1147                         return ops->get_next_file(td);
1148         }
1149
1150         return __get_next_file(td);
1151 }
1152
1153 static long set_io_u_file(struct thread_data *td, struct io_u *io_u)
1154 {
1155         struct fio_file *f;
1156
1157         do {
1158                 f = get_next_file(td);
1159                 if (IS_ERR_OR_NULL(f))
1160                         return PTR_ERR(f);
1161
1162                 io_u->file = f;
1163                 get_file(f);
1164
1165                 if (!fill_io_u(td, io_u))
1166                         break;
1167
1168                 put_file_log(td, f);
1169                 td_io_close_file(td, f);
1170                 io_u->file = NULL;
1171                 fio_file_set_done(f);
1172                 td->nr_done_files++;
1173                 dprint(FD_FILE, "%s: is done (%d of %d)\n", f->file_name,
1174                                         td->nr_done_files, td->o.nr_files);
1175         } while (1);
1176
1177         return 0;
1178 }
1179
1180 static void lat_fatal(struct thread_data *td, struct io_completion_data *icd,
1181                       unsigned long tusec, unsigned long max_usec)
1182 {
1183         if (!td->error)
1184                 log_err("fio: latency of %lu usec exceeds specified max (%lu usec)\n", tusec, max_usec);
1185         td_verror(td, ETIMEDOUT, "max latency exceeded");
1186         icd->error = ETIMEDOUT;
1187 }
1188
1189 static void lat_new_cycle(struct thread_data *td)
1190 {
1191         fio_gettime(&td->latency_ts, NULL);
1192         td->latency_ios = ddir_rw_sum(td->io_blocks);
1193         td->latency_failed = 0;
1194 }
1195
1196 /*
1197  * We had an IO outside the latency target. Reduce the queue depth. If we
1198  * are at QD=1, then it's time to give up.
1199  */
1200 static bool __lat_target_failed(struct thread_data *td)
1201 {
1202         if (td->latency_qd == 1)
1203                 return true;
1204
1205         td->latency_qd_high = td->latency_qd;
1206
1207         if (td->latency_qd == td->latency_qd_low)
1208                 td->latency_qd_low--;
1209
1210         td->latency_qd = (td->latency_qd + td->latency_qd_low) / 2;
1211
1212         dprint(FD_RATE, "Ramped down: %d %d %d\n", td->latency_qd_low, td->latency_qd, td->latency_qd_high);
1213
1214         /*
1215          * When we ramp QD down, quiesce existing IO to prevent
1216          * a storm of ramp downs due to pending higher depth.
1217          */
1218         io_u_quiesce(td);
1219         lat_new_cycle(td);
1220         return false;
1221 }
1222
1223 static bool lat_target_failed(struct thread_data *td)
1224 {
1225         if (td->o.latency_percentile.u.f == 100.0)
1226                 return __lat_target_failed(td);
1227
1228         td->latency_failed++;
1229         return false;
1230 }
1231
1232 void lat_target_init(struct thread_data *td)
1233 {
1234         td->latency_end_run = 0;
1235
1236         if (td->o.latency_target) {
1237                 dprint(FD_RATE, "Latency target=%llu\n", td->o.latency_target);
1238                 fio_gettime(&td->latency_ts, NULL);
1239                 td->latency_qd = 1;
1240                 td->latency_qd_high = td->o.iodepth;
1241                 td->latency_qd_low = 1;
1242                 td->latency_ios = ddir_rw_sum(td->io_blocks);
1243         } else
1244                 td->latency_qd = td->o.iodepth;
1245 }
1246
1247 void lat_target_reset(struct thread_data *td)
1248 {
1249         if (!td->latency_end_run)
1250                 lat_target_init(td);
1251 }
1252
1253 static void lat_target_success(struct thread_data *td)
1254 {
1255         const unsigned int qd = td->latency_qd;
1256         struct thread_options *o = &td->o;
1257
1258         td->latency_qd_low = td->latency_qd;
1259
1260         /*
1261          * If we haven't failed yet, we double up to a failing value instead
1262          * of bisecting from highest possible queue depth. If we have set
1263          * a limit other than td->o.iodepth, bisect between that.
1264          */
1265         if (td->latency_qd_high != o->iodepth)
1266                 td->latency_qd = (td->latency_qd + td->latency_qd_high) / 2;
1267         else
1268                 td->latency_qd *= 2;
1269
1270         if (td->latency_qd > o->iodepth)
1271                 td->latency_qd = o->iodepth;
1272
1273         dprint(FD_RATE, "Ramped up: %d %d %d\n", td->latency_qd_low, td->latency_qd, td->latency_qd_high);
1274
1275         /*
1276          * Same as last one, we are done. Let it run a latency cycle, so
1277          * we get only the results from the targeted depth.
1278          */
1279         if (td->latency_qd == qd) {
1280                 if (td->latency_end_run) {
1281                         dprint(FD_RATE, "We are done\n");
1282                         td->done = 1;
1283                 } else {
1284                         dprint(FD_RATE, "Quiesce and final run\n");
1285                         io_u_quiesce(td);
1286                         td->latency_end_run = 1;
1287                         reset_all_stats(td);
1288                         reset_io_stats(td);
1289                 }
1290         }
1291
1292         lat_new_cycle(td);
1293 }
1294
1295 /*
1296  * Check if we can bump the queue depth
1297  */
1298 void lat_target_check(struct thread_data *td)
1299 {
1300         uint64_t usec_window;
1301         uint64_t ios;
1302         double success_ios;
1303
1304         usec_window = utime_since_now(&td->latency_ts);
1305         if (usec_window < td->o.latency_window)
1306                 return;
1307
1308         ios = ddir_rw_sum(td->io_blocks) - td->latency_ios;
1309         success_ios = (double) (ios - td->latency_failed) / (double) ios;
1310         success_ios *= 100.0;
1311
1312         dprint(FD_RATE, "Success rate: %.2f%% (target %.2f%%)\n", success_ios, td->o.latency_percentile.u.f);
1313
1314         if (success_ios >= td->o.latency_percentile.u.f)
1315                 lat_target_success(td);
1316         else
1317                 __lat_target_failed(td);
1318 }
1319
1320 /*
1321  * If latency target is enabled, we might be ramping up or down and not
1322  * using the full queue depth available.
1323  */
1324 bool queue_full(const struct thread_data *td)
1325 {
1326         const int qempty = io_u_qempty(&td->io_u_freelist);
1327
1328         if (qempty)
1329                 return true;
1330         if (!td->o.latency_target)
1331                 return false;
1332
1333         return td->cur_depth >= td->latency_qd;
1334 }
1335
1336 struct io_u *__get_io_u(struct thread_data *td)
1337 {
1338         struct io_u *io_u = NULL;
1339
1340         if (td->stop_io)
1341                 return NULL;
1342
1343         td_io_u_lock(td);
1344
1345 again:
1346         if (!io_u_rempty(&td->io_u_requeues))
1347                 io_u = io_u_rpop(&td->io_u_requeues);
1348         else if (!queue_full(td)) {
1349                 io_u = io_u_qpop(&td->io_u_freelist);
1350
1351                 io_u->file = NULL;
1352                 io_u->buflen = 0;
1353                 io_u->resid = 0;
1354                 io_u->end_io = NULL;
1355         }
1356
1357         if (io_u) {
1358                 assert(io_u->flags & IO_U_F_FREE);
1359                 io_u_clear(io_u, IO_U_F_FREE | IO_U_F_NO_FILE_PUT |
1360                                  IO_U_F_TRIMMED | IO_U_F_BARRIER |
1361                                  IO_U_F_VER_LIST);
1362
1363                 io_u->error = 0;
1364                 io_u->acct_ddir = -1;
1365                 td->cur_depth++;
1366                 assert(!(td->flags & TD_F_CHILD));
1367                 io_u_set(io_u, IO_U_F_IN_CUR_DEPTH);
1368                 io_u->ipo = NULL;
1369         } else if (td_async_processing(td)) {
1370                 /*
1371                  * We ran out, wait for async verify threads to finish and
1372                  * return one
1373                  */
1374                 assert(!(td->flags & TD_F_CHILD));
1375                 assert(!pthread_cond_wait(&td->free_cond, &td->io_u_lock));
1376                 goto again;
1377         }
1378
1379         td_io_u_unlock(td);
1380         return io_u;
1381 }
1382
1383 static bool check_get_trim(struct thread_data *td, struct io_u *io_u)
1384 {
1385         if (!(td->flags & TD_F_TRIM_BACKLOG))
1386                 return false;
1387
1388         if (td->trim_entries) {
1389                 int get_trim = 0;
1390
1391                 if (td->trim_batch) {
1392                         td->trim_batch--;
1393                         get_trim = 1;
1394                 } else if (!(td->io_hist_len % td->o.trim_backlog) &&
1395                          td->last_ddir != DDIR_READ) {
1396                         td->trim_batch = td->o.trim_batch;
1397                         if (!td->trim_batch)
1398                                 td->trim_batch = td->o.trim_backlog;
1399                         get_trim = 1;
1400                 }
1401
1402                 if (get_trim && !get_next_trim(td, io_u))
1403                         return true;
1404         }
1405
1406         return false;
1407 }
1408
1409 static bool check_get_verify(struct thread_data *td, struct io_u *io_u)
1410 {
1411         if (!(td->flags & TD_F_VER_BACKLOG))
1412                 return false;
1413
1414         if (td->io_hist_len) {
1415                 int get_verify = 0;
1416
1417                 if (td->verify_batch)
1418                         get_verify = 1;
1419                 else if (!(td->io_hist_len % td->o.verify_backlog) &&
1420                          td->last_ddir != DDIR_READ) {
1421                         td->verify_batch = td->o.verify_batch;
1422                         if (!td->verify_batch)
1423                                 td->verify_batch = td->o.verify_backlog;
1424                         get_verify = 1;
1425                 }
1426
1427                 if (get_verify && !get_next_verify(td, io_u)) {
1428                         td->verify_batch--;
1429                         return true;
1430                 }
1431         }
1432
1433         return false;
1434 }
1435
1436 /*
1437  * Fill offset and start time into the buffer content, to prevent too
1438  * easy compressible data for simple de-dupe attempts. Do this for every
1439  * 512b block in the range, since that should be the smallest block size
1440  * we can expect from a device.
1441  */
1442 static void small_content_scramble(struct io_u *io_u)
1443 {
1444         unsigned int i, nr_blocks = io_u->buflen / 512;
1445         uint64_t boffset;
1446         unsigned int offset;
1447         void *p, *end;
1448
1449         if (!nr_blocks)
1450                 return;
1451
1452         p = io_u->xfer_buf;
1453         boffset = io_u->offset;
1454         io_u->buf_filled_len = 0;
1455
1456         for (i = 0; i < nr_blocks; i++) {
1457                 /*
1458                  * Fill the byte offset into a "random" start offset of
1459                  * the buffer, given by the product of the usec time
1460                  * and the actual offset.
1461                  */
1462                 offset = (io_u->start_time.tv_usec ^ boffset) & 511;
1463                 offset &= ~(sizeof(uint64_t) - 1);
1464                 if (offset >= 512 - sizeof(uint64_t))
1465                         offset -= sizeof(uint64_t);
1466                 memcpy(p + offset, &boffset, sizeof(boffset));
1467
1468                 end = p + 512 - sizeof(io_u->start_time);
1469                 memcpy(end, &io_u->start_time, sizeof(io_u->start_time));
1470                 p += 512;
1471                 boffset += 512;
1472         }
1473 }
1474
1475 /*
1476  * Return an io_u to be processed. Gets a buflen and offset, sets direction,
1477  * etc. The returned io_u is fully ready to be prepped and submitted.
1478  */
1479 struct io_u *get_io_u(struct thread_data *td)
1480 {
1481         struct fio_file *f;
1482         struct io_u *io_u;
1483         int do_scramble = 0;
1484         long ret = 0;
1485
1486         io_u = __get_io_u(td);
1487         if (!io_u) {
1488                 dprint(FD_IO, "__get_io_u failed\n");
1489                 return NULL;
1490         }
1491
1492         if (check_get_verify(td, io_u))
1493                 goto out;
1494         if (check_get_trim(td, io_u))
1495                 goto out;
1496
1497         /*
1498          * from a requeue, io_u already setup
1499          */
1500         if (io_u->file)
1501                 goto out;
1502
1503         /*
1504          * If using an iolog, grab next piece if any available.
1505          */
1506         if (td->flags & TD_F_READ_IOLOG) {
1507                 if (read_iolog_get(td, io_u))
1508                         goto err_put;
1509         } else if (set_io_u_file(td, io_u)) {
1510                 ret = -EBUSY;
1511                 dprint(FD_IO, "io_u %p, setting file failed\n", io_u);
1512                 goto err_put;
1513         }
1514
1515         f = io_u->file;
1516         if (!f) {
1517                 dprint(FD_IO, "io_u %p, setting file failed\n", io_u);
1518                 goto err_put;
1519         }
1520
1521         assert(fio_file_open(f));
1522
1523         if (ddir_rw(io_u->ddir)) {
1524                 if (!io_u->buflen && !(td->io_ops->flags & FIO_NOIO)) {
1525                         dprint(FD_IO, "get_io_u: zero buflen on %p\n", io_u);
1526                         goto err_put;
1527                 }
1528
1529                 f->last_start[io_u->ddir] = io_u->offset;
1530                 f->last_pos[io_u->ddir] = io_u->offset + io_u->buflen;
1531
1532                 if (io_u->ddir == DDIR_WRITE) {
1533                         if (td->flags & TD_F_REFILL_BUFFERS) {
1534                                 io_u_fill_buffer(td, io_u,
1535                                         td->o.min_bs[DDIR_WRITE],
1536                                         io_u->buflen);
1537                         } else if ((td->flags & TD_F_SCRAMBLE_BUFFERS) &&
1538                                    !(td->flags & TD_F_COMPRESS))
1539                                 do_scramble = 1;
1540                         if (td->flags & TD_F_VER_NONE) {
1541                                 populate_verify_io_u(td, io_u);
1542                                 do_scramble = 0;
1543                         }
1544                 } else if (io_u->ddir == DDIR_READ) {
1545                         /*
1546                          * Reset the buf_filled parameters so next time if the
1547                          * buffer is used for writes it is refilled.
1548                          */
1549                         io_u->buf_filled_len = 0;
1550                 }
1551         }
1552
1553         /*
1554          * Set io data pointers.
1555          */
1556         io_u->xfer_buf = io_u->buf;
1557         io_u->xfer_buflen = io_u->buflen;
1558
1559 out:
1560         assert(io_u->file);
1561         if (!td_io_prep(td, io_u)) {
1562                 if (!td->o.disable_lat)
1563                         fio_gettime(&io_u->start_time, NULL);
1564                 if (do_scramble)
1565                         small_content_scramble(io_u);
1566                 return io_u;
1567         }
1568 err_put:
1569         dprint(FD_IO, "get_io_u failed\n");
1570         put_io_u(td, io_u);
1571         return ERR_PTR(ret);
1572 }
1573
1574 static void __io_u_log_error(struct thread_data *td, struct io_u *io_u)
1575 {
1576         enum error_type_bit eb = td_error_type(io_u->ddir, io_u->error);
1577
1578         if (td_non_fatal_error(td, eb, io_u->error) && !td->o.error_dump)
1579                 return;
1580
1581         log_err("fio: io_u error%s%s: %s: %s offset=%llu, buflen=%lu\n",
1582                 io_u->file ? " on file " : "",
1583                 io_u->file ? io_u->file->file_name : "",
1584                 strerror(io_u->error),
1585                 io_ddir_name(io_u->ddir),
1586                 io_u->offset, io_u->xfer_buflen);
1587
1588         if (td->io_ops->errdetails) {
1589                 char *err = td->io_ops->errdetails(io_u);
1590
1591                 log_err("fio: %s\n", err);
1592                 free(err);
1593         }
1594
1595         if (!td->error)
1596                 td_verror(td, io_u->error, "io_u error");
1597 }
1598
1599 void io_u_log_error(struct thread_data *td, struct io_u *io_u)
1600 {
1601         __io_u_log_error(td, io_u);
1602         if (td->parent)
1603                 __io_u_log_error(td, io_u);
1604 }
1605
1606 static inline bool gtod_reduce(struct thread_data *td)
1607 {
1608         return (td->o.disable_clat && td->o.disable_slat && td->o.disable_bw)
1609                         || td->o.gtod_reduce;
1610 }
1611
1612 static void account_io_completion(struct thread_data *td, struct io_u *io_u,
1613                                   struct io_completion_data *icd,
1614                                   const enum fio_ddir idx, unsigned int bytes)
1615 {
1616         const int no_reduce = !gtod_reduce(td);
1617         unsigned long lusec = 0;
1618
1619         if (td->parent)
1620                 td = td->parent;
1621
1622         if (no_reduce)
1623                 lusec = utime_since(&io_u->issue_time, &icd->time);
1624
1625         if (!td->o.disable_lat) {
1626                 unsigned long tusec;
1627
1628                 tusec = utime_since(&io_u->start_time, &icd->time);
1629                 add_lat_sample(td, idx, tusec, bytes, io_u->offset);
1630
1631                 if (td->flags & TD_F_PROFILE_OPS) {
1632                         struct prof_io_ops *ops = &td->prof_io_ops;
1633
1634                         if (ops->io_u_lat)
1635                                 icd->error = ops->io_u_lat(td, tusec);
1636                 }
1637
1638                 if (td->o.max_latency && tusec > td->o.max_latency)
1639                         lat_fatal(td, icd, tusec, td->o.max_latency);
1640                 if (td->o.latency_target && tusec > td->o.latency_target) {
1641                         if (lat_target_failed(td))
1642                                 lat_fatal(td, icd, tusec, td->o.latency_target);
1643                 }
1644         }
1645
1646         if (!td->o.disable_clat) {
1647                 add_clat_sample(td, idx, lusec, bytes, io_u->offset);
1648                 io_u_mark_latency(td, lusec);
1649         }
1650
1651         if (!td->o.disable_bw)
1652                 add_bw_sample(td, idx, bytes, &icd->time);
1653
1654         if (no_reduce)
1655                 add_iops_sample(td, idx, bytes, &icd->time);
1656
1657         if (td->ts.nr_block_infos && io_u->ddir == DDIR_TRIM) {
1658                 uint32_t *info = io_u_block_info(td, io_u);
1659                 if (BLOCK_INFO_STATE(*info) < BLOCK_STATE_TRIM_FAILURE) {
1660                         if (io_u->ddir == DDIR_TRIM) {
1661                                 *info = BLOCK_INFO(BLOCK_STATE_TRIMMED,
1662                                                 BLOCK_INFO_TRIMS(*info) + 1);
1663                         } else if (io_u->ddir == DDIR_WRITE) {
1664                                 *info = BLOCK_INFO_SET_STATE(BLOCK_STATE_WRITTEN,
1665                                                                 *info);
1666                         }
1667                 }
1668         }
1669 }
1670
1671 static void io_completed(struct thread_data *td, struct io_u **io_u_ptr,
1672                          struct io_completion_data *icd)
1673 {
1674         struct io_u *io_u = *io_u_ptr;
1675         enum fio_ddir ddir = io_u->ddir;
1676         struct fio_file *f = io_u->file;
1677
1678         dprint_io_u(io_u, "io complete");
1679
1680         assert(io_u->flags & IO_U_F_FLIGHT);
1681         io_u_clear(io_u, IO_U_F_FLIGHT | IO_U_F_BUSY_OK);
1682
1683         /*
1684          * Mark IO ok to verify
1685          */
1686         if (io_u->ipo) {
1687                 /*
1688                  * Remove errored entry from the verification list
1689                  */
1690                 if (io_u->error)
1691                         unlog_io_piece(td, io_u);
1692                 else {
1693                         io_u->ipo->flags &= ~IP_F_IN_FLIGHT;
1694                         write_barrier();
1695                 }
1696         }
1697
1698         if (ddir_sync(ddir)) {
1699                 td->last_was_sync = 1;
1700                 if (f) {
1701                         f->first_write = -1ULL;
1702                         f->last_write = -1ULL;
1703                 }
1704                 return;
1705         }
1706
1707         td->last_was_sync = 0;
1708         td->last_ddir = ddir;
1709
1710         if (!io_u->error && ddir_rw(ddir)) {
1711                 unsigned int bytes = io_u->buflen - io_u->resid;
1712                 int ret;
1713
1714                 td->io_blocks[ddir]++;
1715                 td->this_io_blocks[ddir]++;
1716                 td->io_bytes[ddir] += bytes;
1717
1718                 if (!(io_u->flags & IO_U_F_VER_LIST))
1719                         td->this_io_bytes[ddir] += bytes;
1720
1721                 if (ddir == DDIR_WRITE) {
1722                         if (f) {
1723                                 if (f->first_write == -1ULL ||
1724                                     io_u->offset < f->first_write)
1725                                         f->first_write = io_u->offset;
1726                                 if (f->last_write == -1ULL ||
1727                                     ((io_u->offset + bytes) > f->last_write))
1728                                         f->last_write = io_u->offset + bytes;
1729                         }
1730                         if (td->last_write_comp) {
1731                                 int idx = td->last_write_idx++;
1732
1733                                 td->last_write_comp[idx] = io_u->offset;
1734                                 if (td->last_write_idx == td->o.iodepth)
1735                                         td->last_write_idx = 0;
1736                         }
1737                 }
1738
1739                 if (ramp_time_over(td) && (td->runstate == TD_RUNNING ||
1740                                            td->runstate == TD_VERIFYING))
1741                         account_io_completion(td, io_u, icd, ddir, bytes);
1742
1743                 icd->bytes_done[ddir] += bytes;
1744
1745                 if (io_u->end_io) {
1746                         ret = io_u->end_io(td, io_u_ptr);
1747                         io_u = *io_u_ptr;
1748                         if (ret && !icd->error)
1749                                 icd->error = ret;
1750                 }
1751         } else if (io_u->error) {
1752                 icd->error = io_u->error;
1753                 io_u_log_error(td, io_u);
1754         }
1755         if (icd->error) {
1756                 enum error_type_bit eb = td_error_type(ddir, icd->error);
1757
1758                 if (!td_non_fatal_error(td, eb, icd->error))
1759                         return;
1760
1761                 /*
1762                  * If there is a non_fatal error, then add to the error count
1763                  * and clear all the errors.
1764                  */
1765                 update_error_count(td, icd->error);
1766                 td_clear_error(td);
1767                 icd->error = 0;
1768                 if (io_u)
1769                         io_u->error = 0;
1770         }
1771 }
1772
1773 static void init_icd(struct thread_data *td, struct io_completion_data *icd,
1774                      int nr)
1775 {
1776         int ddir;
1777
1778         if (!gtod_reduce(td))
1779                 fio_gettime(&icd->time, NULL);
1780
1781         icd->nr = nr;
1782
1783         icd->error = 0;
1784         for (ddir = DDIR_READ; ddir < DDIR_RWDIR_CNT; ddir++)
1785                 icd->bytes_done[ddir] = 0;
1786 }
1787
1788 static void ios_completed(struct thread_data *td,
1789                           struct io_completion_data *icd)
1790 {
1791         struct io_u *io_u;
1792         int i;
1793
1794         for (i = 0; i < icd->nr; i++) {
1795                 io_u = td->io_ops->event(td, i);
1796
1797                 io_completed(td, &io_u, icd);
1798
1799                 if (io_u)
1800                         put_io_u(td, io_u);
1801         }
1802 }
1803
1804 /*
1805  * Complete a single io_u for the sync engines.
1806  */
1807 int io_u_sync_complete(struct thread_data *td, struct io_u *io_u)
1808 {
1809         struct io_completion_data icd;
1810         int ddir;
1811
1812         init_icd(td, &icd, 1);
1813         io_completed(td, &io_u, &icd);
1814
1815         if (io_u)
1816                 put_io_u(td, io_u);
1817
1818         if (icd.error) {
1819                 td_verror(td, icd.error, "io_u_sync_complete");
1820                 return -1;
1821         }
1822
1823         for (ddir = DDIR_READ; ddir < DDIR_RWDIR_CNT; ddir++)
1824                 td->bytes_done[ddir] += icd.bytes_done[ddir];
1825
1826         return 0;
1827 }
1828
1829 /*
1830  * Called to complete min_events number of io for the async engines.
1831  */
1832 int io_u_queued_complete(struct thread_data *td, int min_evts)
1833 {
1834         struct io_completion_data icd;
1835         struct timespec *tvp = NULL;
1836         int ret, ddir;
1837         struct timespec ts = { .tv_sec = 0, .tv_nsec = 0, };
1838
1839         dprint(FD_IO, "io_u_queued_completed: min=%d\n", min_evts);
1840
1841         if (!min_evts)
1842                 tvp = &ts;
1843         else if (min_evts > td->cur_depth)
1844                 min_evts = td->cur_depth;
1845
1846         /* No worries, td_io_getevents fixes min and max if they are
1847          * set incorrectly */
1848         ret = td_io_getevents(td, min_evts, td->o.iodepth_batch_complete_max, tvp);
1849         if (ret < 0) {
1850                 td_verror(td, -ret, "td_io_getevents");
1851                 return ret;
1852         } else if (!ret)
1853                 return ret;
1854
1855         init_icd(td, &icd, ret);
1856         ios_completed(td, &icd);
1857         if (icd.error) {
1858                 td_verror(td, icd.error, "io_u_queued_complete");
1859                 return -1;
1860         }
1861
1862         for (ddir = DDIR_READ; ddir < DDIR_RWDIR_CNT; ddir++)
1863                 td->bytes_done[ddir] += icd.bytes_done[ddir];
1864
1865         return ret;
1866 }
1867
1868 /*
1869  * Call when io_u is really queued, to update the submission latency.
1870  */
1871 void io_u_queued(struct thread_data *td, struct io_u *io_u)
1872 {
1873         if (!td->o.disable_slat) {
1874                 unsigned long slat_time;
1875
1876                 slat_time = utime_since(&io_u->start_time, &io_u->issue_time);
1877
1878                 if (td->parent)
1879                         td = td->parent;
1880
1881                 add_slat_sample(td, io_u->ddir, slat_time, io_u->xfer_buflen,
1882                                 io_u->offset);
1883         }
1884 }
1885
1886 /*
1887  * See if we should reuse the last seed, if dedupe is enabled
1888  */
1889 static struct frand_state *get_buf_state(struct thread_data *td)
1890 {
1891         uint64_t frand_max;
1892         unsigned int v;
1893         unsigned long r;
1894
1895         if (!td->o.dedupe_percentage)
1896                 return &td->buf_state;
1897         else if (td->o.dedupe_percentage == 100) {
1898                 frand_copy(&td->buf_state_prev, &td->buf_state);
1899                 return &td->buf_state;
1900         }
1901
1902         frand_max = rand_max(&td->dedupe_state);
1903         r = __rand(&td->dedupe_state);
1904         v = 1 + (int) (100.0 * (r / (frand_max + 1.0)));
1905
1906         if (v <= td->o.dedupe_percentage)
1907                 return &td->buf_state_prev;
1908
1909         return &td->buf_state;
1910 }
1911
1912 static void save_buf_state(struct thread_data *td, struct frand_state *rs)
1913 {
1914         if (td->o.dedupe_percentage == 100)
1915                 frand_copy(rs, &td->buf_state_prev);
1916         else if (rs == &td->buf_state)
1917                 frand_copy(&td->buf_state_prev, rs);
1918 }
1919
1920 void fill_io_buffer(struct thread_data *td, void *buf, unsigned int min_write,
1921                     unsigned int max_bs)
1922 {
1923         struct thread_options *o = &td->o;
1924
1925         if (o->compress_percentage || o->dedupe_percentage) {
1926                 unsigned int perc = td->o.compress_percentage;
1927                 struct frand_state *rs;
1928                 unsigned int left = max_bs;
1929                 unsigned int this_write;
1930
1931                 do {
1932                         rs = get_buf_state(td);
1933
1934                         min_write = min(min_write, left);
1935
1936                         if (perc) {
1937                                 this_write = min_not_zero(min_write,
1938                                                         td->o.compress_chunk);
1939
1940                                 fill_random_buf_percentage(rs, buf, perc,
1941                                         this_write, this_write,
1942                                         o->buffer_pattern,
1943                                         o->buffer_pattern_bytes);
1944                         } else {
1945                                 fill_random_buf(rs, buf, min_write);
1946                                 this_write = min_write;
1947                         }
1948
1949                         buf += this_write;
1950                         left -= this_write;
1951                         save_buf_state(td, rs);
1952                 } while (left);
1953         } else if (o->buffer_pattern_bytes)
1954                 fill_buffer_pattern(td, buf, max_bs);
1955         else if (o->zero_buffers)
1956                 memset(buf, 0, max_bs);
1957         else
1958                 fill_random_buf(get_buf_state(td), buf, max_bs);
1959 }
1960
1961 /*
1962  * "randomly" fill the buffer contents
1963  */
1964 void io_u_fill_buffer(struct thread_data *td, struct io_u *io_u,
1965                       unsigned int min_write, unsigned int max_bs)
1966 {
1967         io_u->buf_filled_len = 0;
1968         fill_io_buffer(td, io_u->buf, min_write, max_bs);
1969 }