ab1bf7c9a4a176f8bdfc23cd6b2245371c9a4d2c
[fio.git] / io_u.c
1 #include <unistd.h>
2 #include <string.h>
3 #include <assert.h>
4
5 #include "fio.h"
6 #include "verify.h"
7 #include "trim.h"
8 #include "lib/rand.h"
9 #include "lib/axmap.h"
10 #include "err.h"
11 #include "lib/pow2.h"
12 #include "minmax.h"
13 #include "zbd.h"
14 #include "sprandom.h"
15
16 struct io_completion_data {
17         int nr;                         /* input */
18
19         int error;                      /* output */
20         uint64_t bytes_done[DDIR_RWDIR_CNT];    /* output */
21         struct timespec time;           /* output */
22 };
23
24 /*
25  * The ->io_axmap contains a map of blocks we have or have not done io
26  * to yet. Used to make sure we cover the entire range in a fair fashion.
27  */
28 static bool random_map_free(struct fio_file *f, const uint64_t block)
29 {
30         return !axmap_isset(f->io_axmap, block);
31 }
32
33 /*
34  * Mark a given offset as used in the map.
35  */
36 static uint64_t mark_random_map(struct thread_data *td, struct io_u *io_u,
37                                 uint64_t offset, uint64_t buflen)
38 {
39         unsigned long long min_bs = td->o.min_bs[io_u->ddir];
40         struct fio_file *f = io_u->file;
41         unsigned long long nr_blocks;
42         uint64_t block;
43
44         block = (offset - f->file_offset) / (uint64_t) min_bs;
45         nr_blocks = (buflen + min_bs - 1) / min_bs;
46         assert(nr_blocks > 0);
47
48         if (!(io_u->flags & IO_U_F_BUSY_OK)) {
49                 nr_blocks = axmap_set_nr(f->io_axmap, block, nr_blocks);
50                 assert(nr_blocks > 0);
51         }
52
53         if ((nr_blocks * min_bs) < buflen)
54                 buflen = nr_blocks * min_bs;
55
56         return buflen;
57 }
58
59 static uint64_t last_block(struct thread_data *td, struct fio_file *f,
60                            enum fio_ddir ddir)
61 {
62         uint64_t max_blocks;
63         uint64_t max_size;
64
65         assert(ddir_rw(ddir));
66
67         /*
68          * Hmm, should we make sure that ->io_size <= ->real_file_size?
69          * -> not for now since there is code assuming it could go either.
70          */
71         max_size = f->io_size;
72         if (max_size > f->real_file_size)
73                 max_size = f->real_file_size;
74
75         if (td->o.zone_mode == ZONE_MODE_STRIDED && td->o.zone_range)
76                 max_size = td->o.zone_range;
77
78         if (td->o.min_bs[ddir] > td->o.ba[ddir])
79                 max_size -= td->o.min_bs[ddir] - td->o.ba[ddir];
80
81         max_blocks = max_size / (uint64_t) td->o.ba[ddir];
82         if (!max_blocks)
83                 return 0;
84
85         return max_blocks;
86 }
87
88
89 static int __get_next_rand_offset_sprandom(struct thread_data *td, struct fio_file *f,
90                                            enum fio_ddir ddir, uint64_t *b,
91                                            uint64_t lastb)
92 {
93         assert(ddir == DDIR_WRITE);
94
95         /* SP RANDOM writes all addresses once */
96         if (sprandom_get_next_offset(f->spr_info, f, b)) {
97                 dprint(FD_SPRANDOM, "sprandom is done\n");
98                 td->done = 1;
99                 return 1;
100         }
101         return 0;
102 }
103
104 static int __get_next_rand_offset(struct thread_data *td, struct fio_file *f,
105                                   enum fio_ddir ddir, uint64_t *b,
106                                   uint64_t lastb)
107 {
108         uint64_t r;
109
110         if (td->o.random_generator == FIO_RAND_GEN_TAUSWORTHE ||
111             td->o.random_generator == FIO_RAND_GEN_TAUSWORTHE64) {
112
113                 r = __rand(&td->random_state);
114
115                 dprint(FD_RANDOM, "off rand %llu\n", (unsigned long long) r);
116
117                 *b = lastb * (r / (rand_max(&td->random_state) + 1.0));
118         } else {
119                 uint64_t off = 0;
120
121                 assert(fio_file_lfsr(f));
122
123                 if (lfsr_next(&f->lfsr, &off))
124                         return 1;
125
126                 *b = off;
127         }
128
129         /*
130          * if we are not maintaining a random map, we are done.
131          */
132         if (!file_randommap(td, f))
133                 goto ret;
134
135         /*
136          * calculate map offset and check if it's free
137          */
138         if (random_map_free(f, *b))
139                 goto ret;
140
141         dprint(FD_RANDOM, "get_next_rand_offset: offset %llu busy\n",
142                                                 (unsigned long long) *b);
143
144         *b = axmap_next_free(f->io_axmap, *b);
145         if (*b == (uint64_t) -1ULL)
146                 return 1;
147 ret:
148         return 0;
149 }
150
151 static int __get_next_rand_offset_zipf(struct thread_data *td,
152                                        struct fio_file *f, enum fio_ddir ddir,
153                                        uint64_t *b)
154 {
155         *b = zipf_next(&f->zipf);
156         return 0;
157 }
158
159 static int __get_next_rand_offset_pareto(struct thread_data *td,
160                                          struct fio_file *f, enum fio_ddir ddir,
161                                          uint64_t *b)
162 {
163         *b = pareto_next(&f->zipf);
164         return 0;
165 }
166
167 static int __get_next_rand_offset_gauss(struct thread_data *td,
168                                         struct fio_file *f, enum fio_ddir ddir,
169                                         uint64_t *b)
170 {
171         *b = gauss_next(&f->gauss);
172         return 0;
173 }
174
175 static int __get_next_rand_offset_zoned_abs(struct thread_data *td,
176                                             struct fio_file *f,
177                                             enum fio_ddir ddir, uint64_t *b)
178 {
179         struct zone_split_index *zsi;
180         uint64_t lastb, send, stotal;
181         unsigned int v;
182
183         lastb = last_block(td, f, ddir);
184         if (!lastb)
185                 return 1;
186
187         if (!td->o.zone_split_nr[ddir]) {
188 bail:
189                 return __get_next_rand_offset(td, f, ddir, b, lastb);
190         }
191
192         /*
193          * Generate a value, v, between 1 and 100, both inclusive
194          */
195         v = rand_between(&td->zone_state, 1, 100);
196
197         /*
198          * Find our generated table. 'send' is the end block of this zone,
199          * 'stotal' is our start offset.
200          */
201         zsi = &td->zone_state_index[ddir][v - 1];
202         stotal = zsi->size_prev / td->o.ba[ddir];
203         send = zsi->size / td->o.ba[ddir];
204
205         /*
206          * Should never happen
207          */
208         if (send == -1U) {
209                 if (!fio_did_warn(FIO_WARN_ZONED_BUG))
210                         log_err("fio: bug in zoned generation\n");
211                 goto bail;
212         } else if (send > lastb) {
213                 /*
214                  * This happens if the user specifies ranges that exceed
215                  * the file/device size. We can't handle that gracefully,
216                  * so error and exit.
217                  */
218                 log_err("fio: zoned_abs sizes exceed file size\n");
219                 return 1;
220         }
221
222         /*
223          * Generate index from 0..send-stotal
224          */
225         if (__get_next_rand_offset(td, f, ddir, b, send - stotal) == 1)
226                 return 1;
227
228         *b += stotal;
229         return 0;
230 }
231
232 static int __get_next_rand_offset_zoned(struct thread_data *td,
233                                         struct fio_file *f, enum fio_ddir ddir,
234                                         uint64_t *b)
235 {
236         unsigned int v, send, stotal;
237         uint64_t offset, lastb;
238         struct zone_split_index *zsi;
239
240         lastb = last_block(td, f, ddir);
241         if (!lastb)
242                 return 1;
243
244         if (!td->o.zone_split_nr[ddir]) {
245 bail:
246                 return __get_next_rand_offset(td, f, ddir, b, lastb);
247         }
248
249         /*
250          * Generate a value, v, between 1 and 100, both inclusive
251          */
252         v = rand_between(&td->zone_state, 1, 100);
253
254         zsi = &td->zone_state_index[ddir][v - 1];
255         stotal = zsi->size_perc_prev;
256         send = zsi->size_perc;
257
258         /*
259          * Should never happen
260          */
261         if (send == -1U) {
262                 if (!fio_did_warn(FIO_WARN_ZONED_BUG))
263                         log_err("fio: bug in zoned generation\n");
264                 goto bail;
265         }
266
267         /*
268          * 'send' is some percentage below or equal to 100 that
269          * marks the end of the current IO range. 'stotal' marks
270          * the start, in percent.
271          */
272         if (stotal)
273                 offset = stotal * lastb / 100ULL;
274         else
275                 offset = 0;
276
277         lastb = lastb * (send - stotal) / 100ULL;
278
279         /*
280          * Generate index from 0..send-of-lastb
281          */
282         if (__get_next_rand_offset(td, f, ddir, b, lastb) == 1)
283                 return 1;
284
285         /*
286          * Add our start offset, if any
287          */
288         if (offset)
289                 *b += offset;
290
291         return 0;
292 }
293
294 static int get_next_rand_offset(struct thread_data *td, struct fio_file *f,
295                                 enum fio_ddir ddir, uint64_t *b)
296 {
297         if (td->o.sprandom && ddir == DDIR_WRITE) {
298                 return __get_next_rand_offset_sprandom(td, f, ddir, b, 0);
299         } else if (td->o.random_distribution == FIO_RAND_DIST_RANDOM) {
300                 uint64_t lastb;
301
302                 lastb = last_block(td, f, ddir);
303                 if (!lastb)
304                         return 1;
305
306                 return __get_next_rand_offset(td, f, ddir, b, lastb);
307         } else if (td->o.random_distribution == FIO_RAND_DIST_ZIPF)
308                 return __get_next_rand_offset_zipf(td, f, ddir, b);
309         else if (td->o.random_distribution == FIO_RAND_DIST_PARETO)
310                 return __get_next_rand_offset_pareto(td, f, ddir, b);
311         else if (td->o.random_distribution == FIO_RAND_DIST_GAUSS)
312                 return __get_next_rand_offset_gauss(td, f, ddir, b);
313         else if (td->o.random_distribution == FIO_RAND_DIST_ZONED)
314                 return __get_next_rand_offset_zoned(td, f, ddir, b);
315         else if (td->o.random_distribution == FIO_RAND_DIST_ZONED_ABS)
316                 return __get_next_rand_offset_zoned_abs(td, f, ddir, b);
317
318         log_err("fio: unknown random distribution: %d\n", td->o.random_distribution);
319         return 1;
320 }
321
322 static bool should_do_random(struct thread_data *td, enum fio_ddir ddir)
323 {
324         unsigned int v;
325
326         if (td->o.perc_rand[ddir] == 100)
327                 return true;
328
329         v = rand_between(&td->seq_rand_state[ddir], 1, 100);
330
331         return v <= td->o.perc_rand[ddir];
332 }
333
334 static void loop_cache_invalidate(struct thread_data *td, struct fio_file *f)
335 {
336         struct thread_options *o = &td->o;
337
338         if (o->invalidate_cache && !o->odirect) {
339                 int fio_unused ret;
340
341                 ret = file_invalidate_cache(td, f);
342         }
343 }
344
345 static int get_next_rand_block(struct thread_data *td, struct fio_file *f,
346                                enum fio_ddir ddir, uint64_t *b)
347 {
348         if (!get_next_rand_offset(td, f, ddir, b))
349                 return 0;
350
351         if (td->o.time_based ||
352             (td->o.file_service_type & __FIO_FSERVICE_NONUNIFORM)) {
353                 fio_file_reset(td, f);
354                 loop_cache_invalidate(td, f);
355                 if (!get_next_rand_offset(td, f, ddir, b))
356                         return 0;
357         }
358
359         dprint(FD_IO, "%s: rand offset failed, last=%llu, size=%llu\n",
360                         f->file_name, (unsigned long long) f->last_pos[ddir],
361                         (unsigned long long) f->real_file_size);
362         return 1;
363 }
364
365 static int get_next_seq_offset(struct thread_data *td, struct fio_file *f,
366                                enum fio_ddir ddir, uint64_t *offset)
367 {
368         struct thread_options *o = &td->o;
369
370         assert(ddir_rw(ddir));
371
372         /*
373          * If we reach the end for a time based run, reset us back to 0
374          * and invalidate the cache, if we need to.
375          */
376         if (f->last_pos[ddir] >= f->io_size + get_start_offset(td, f) &&
377             o->time_based && o->nr_files == 1) {
378                 f->last_pos[ddir] = f->file_offset;
379                 loop_cache_invalidate(td, f);
380         }
381
382         /*
383          * If we reach the end for a rw-io-size based run, reset us back to 0
384          * and invalidate the cache, if we need to.
385          */
386         if (td_rw(td) && o->io_size > o->size) {
387                 if (f->last_pos[ddir] >= f->io_size + get_start_offset(td, f)) {
388                         f->last_pos[ddir] = f->file_offset;
389                         loop_cache_invalidate(td, f);
390                 }
391         }
392
393         if (f->last_pos[ddir] < f->real_file_size) {
394                 uint64_t pos;
395
396                 /*
397                  * Only rewind if we already hit the end
398                  */
399                 if (f->last_pos[ddir] == f->file_offset &&
400                     f->file_offset && o->ddir_seq_add < 0) {
401                         if (f->real_file_size > f->io_size)
402                                 f->last_pos[ddir] = f->io_size;
403                         else
404                                 f->last_pos[ddir] = f->real_file_size;
405                 }
406
407                 pos = f->last_pos[ddir] - f->file_offset;
408                 if (pos && o->ddir_seq_add) {
409                         pos += o->ddir_seq_add;
410
411                         /*
412                          * If we reach beyond the end of the file
413                          * with holed IO, wrap around to the
414                          * beginning again. If we're doing backwards IO,
415                          * wrap to the end.
416                          */
417                         if (pos >= f->real_file_size) {
418                                 if (o->ddir_seq_add > 0)
419                                         pos = f->file_offset;
420                                 else {
421                                         if (f->real_file_size > f->io_size)
422                                                 pos = f->io_size;
423                                         else
424                                                 pos = f->real_file_size;
425
426                                         pos += o->ddir_seq_add;
427                                 }
428                         }
429                 }
430
431                 *offset = pos;
432                 return 0;
433         }
434
435         return 1;
436 }
437
438 static int get_next_block(struct thread_data *td, struct io_u *io_u,
439                           enum fio_ddir ddir, int rw_seq,
440                           bool *is_random)
441 {
442         struct fio_file *f = io_u->file;
443         uint64_t b, offset;
444         int ret;
445
446         assert(ddir_rw(ddir));
447
448         b = offset = -1ULL;
449
450         if (td_randtrimwrite(td) && ddir == DDIR_WRITE) {
451                 /* don't mark randommap for these writes */
452                 io_u_set(td, io_u, IO_U_F_BUSY_OK);
453                 offset = f->last_start[DDIR_TRIM] - f->file_offset;
454                 *is_random = true;
455                 ret = 0;
456         } else if (rw_seq) {
457                 if (td_random(td)) {
458                         if (should_do_random(td, ddir)) {
459                                 ret = get_next_rand_block(td, f, ddir, &b);
460                                 *is_random = true;
461                         } else {
462                                 *is_random = false;
463                                 io_u_set(td, io_u, IO_U_F_BUSY_OK);
464                                 ret = get_next_seq_offset(td, f, ddir, &offset);
465                                 if (ret)
466                                         ret = get_next_rand_block(td, f, ddir, &b);
467                         }
468                 } else {
469                         *is_random = false;
470                         ret = get_next_seq_offset(td, f, ddir, &offset);
471                 }
472         } else {
473                 io_u_set(td, io_u, IO_U_F_BUSY_OK);
474                 *is_random = false;
475
476                 if (td->o.rw_seq == RW_SEQ_SEQ) {
477                         ret = get_next_seq_offset(td, f, ddir, &offset);
478                         if (ret) {
479                                 ret = get_next_rand_block(td, f, ddir, &b);
480                                 *is_random = false;
481                         }
482                 } else if (td->o.rw_seq == RW_SEQ_IDENT) {
483                         if (f->last_start[ddir] != -1ULL)
484                                 offset = f->last_start[ddir] - f->file_offset;
485                         else
486                                 offset = 0;
487                         ret = 0;
488                 } else {
489                         log_err("fio: unknown rw_seq=%d\n", td->o.rw_seq);
490                         ret = 1;
491                 }
492         }
493
494         if (!ret) {
495                 if (offset != -1ULL)
496                         io_u->offset = offset;
497                 else if (b != -1ULL)
498                         io_u->offset = b * td->o.ba[ddir];
499                 else {
500                         log_err("fio: bug in offset generation: offset=%llu, b=%llu\n", (unsigned long long) offset, (unsigned long long) b);
501                         ret = 1;
502                 }
503                 io_u->verify_offset = io_u->offset;
504         }
505
506         return ret;
507 }
508
509 /*
510  * For random io, generate a random new block and see if it's used. Repeat
511  * until we find a free one. For sequential io, just return the end of
512  * the last io issued.
513  */
514 static int get_next_offset(struct thread_data *td, struct io_u *io_u,
515                            bool *is_random)
516 {
517         struct fio_file *f = io_u->file;
518         enum fio_ddir ddir = io_u->ddir;
519         int rw_seq_hit = 0;
520
521         assert(ddir_rw(ddir));
522
523         if (td->o.ddir_seq_nr && !--td->ddir_seq_nr) {
524                 rw_seq_hit = 1;
525                 td->ddir_seq_nr = td->o.ddir_seq_nr;
526         }
527
528         if (get_next_block(td, io_u, ddir, rw_seq_hit, is_random))
529                 return 1;
530
531         if (io_u->offset >= f->io_size) {
532                 dprint(FD_IO, "get_next_offset: offset %llu >= io_size %llu\n",
533                                         (unsigned long long) io_u->offset,
534                                         (unsigned long long) f->io_size);
535                 return 1;
536         }
537
538         io_u->offset += f->file_offset;
539         if (io_u->offset >= f->real_file_size) {
540                 dprint(FD_IO, "get_next_offset: offset %llu >= size %llu\n",
541                                         (unsigned long long) io_u->offset,
542                                         (unsigned long long) f->real_file_size);
543                 return 1;
544         }
545
546         /*
547          * For randtrimwrite, we decide whether to issue a trim or a write
548          * based on whether the offsets for the most recent trim and write
549          * operations match. If they don't match that means we just issued a
550          * new trim and the next operation should be a write. If they *do*
551          * match that means we just completed a trim+write pair and the next
552          * command should be a trim.
553          *
554          * This works fine for sequential workloads but for random workloads
555          * it's possible to complete a trim+write pair and then have the next
556          * randomly generated offset match the previous offset. If that happens
557          * we need to alter the offset for the last write operation in order
558          * to ensure that we issue a write operation the next time through.
559          */
560         if (td_randtrimwrite(td) && ddir == DDIR_TRIM &&
561             f->last_start[DDIR_TRIM] == io_u->offset)
562                 f->last_start[DDIR_WRITE]--;
563
564         io_u->verify_offset = io_u->offset;
565         return 0;
566 }
567
568 static inline bool io_u_fits(struct thread_data *td, struct io_u *io_u,
569                              unsigned long long buflen)
570 {
571         struct fio_file *f = io_u->file;
572
573         return io_u->offset + buflen <= f->io_size + get_start_offset(td, f);
574 }
575
576 static unsigned long long get_next_buflen(struct thread_data *td, struct io_u *io_u,
577                                     bool is_random)
578 {
579         int ddir = io_u->ddir;
580         unsigned long long buflen = 0;
581         unsigned long long minbs, maxbs;
582         uint64_t frand_max, r;
583         bool power_2;
584
585         assert(ddir_rw(ddir));
586
587         if (td_randtrimwrite(td) && ddir == DDIR_WRITE) {
588                 struct fio_file *f = io_u->file;
589
590                 return f->last_pos[DDIR_TRIM] - f->last_start[DDIR_TRIM];
591         }
592
593         if (td->o.bs_is_seq_rand)
594                 ddir = is_random ? DDIR_WRITE : DDIR_READ;
595
596         minbs = td->o.min_bs[ddir];
597         maxbs = td->o.max_bs[ddir];
598
599         if (minbs == maxbs)
600                 return minbs;
601
602         /*
603          * If we can't satisfy the min block size from here, then fail
604          */
605         if (!io_u_fits(td, io_u, minbs))
606                 return 0;
607
608         frand_max = rand_max(&td->bsrange_state[ddir]);
609         do {
610                 r = __rand(&td->bsrange_state[ddir]);
611
612                 if (!td->o.bssplit_nr[ddir]) {
613                         buflen = minbs + (unsigned long long) ((double) maxbs *
614                                         (r / (frand_max + 1.0)));
615                 } else {
616                         long long perc = 0;
617                         unsigned int i;
618
619                         for (i = 0; i < td->o.bssplit_nr[ddir]; i++) {
620                                 struct bssplit *bsp = &td->o.bssplit[ddir][i];
621
622                                 if (!bsp->perc)
623                                         continue;
624                                 buflen = bsp->bs;
625                                 perc += bsp->perc;
626                                 if ((r / perc <= frand_max / 100ULL) &&
627                                     io_u_fits(td, io_u, buflen))
628                                         break;
629                         }
630                 }
631
632                 power_2 = is_power_of_2(minbs);
633                 if (!td->o.bs_unaligned && power_2)
634                         buflen &= ~(minbs - 1);
635                 else if (!td->o.bs_unaligned && !power_2)
636                         buflen -= buflen % minbs;
637                 if (buflen > maxbs)
638                         buflen = maxbs;
639         } while (!io_u_fits(td, io_u, buflen));
640
641         return buflen;
642 }
643
644 static void set_rwmix_bytes(struct thread_data *td)
645 {
646         unsigned int diff;
647
648         /*
649          * we do time or byte based switch. this is needed because
650          * buffered writes may issue a lot quicker than they complete,
651          * whereas reads do not.
652          */
653         diff = td->o.rwmix[td->rwmix_ddir ^ 1];
654         td->rwmix_issues = (td->io_issues[td->rwmix_ddir] * diff) / 100;
655 }
656
657 static inline enum fio_ddir get_rand_ddir(struct thread_data *td)
658 {
659         unsigned int v;
660
661         v = rand_between(&td->rwmix_state, 1, 100);
662
663         if (v <= td->o.rwmix[DDIR_READ])
664                 return DDIR_READ;
665
666         return DDIR_WRITE;
667 }
668
669 int io_u_quiesce(struct thread_data *td)
670 {
671         int ret = 0, completed = 0, err = 0;
672
673         /*
674          * We are going to sleep, ensure that we flush anything pending as
675          * not to skew our latency numbers.
676          *
677          * Changed to only monitor 'in flight' requests here instead of the
678          * td->cur_depth, b/c td->cur_depth does not accurately represent
679          * io's that have been actually submitted to an async engine,
680          * and cur_depth is meaningless for sync engines.
681          */
682         if (td->io_u_queued || td->cur_depth)
683                 td_io_commit(td);
684
685         while (td->io_u_in_flight) {
686                 ret = io_u_queued_complete(td, 1);
687                 if (ret > 0)
688                         completed += ret;
689                 else if (ret < 0)
690                         err = ret;
691         }
692
693         if (td->flags & TD_F_REGROW_LOGS)
694                 regrow_logs(td);
695
696         if (completed)
697                 return completed;
698
699         return err;
700 }
701
702 static enum fio_ddir rate_ddir(struct thread_data *td, enum fio_ddir ddir)
703 {
704         enum fio_ddir odir = ddir ^ 1;
705         uint64_t usec;
706         uint64_t now;
707
708         assert(ddir_rw(ddir));
709         now = utime_since_now(&td->epoch);
710
711         /*
712          * if rate_next_io_time is in the past, need to catch up to rate
713          */
714         if (td->rate_next_io_time[ddir] <= now)
715                 return ddir;
716
717         /*
718          * We are ahead of rate in this direction. See if we
719          * should switch.
720          */
721         if (td_rw(td) && td->o.rwmix[odir]) {
722                 /*
723                  * Other direction is behind rate, switch
724                  */
725                 if (td->rate_next_io_time[odir] <= now)
726                         return odir;
727
728                 /*
729                  * Both directions are ahead of rate. sleep the min,
730                  * switch if necessary
731                  */
732                 if (td->rate_next_io_time[ddir] <=
733                     td->rate_next_io_time[odir]) {
734                         usec = td->rate_next_io_time[ddir] - now;
735                 } else {
736                         usec = td->rate_next_io_time[odir] - now;
737                         ddir = odir;
738                 }
739         } else
740                 usec = td->rate_next_io_time[ddir] - now;
741
742         if (td->o.io_submit_mode == IO_MODE_INLINE)
743                 io_u_quiesce(td);
744
745         if (td->o.timeout && ((usec + now) > td->o.timeout)) {
746                 /*
747                  * check if the usec is capable of taking negative values
748                  */
749                 if (now > td->o.timeout) {
750                         ddir = DDIR_TIMEOUT;
751                         return ddir;
752                 }
753                 usec = td->o.timeout - now;
754         }
755         usec_sleep(td, usec);
756
757         now = utime_since_now(&td->epoch);
758         if ((td->o.timeout && (now > td->o.timeout)) || td->terminate)
759                 ddir = DDIR_TIMEOUT;
760
761         return ddir;
762 }
763
764 /*
765  * Return the data direction for the next io_u. If the job is a
766  * mixed read/write workload, check the rwmix cycle and switch if
767  * necessary.
768  */
769 static enum fio_ddir get_rw_ddir(struct thread_data *td)
770 {
771         enum fio_ddir ddir;
772
773         /*
774          * See if it's time to fsync/fdatasync/sync_file_range first,
775          * and if not then move on to check regular I/Os.
776          */
777         if (should_fsync(td) && td->last_ddir_issued == DDIR_WRITE) {
778                 if (td->o.fsync_blocks && td->io_issues[DDIR_WRITE] &&
779                     !(td->io_issues[DDIR_WRITE] % td->o.fsync_blocks))
780                         return DDIR_SYNC;
781
782                 if (td->o.fdatasync_blocks && td->io_issues[DDIR_WRITE] &&
783                     !(td->io_issues[DDIR_WRITE] % td->o.fdatasync_blocks))
784                         return DDIR_DATASYNC;
785
786                 if (td->sync_file_range_nr && td->io_issues[DDIR_WRITE] &&
787                     !(td->io_issues[DDIR_WRITE] % td->sync_file_range_nr))
788                         return DDIR_SYNC_FILE_RANGE;
789         }
790
791         if (td_rw(td)) {
792                 /*
793                  * Check if it's time to seed a new data direction.
794                  */
795                 if (td->io_issues[td->rwmix_ddir] >= td->rwmix_issues) {
796                         /*
797                          * Put a top limit on how many bytes we do for
798                          * one data direction, to avoid overflowing the
799                          * ranges too much
800                          */
801                         ddir = get_rand_ddir(td);
802
803                         if (ddir != td->rwmix_ddir)
804                                 set_rwmix_bytes(td);
805
806                         td->rwmix_ddir = ddir;
807                 }
808                 ddir = td->rwmix_ddir;
809         } else if (td_read(td))
810                 ddir = DDIR_READ;
811         else if (td_write(td))
812                 ddir = DDIR_WRITE;
813         else if (td_trim(td))
814                 ddir = DDIR_TRIM;
815         else
816                 ddir = DDIR_INVAL;
817
818         if (!should_check_rate(td)) {
819                 /*
820                  * avoid time-consuming call to utime_since_now() if rate checking
821                  * isn't being used. this imrpoves IOPs 50%. See:
822                  * https://github.com/axboe/fio/issues/1501#issuecomment-1418327049
823                  */
824                 td->rwmix_ddir = ddir;
825         } else
826                 td->rwmix_ddir = rate_ddir(td, ddir);
827         return td->rwmix_ddir;
828 }
829
830 static void set_rw_ddir(struct thread_data *td, struct io_u *io_u)
831 {
832         enum fio_ddir ddir = get_rw_ddir(td);
833
834         if (td->o.zone_mode == ZONE_MODE_ZBD)
835                 ddir = zbd_adjust_ddir(td, io_u, ddir);
836
837         if (td_trimwrite(td) && !ddir_sync(ddir)) {
838                 struct fio_file *f = io_u->file;
839                 if (f->last_start[DDIR_WRITE] == f->last_start[DDIR_TRIM])
840                         ddir = DDIR_TRIM;
841                 else
842                         ddir = DDIR_WRITE;
843         }
844
845         io_u->ddir = io_u->acct_ddir = ddir;
846
847         if (io_u->ddir == DDIR_WRITE && td_ioengine_flagged(td, FIO_BARRIER) &&
848             td->o.barrier_blocks &&
849            !(td->io_issues[DDIR_WRITE] % td->o.barrier_blocks) &&
850              td->io_issues[DDIR_WRITE])
851                 io_u_set(td, io_u, IO_U_F_BARRIER);
852 }
853
854 void put_file_log(struct thread_data *td, struct fio_file *f)
855 {
856         unsigned int ret = put_file(td, f);
857
858         if (ret)
859                 td_verror(td, ret, "file close");
860 }
861
862 void put_io_u(struct thread_data *td, struct io_u *io_u)
863 {
864         const bool needs_lock = td_async_processing(td);
865
866         zbd_put_io_u(td, io_u);
867
868         if (td->parent)
869                 td = td->parent;
870
871         if (needs_lock)
872                 __td_io_u_lock(td);
873
874         if (io_u->file && !(io_u->flags & IO_U_F_NO_FILE_PUT))
875                 put_file_log(td, io_u->file);
876
877         io_u->file = NULL;
878         io_u_set(td, io_u, IO_U_F_FREE);
879
880         if (io_u->flags & IO_U_F_IN_CUR_DEPTH) {
881                 td->cur_depth--;
882                 assert(!(td->flags & TD_F_CHILD));
883         }
884         io_u_qpush(&td->io_u_freelist, io_u);
885         td_io_u_free_notify(td);
886
887         if (needs_lock)
888                 __td_io_u_unlock(td);
889 }
890
891 static inline void io_u_clear_inflight_flags(struct thread_data *td,
892                                               struct io_u *io_u)
893 {
894         io_u_clear(td, io_u, IO_U_F_FLIGHT | IO_U_F_BUSY_OK |
895                    IO_U_F_PATTERN_DONE);
896 }
897
898 void clear_io_u(struct thread_data *td, struct io_u *io_u)
899 {
900         io_u_clear_inflight_flags(td, io_u);
901         put_io_u(td, io_u);
902 }
903
904 void requeue_io_u(struct thread_data *td, struct io_u **io_u)
905 {
906         const bool needs_lock = td_async_processing(td);
907         struct io_u *__io_u = *io_u;
908         enum fio_ddir ddir = acct_ddir(__io_u);
909
910         dprint(FD_IO, "requeue %p\n", __io_u);
911
912         if (td->parent)
913                 td = td->parent;
914
915         if (needs_lock)
916                 __td_io_u_lock(td);
917
918         io_u_set(td, __io_u, IO_U_F_FREE);
919         if ((__io_u->flags & IO_U_F_FLIGHT) && ddir_rw(ddir))
920                 td->io_issues[ddir]--;
921
922         io_u_clear(td, __io_u, IO_U_F_FLIGHT);
923         if (__io_u->flags & IO_U_F_IN_CUR_DEPTH) {
924                 td->cur_depth--;
925                 assert(!(td->flags & TD_F_CHILD));
926         }
927
928         io_u_rpush(&td->io_u_requeues, __io_u);
929         td_io_u_free_notify(td);
930
931         if (needs_lock)
932                 __td_io_u_unlock(td);
933
934         *io_u = NULL;
935 }
936
937 static void setup_strided_zone_mode(struct thread_data *td, struct io_u *io_u)
938 {
939         struct fio_file *f = io_u->file;
940
941         assert(td->o.zone_mode == ZONE_MODE_STRIDED);
942         assert(td->o.zone_size);
943         assert(td->o.zone_range);
944
945         /*
946          * See if it's time to switch to a new zone
947          */
948         if (td->zone_bytes >= td->o.zone_size) {
949                 td->zone_bytes = 0;
950                 f->file_offset += td->o.zone_range + td->o.zone_skip;
951
952                 /*
953                  * Wrap from the beginning, if we exceed the file size
954                  */
955                 if (f->file_offset >= f->real_file_size)
956                         f->file_offset = get_start_offset(td, f);
957
958                 f->last_pos[io_u->ddir] = f->file_offset;
959                 td->io_skip_bytes += td->o.zone_skip;
960         }
961
962         /*
963          * If zone_size > zone_range, then maintain the same zone until
964          * zone_bytes >= zone_size.
965          */
966         if (f->last_pos[io_u->ddir] >= (f->file_offset + td->o.zone_range)) {
967                 dprint(FD_IO, "io_u maintain zone offset=%" PRIu64 "/last_pos=%" PRIu64 "\n",
968                                 f->file_offset, f->last_pos[io_u->ddir]);
969                 f->last_pos[io_u->ddir] = f->file_offset;
970         }
971
972         /*
973          * For random: if 'norandommap' is not set and zone_size > zone_range,
974          * map needs to be reset as it's done with zone_range everytime.
975          */
976         if ((td->zone_bytes % td->o.zone_range) == 0)
977                 fio_file_reset(td, f);
978 }
979
980 static int fill_multi_range_io_u(struct thread_data *td, struct io_u *io_u)
981 {
982         bool is_random;
983         uint64_t buflen, i = 0;
984         struct trim_range *range;
985         struct fio_file *f = io_u->file;
986         uint8_t *buf;
987
988         buf = io_u->buf;
989         buflen = 0;
990
991         while (i < td->o.num_range) {
992                 range = (struct trim_range *)buf;
993                 if (get_next_offset(td, io_u, &is_random)) {
994                         dprint(FD_IO, "io_u %p, failed getting offset\n",
995                                io_u);
996                         break;
997                 }
998
999                 io_u->buflen = get_next_buflen(td, io_u, is_random);
1000                 if (!io_u->buflen) {
1001                         dprint(FD_IO, "io_u %p, failed getting buflen\n", io_u);
1002                         break;
1003                 }
1004
1005                 if (io_u->offset + io_u->buflen > io_u->file->real_file_size) {
1006                         dprint(FD_IO, "io_u %p, off=0x%llx + len=0x%llx exceeds file size=0x%llx\n",
1007                                io_u,
1008                                (unsigned long long) io_u->offset, io_u->buflen,
1009                                (unsigned long long) io_u->file->real_file_size);
1010                         break;
1011                 }
1012
1013                 range->start = io_u->offset;
1014                 range->len = io_u->buflen;
1015                 buflen += io_u->buflen;
1016                 f->last_start[io_u->ddir] = io_u->offset;
1017                 f->last_pos[io_u->ddir] = io_u->offset + range->len;
1018
1019                 buf += sizeof(struct trim_range);
1020                 i++;
1021
1022                 if (td_random(td) && file_randommap(td, io_u->file))
1023                         mark_random_map(td, io_u, io_u->offset, io_u->buflen);
1024                 dprint_io_u(io_u, "fill");
1025         }
1026         if (buflen) {
1027                 /*
1028                  * Set buffer length as overall trim length for this IO, and
1029                  * tell the ioengine about the number of ranges to be trimmed.
1030                  */
1031                 io_u->buflen = buflen;
1032                 io_u->number_trim = i;
1033                 return 0;
1034         }
1035
1036         return 1;
1037 }
1038
1039 static int fill_io_u(struct thread_data *td, struct io_u *io_u)
1040 {
1041         bool is_random;
1042         uint64_t offset;
1043         enum io_u_action ret;
1044
1045         if (td_ioengine_flagged(td, FIO_NOIO))
1046                 goto out;
1047
1048         set_rw_ddir(td, io_u);
1049
1050         if (io_u->ddir == DDIR_INVAL || io_u->ddir == DDIR_TIMEOUT) {
1051                 dprint(FD_IO, "invalid direction received ddir = %d", io_u->ddir);
1052                 return 1;
1053         }
1054         /*
1055          * fsync() or fdatasync() or trim etc, we are done
1056          */
1057         if (!ddir_rw(io_u->ddir))
1058                 goto out;
1059
1060         if (td->o.zone_mode == ZONE_MODE_STRIDED)
1061                 setup_strided_zone_mode(td, io_u);
1062         else if (td->o.zone_mode == ZONE_MODE_ZBD)
1063                 setup_zbd_zone_mode(td, io_u);
1064
1065         if (multi_range_trim(td, io_u)) {
1066                 if (fill_multi_range_io_u(td, io_u))
1067                         return 1;
1068         } else {
1069                 /*
1070                  * No log, let the seq/rand engine retrieve the next buflen and
1071                  * position.
1072                  */
1073                 if (get_next_offset(td, io_u, &is_random)) {
1074                         dprint(FD_IO, "io_u %p, failed getting offset\n", io_u);
1075                         return 1;
1076                 }
1077
1078                 io_u->buflen = get_next_buflen(td, io_u, is_random);
1079                 if (!io_u->buflen) {
1080                         dprint(FD_IO, "io_u %p, failed getting buflen\n", io_u);
1081                         return 1;
1082                 }
1083         }
1084         offset = io_u->offset;
1085
1086         if (td->o.zone_mode == ZONE_MODE_ZBD) {
1087                 ret = zbd_adjust_block(td, io_u);
1088                 if (ret == io_u_eof) {
1089                         dprint(FD_IO, "zbd_adjust_block() returned io_u_eof\n");
1090                         return 1;
1091                 }
1092         }
1093
1094         if (td->o.dp_type != FIO_DP_NONE)
1095                 dp_fill_dspec_data(td, io_u);
1096
1097         if (io_u->offset + io_u->buflen > io_u->file->real_file_size) {
1098                 dprint(FD_IO, "io_u %p, off=0x%llx + len=0x%llx exceeds file size=0x%llx\n",
1099                         io_u,
1100                         (unsigned long long) io_u->offset, io_u->buflen,
1101                         (unsigned long long) io_u->file->real_file_size);
1102                 return 1;
1103         }
1104
1105         /*
1106          * mark entry before potentially trimming io_u
1107          */
1108         if (!multi_range_trim(td, io_u) && td_random(td) && file_randommap(td, io_u->file))
1109                 io_u->buflen = mark_random_map(td, io_u, offset, io_u->buflen);
1110
1111 out:
1112         if (!multi_range_trim(td, io_u))
1113                 dprint_io_u(io_u, "fill");
1114         io_u->verify_offset = io_u->offset;
1115         td->zone_bytes += io_u->buflen;
1116         return 0;
1117 }
1118
1119 static void __io_u_mark_map(uint64_t *map, unsigned int nr)
1120 {
1121         int idx = 0;
1122
1123         switch (nr) {
1124         default:
1125                 idx = 6;
1126                 break;
1127         case 33 ... 64:
1128                 idx = 5;
1129                 break;
1130         case 17 ... 32:
1131                 idx = 4;
1132                 break;
1133         case 9 ... 16:
1134                 idx = 3;
1135                 break;
1136         case 5 ... 8:
1137                 idx = 2;
1138                 break;
1139         case 1 ... 4:
1140                 idx = 1;
1141                 fio_fallthrough;
1142         case 0:
1143                 break;
1144         }
1145
1146         map[idx]++;
1147 }
1148
1149 void io_u_mark_submit(struct thread_data *td, unsigned int nr)
1150 {
1151         __io_u_mark_map(td->ts.io_u_submit, nr);
1152         td->ts.total_submit++;
1153 }
1154
1155 void io_u_mark_complete(struct thread_data *td, unsigned int nr)
1156 {
1157         __io_u_mark_map(td->ts.io_u_complete, nr);
1158         td->ts.total_complete++;
1159 }
1160
1161 void io_u_mark_depth(struct thread_data *td, unsigned int nr)
1162 {
1163         int idx = 0;
1164
1165         switch (td->cur_depth) {
1166         default:
1167                 idx = 6;
1168                 break;
1169         case 32 ... 63:
1170                 idx = 5;
1171                 break;
1172         case 16 ... 31:
1173                 idx = 4;
1174                 break;
1175         case 8 ... 15:
1176                 idx = 3;
1177                 break;
1178         case 4 ... 7:
1179                 idx = 2;
1180                 break;
1181         case 2 ... 3:
1182                 idx = 1;
1183                 fio_fallthrough;
1184         case 1:
1185                 break;
1186         }
1187
1188         td->ts.io_u_map[idx] += nr;
1189 }
1190
1191 static void io_u_mark_lat_nsec(struct thread_data *td, unsigned long long nsec)
1192 {
1193         int idx = 0;
1194
1195         assert(nsec < 1000);
1196
1197         switch (nsec) {
1198         case 750 ... 999:
1199                 idx = 9;
1200                 break;
1201         case 500 ... 749:
1202                 idx = 8;
1203                 break;
1204         case 250 ... 499:
1205                 idx = 7;
1206                 break;
1207         case 100 ... 249:
1208                 idx = 6;
1209                 break;
1210         case 50 ... 99:
1211                 idx = 5;
1212                 break;
1213         case 20 ... 49:
1214                 idx = 4;
1215                 break;
1216         case 10 ... 19:
1217                 idx = 3;
1218                 break;
1219         case 4 ... 9:
1220                 idx = 2;
1221                 break;
1222         case 2 ... 3:
1223                 idx = 1;
1224                 fio_fallthrough;
1225         case 0 ... 1:
1226                 break;
1227         }
1228
1229         assert(idx < FIO_IO_U_LAT_N_NR);
1230         td->ts.io_u_lat_n[idx]++;
1231 }
1232
1233 static void io_u_mark_lat_usec(struct thread_data *td, unsigned long long usec)
1234 {
1235         int idx = 0;
1236
1237         assert(usec < 1000 && usec >= 1);
1238
1239         switch (usec) {
1240         case 750 ... 999:
1241                 idx = 9;
1242                 break;
1243         case 500 ... 749:
1244                 idx = 8;
1245                 break;
1246         case 250 ... 499:
1247                 idx = 7;
1248                 break;
1249         case 100 ... 249:
1250                 idx = 6;
1251                 break;
1252         case 50 ... 99:
1253                 idx = 5;
1254                 break;
1255         case 20 ... 49:
1256                 idx = 4;
1257                 break;
1258         case 10 ... 19:
1259                 idx = 3;
1260                 break;
1261         case 4 ... 9:
1262                 idx = 2;
1263                 break;
1264         case 2 ... 3:
1265                 idx = 1;
1266                 fio_fallthrough;
1267         case 0 ... 1:
1268                 break;
1269         }
1270
1271         assert(idx < FIO_IO_U_LAT_U_NR);
1272         td->ts.io_u_lat_u[idx]++;
1273 }
1274
1275 static void io_u_mark_lat_msec(struct thread_data *td, unsigned long long msec)
1276 {
1277         int idx = 0;
1278
1279         assert(msec >= 1);
1280
1281         switch (msec) {
1282         default:
1283                 idx = 11;
1284                 break;
1285         case 1000 ... 1999:
1286                 idx = 10;
1287                 break;
1288         case 750 ... 999:
1289                 idx = 9;
1290                 break;
1291         case 500 ... 749:
1292                 idx = 8;
1293                 break;
1294         case 250 ... 499:
1295                 idx = 7;
1296                 break;
1297         case 100 ... 249:
1298                 idx = 6;
1299                 break;
1300         case 50 ... 99:
1301                 idx = 5;
1302                 break;
1303         case 20 ... 49:
1304                 idx = 4;
1305                 break;
1306         case 10 ... 19:
1307                 idx = 3;
1308                 break;
1309         case 4 ... 9:
1310                 idx = 2;
1311                 break;
1312         case 2 ... 3:
1313                 idx = 1;
1314                 fio_fallthrough;
1315         case 0 ... 1:
1316                 break;
1317         }
1318
1319         assert(idx < FIO_IO_U_LAT_M_NR);
1320         td->ts.io_u_lat_m[idx]++;
1321 }
1322
1323 static void io_u_mark_latency(struct thread_data *td, unsigned long long nsec)
1324 {
1325         if (nsec < 1000)
1326                 io_u_mark_lat_nsec(td, nsec);
1327         else if (nsec < 1000000)
1328                 io_u_mark_lat_usec(td, nsec / 1000);
1329         else
1330                 io_u_mark_lat_msec(td, nsec / 1000000);
1331 }
1332
1333 static unsigned int __get_next_fileno_rand(struct thread_data *td)
1334 {
1335         unsigned long fileno;
1336
1337         if (td->o.file_service_type == FIO_FSERVICE_RANDOM) {
1338                 uint64_t frand_max = rand_max(&td->next_file_state);
1339                 unsigned long r;
1340
1341                 r = __rand(&td->next_file_state);
1342                 return (unsigned int) ((double) td->o.nr_files
1343                                 * (r / (frand_max + 1.0)));
1344         }
1345
1346         if (td->o.file_service_type == FIO_FSERVICE_ZIPF)
1347                 fileno = zipf_next(&td->next_file_zipf);
1348         else if (td->o.file_service_type == FIO_FSERVICE_PARETO)
1349                 fileno = pareto_next(&td->next_file_zipf);
1350         else if (td->o.file_service_type == FIO_FSERVICE_GAUSS)
1351                 fileno = gauss_next(&td->next_file_gauss);
1352         else {
1353                 log_err("fio: bad file service type: %d\n", td->o.file_service_type);
1354                 assert(0);
1355                 return 0;
1356         }
1357
1358         return fileno >> FIO_FSERVICE_SHIFT;
1359 }
1360
1361 /*
1362  * Get next file to service by choosing one at random
1363  */
1364 static struct fio_file *get_next_file_rand(struct thread_data *td,
1365                                            enum fio_file_flags goodf,
1366                                            enum fio_file_flags badf)
1367 {
1368         struct fio_file *f;
1369         int fno;
1370
1371         do {
1372                 int opened = 0;
1373
1374                 fno = __get_next_fileno_rand(td);
1375
1376                 f = td->files[fno];
1377                 if (fio_file_done(f))
1378                         continue;
1379
1380                 if (!fio_file_open(f)) {
1381                         int err;
1382
1383                         if (td->nr_open_files >= td->o.open_files)
1384                                 return ERR_PTR(-EBUSY);
1385
1386                         err = td_io_open_file(td, f);
1387                         if (err)
1388                                 continue;
1389                         opened = 1;
1390                 }
1391
1392                 if ((!goodf || (f->flags & goodf)) && !(f->flags & badf)) {
1393                         dprint(FD_FILE, "get_next_file_rand: %p\n", f);
1394                         return f;
1395                 }
1396                 if (opened)
1397                         td_io_close_file(td, f);
1398         } while (1);
1399 }
1400
1401 /*
1402  * Get next file to service by doing round robin between all available ones
1403  */
1404 static struct fio_file *get_next_file_rr(struct thread_data *td, int goodf,
1405                                          int badf)
1406 {
1407         unsigned int old_next_file = td->next_file;
1408         struct fio_file *f;
1409
1410         do {
1411                 int opened = 0;
1412
1413                 f = td->files[td->next_file];
1414
1415                 td->next_file++;
1416                 if (td->next_file >= td->o.nr_files)
1417                         td->next_file = 0;
1418
1419                 dprint(FD_FILE, "trying file %s %x\n", f->file_name, f->flags);
1420                 if (fio_file_done(f)) {
1421                         f = NULL;
1422                         continue;
1423                 }
1424
1425                 if (!fio_file_open(f)) {
1426                         int err;
1427
1428                         if (td->nr_open_files >= td->o.open_files)
1429                                 return ERR_PTR(-EBUSY);
1430
1431                         err = td_io_open_file(td, f);
1432                         if (err) {
1433                                 dprint(FD_FILE, "error %d on open of %s\n",
1434                                         err, f->file_name);
1435                                 f = NULL;
1436                                 continue;
1437                         }
1438                         opened = 1;
1439                 }
1440
1441                 dprint(FD_FILE, "goodf=%x, badf=%x, ff=%x\n", goodf, badf,
1442                                                                 f->flags);
1443                 if ((!goodf || (f->flags & goodf)) && !(f->flags & badf))
1444                         break;
1445
1446                 if (opened)
1447                         td_io_close_file(td, f);
1448
1449                 f = NULL;
1450         } while (td->next_file != old_next_file);
1451
1452         dprint(FD_FILE, "get_next_file_rr: %p\n", f);
1453         return f;
1454 }
1455
1456 static struct fio_file *__get_next_file(struct thread_data *td)
1457 {
1458         struct fio_file *f;
1459
1460         assert(td->o.nr_files <= td->files_index);
1461
1462         if (td->nr_done_files >= td->o.nr_files) {
1463                 dprint(FD_FILE, "get_next_file: nr_open=%d, nr_done=%d,"
1464                                 " nr_files=%d\n", td->nr_open_files,
1465                                                   td->nr_done_files,
1466                                                   td->o.nr_files);
1467                 return NULL;
1468         }
1469
1470         f = td->file_service_file;
1471         if (f && fio_file_open(f) && !fio_file_closing(f)) {
1472                 if (td->o.file_service_type == FIO_FSERVICE_SEQ)
1473                         goto out;
1474                 if (td->file_service_left) {
1475                         td->file_service_left--;
1476                         goto out;
1477                 }
1478         }
1479
1480         if (td->o.file_service_type == FIO_FSERVICE_RR ||
1481             td->o.file_service_type == FIO_FSERVICE_SEQ)
1482                 f = get_next_file_rr(td, FIO_FILE_open, FIO_FILE_closing);
1483         else
1484                 f = get_next_file_rand(td, FIO_FILE_open, FIO_FILE_closing);
1485
1486         if (IS_ERR(f))
1487                 return f;
1488
1489         td->file_service_file = f;
1490         td->file_service_left = td->file_service_nr - 1;
1491 out:
1492         if (f)
1493                 dprint(FD_FILE, "get_next_file: %p [%s]\n", f, f->file_name);
1494         else
1495                 dprint(FD_FILE, "get_next_file: NULL\n");
1496         return f;
1497 }
1498
1499 static struct fio_file *get_next_file(struct thread_data *td)
1500 {
1501         return __get_next_file(td);
1502 }
1503
1504 static long set_io_u_file(struct thread_data *td, struct io_u *io_u)
1505 {
1506         struct fio_file *f;
1507
1508         do {
1509                 f = get_next_file(td);
1510                 if (IS_ERR_OR_NULL(f))
1511                         return PTR_ERR(f);
1512
1513                 io_u->file = f;
1514                 get_file(f);
1515
1516                 if (!fill_io_u(td, io_u))
1517                         break;
1518
1519                 zbd_put_io_u(td, io_u);
1520
1521                 put_file_log(td, f);
1522                 td_io_close_file(td, f);
1523                 io_u->file = NULL;
1524
1525                 if (io_u->ddir == DDIR_TIMEOUT)
1526                         return 1;
1527
1528                 if (td->o.file_service_type & __FIO_FSERVICE_NONUNIFORM)
1529                         fio_file_reset(td, f);
1530                 else {
1531                         fio_file_set_done(f);
1532                         td->nr_done_files++;
1533                         dprint(FD_FILE, "%s: is done (%d of %d)\n", f->file_name,
1534                                         td->nr_done_files, td->o.nr_files);
1535                 }
1536         } while (1);
1537
1538         return 0;
1539 }
1540
1541 static void lat_fatal(struct thread_data *td, struct io_u *io_u, struct io_completion_data *icd,
1542                       unsigned long long tnsec, unsigned long long max_nsec)
1543 {
1544         if (!td->error) {
1545                 log_err("fio: latency of %llu nsec exceeds specified max (%llu nsec): %s %s %llu %llu\n",
1546                                         tnsec, max_nsec,
1547                                         io_u->file->file_name,
1548                                         io_ddir_name(io_u->ddir),
1549                                         io_u->offset, io_u->buflen);
1550         }
1551         td_verror(td, ETIMEDOUT, "max latency exceeded");
1552         icd->error = ETIMEDOUT;
1553 }
1554
1555 static void lat_new_cycle(struct thread_data *td)
1556 {
1557         fio_gettime(&td->latency_ts, NULL);
1558         td->latency_ios = ddir_rw_sum(td->io_blocks);
1559         td->latency_failed = 0;
1560 }
1561
1562 /*
1563  * We had an IO outside the latency target. Reduce the queue depth. If we
1564  * are at QD=1, then it's time to give up.
1565  */
1566 static bool __lat_target_failed(struct thread_data *td)
1567 {
1568         if (td->latency_qd == 1)
1569                 return true;
1570
1571         td->latency_qd_high = td->latency_qd;
1572
1573         if (td->latency_qd == td->latency_qd_low)
1574                 td->latency_qd_low--;
1575
1576         td->latency_qd = (td->latency_qd + td->latency_qd_low) / 2;
1577         td->latency_stable_count = 0;
1578
1579         dprint(FD_RATE, "Ramped down: %d %d %d\n", td->latency_qd_low, td->latency_qd, td->latency_qd_high);
1580
1581         /*
1582          * When we ramp QD down, quiesce existing IO to prevent
1583          * a storm of ramp downs due to pending higher depth.
1584          */
1585         io_u_quiesce(td);
1586         lat_new_cycle(td);
1587         return false;
1588 }
1589
1590 static bool lat_target_failed(struct thread_data *td)
1591 {
1592         if (td->o.latency_percentile.u.f == 100.0)
1593                 return __lat_target_failed(td);
1594
1595         td->latency_failed++;
1596         return false;
1597 }
1598
1599 void lat_target_init(struct thread_data *td)
1600 {
1601         td->latency_end_run = 0;
1602
1603         if (td->o.latency_target) {
1604                 dprint(FD_RATE, "Latency target=%llu\n", td->o.latency_target);
1605                 fio_gettime(&td->latency_ts, NULL);
1606                 td->latency_qd = 1;
1607                 td->latency_qd_high = td->o.iodepth;
1608                 td->latency_qd_low = 1;
1609                 td->latency_ios = ddir_rw_sum(td->io_blocks);
1610         } else
1611                 td->latency_qd = td->o.iodepth;
1612 }
1613
1614 void lat_target_reset(struct thread_data *td)
1615 {
1616         if (!td->latency_end_run)
1617                 lat_target_init(td);
1618 }
1619
1620 static void lat_target_success(struct thread_data *td)
1621 {
1622         const unsigned int qd = td->latency_qd;
1623         struct thread_options *o = &td->o;
1624
1625         td->latency_qd_low = td->latency_qd;
1626
1627         if (td->latency_qd + 1 == td->latency_qd_high) {
1628                 /*
1629                  * latency_qd will not incease on lat_target_success(), so
1630                  * called stable. If we stick with this queue depth, the
1631                  * final latency is likely lower than latency_target. Fix
1632                  * this by increasing latency_qd_high slowly. Use a naive
1633                  * heuristic here. If we get lat_target_success() 3 times
1634                  * in a row, increase latency_qd_high by 1.
1635                  */
1636                 if (++td->latency_stable_count >= 3) {
1637                         td->latency_qd_high++;
1638                         td->latency_stable_count = 0;
1639                 }
1640         }
1641
1642         /*
1643          * If we haven't failed yet, we double up to a failing value instead
1644          * of bisecting from highest possible queue depth. If we have set
1645          * a limit other than td->o.iodepth, bisect between that.
1646          */
1647         if (td->latency_qd_high != o->iodepth)
1648                 td->latency_qd = (td->latency_qd + td->latency_qd_high) / 2;
1649         else
1650                 td->latency_qd *= 2;
1651
1652         if (td->latency_qd > o->iodepth)
1653                 td->latency_qd = o->iodepth;
1654
1655         dprint(FD_RATE, "Ramped up: %d %d %d\n", td->latency_qd_low, td->latency_qd, td->latency_qd_high);
1656
1657         /*
1658          * Same as last one, we are done. Let it run a latency cycle, so
1659          * we get only the results from the targeted depth.
1660          */
1661         if (!o->latency_run && td->latency_qd == qd) {
1662                 if (td->latency_end_run) {
1663                         dprint(FD_RATE, "We are done\n");
1664                         td->done = 1;
1665                 } else {
1666                         dprint(FD_RATE, "Quiesce and final run\n");
1667                         io_u_quiesce(td);
1668                         td->latency_end_run = 1;
1669                         reset_all_stats(td);
1670                         reset_io_stats(td);
1671                 }
1672         }
1673
1674         lat_new_cycle(td);
1675 }
1676
1677 /*
1678  * Check if we can bump the queue depth
1679  */
1680 void lat_target_check(struct thread_data *td)
1681 {
1682         uint64_t usec_window;
1683         uint64_t ios;
1684         double success_ios;
1685
1686         usec_window = utime_since_now(&td->latency_ts);
1687         if (usec_window < td->o.latency_window)
1688                 return;
1689
1690         ios = ddir_rw_sum(td->io_blocks) - td->latency_ios;
1691         success_ios = (double) (ios - td->latency_failed) / (double) ios;
1692         success_ios *= 100.0;
1693
1694         dprint(FD_RATE, "Success rate: %.2f%% (target %.2f%%)\n", success_ios, td->o.latency_percentile.u.f);
1695
1696         if (success_ios >= td->o.latency_percentile.u.f)
1697                 lat_target_success(td);
1698         else
1699                 __lat_target_failed(td);
1700 }
1701
1702 /*
1703  * If latency target is enabled, we might be ramping up or down and not
1704  * using the full queue depth available.
1705  */
1706 bool queue_full(const struct thread_data *td)
1707 {
1708         const int qempty = io_u_qempty(&td->io_u_freelist);
1709
1710         if (qempty)
1711                 return true;
1712         if (!td->o.latency_target)
1713                 return false;
1714
1715         return td->cur_depth >= td->latency_qd;
1716 }
1717
1718 struct io_u *__get_io_u(struct thread_data *td)
1719 {
1720         const bool needs_lock = td_async_processing(td);
1721         struct io_u *io_u = NULL;
1722
1723         if (td->stop_io)
1724                 return NULL;
1725
1726         if (needs_lock)
1727                 __td_io_u_lock(td);
1728
1729 again:
1730         if (td->runstate != TD_FSYNCING && !io_u_rempty(&td->io_u_requeues)) {
1731                 io_u = io_u_rpop(&td->io_u_requeues);
1732                 io_u->resid = 0;
1733         } else if (!queue_full(td)) {
1734                 io_u = io_u_qpop(&td->io_u_freelist);
1735
1736                 io_u->file = NULL;
1737                 io_u->buflen = 0;
1738                 io_u->resid = 0;
1739                 io_u->end_io = NULL;
1740         }
1741
1742         if (io_u) {
1743                 assert(io_u->flags & IO_U_F_FREE);
1744                 io_u_clear(td, io_u, IO_U_F_FREE | IO_U_F_NO_FILE_PUT |
1745                                  IO_U_F_TRIMMED | IO_U_F_BARRIER |
1746                                  IO_U_F_VER_LIST);
1747
1748                 io_u->error = 0;
1749                 io_u->acct_ddir = -1;
1750                 td->cur_depth++;
1751                 assert(!(td->flags & TD_F_CHILD));
1752                 io_u_set(td, io_u, IO_U_F_IN_CUR_DEPTH);
1753                 io_u->ipo = NULL;
1754         } else if (td_async_processing(td)) {
1755                 int ret;
1756                 /*
1757                  * We ran out, wait for async verify threads to finish and
1758                  * return one
1759                  */
1760                 assert(!(td->flags & TD_F_CHILD));
1761                 ret = pthread_cond_wait(&td->free_cond, &td->io_u_lock);
1762                 if (fio_unlikely(ret != 0)) {
1763                         td->error = errno;
1764                 } else if (!td->error)
1765                         goto again;
1766         }
1767
1768         if (needs_lock)
1769                 __td_io_u_unlock(td);
1770
1771         return io_u;
1772 }
1773
1774 static bool check_get_trim(struct thread_data *td, struct io_u *io_u)
1775 {
1776         if (!(td->flags & TD_F_TRIM_BACKLOG))
1777                 return false;
1778         if (!td->trim_entries) {
1779                 td->trim_batch = 0;
1780                 return false;
1781         }
1782
1783         if (td->trim_batch) {
1784                 td->trim_batch--;
1785                 if (get_next_trim(td, io_u))
1786                         return true;
1787                 else
1788                         td->trim_batch = 0;
1789         } else if (!(td->io_hist_len % td->o.trim_backlog) &&
1790                      td->last_ddir_completed != DDIR_TRIM) {
1791                 if (get_next_trim(td, io_u)) {
1792                         td->trim_batch = td->o.trim_batch;
1793                         if (!td->trim_batch)
1794                                 td->trim_batch = td->o.trim_backlog;
1795                         td->trim_batch--;
1796                         return true;
1797                 }
1798         }
1799
1800         return false;
1801 }
1802
1803 static bool check_get_verify(struct thread_data *td, struct io_u *io_u)
1804 {
1805         if (!(td->flags & TD_F_VER_BACKLOG))
1806                 return false;
1807
1808         if (td->io_hist_len) {
1809                 int get_verify = 0;
1810
1811                 if (td->verify_batch)
1812                         get_verify = 1;
1813                 else if (!(td->io_hist_len % td->o.verify_backlog) &&
1814                          td->last_ddir_completed != DDIR_READ) {
1815                         td->verify_batch = td->o.verify_batch;
1816                         if (!td->verify_batch)
1817                                 td->verify_batch = td->o.verify_backlog;
1818                         get_verify = 1;
1819                 }
1820
1821                 if (get_verify && !get_next_verify(td, io_u)) {
1822                         td->verify_batch--;
1823                         return true;
1824                 }
1825         }
1826
1827         return false;
1828 }
1829
1830 /*
1831  * Fill offset and start time into the buffer content, to prevent too
1832  * easy compressible data for simple de-dupe attempts. Do this for every
1833  * 512b block in the range, since that should be the smallest block size
1834  * we can expect from a device.
1835  */
1836 static void small_content_scramble(struct io_u *io_u)
1837 {
1838         unsigned long long i, nr_blocks = io_u->buflen >> 9;
1839         unsigned int offset;
1840         uint64_t boffset, *iptr;
1841         char *p;
1842
1843         if (!nr_blocks)
1844                 return;
1845
1846         p = io_u->xfer_buf;
1847         boffset = io_u->offset;
1848
1849         if (io_u->buf_filled_len)
1850                 io_u->buf_filled_len = 0;
1851
1852         /*
1853          * Generate random index between 0..7. We do chunks of 512b, if
1854          * we assume a cacheline is 64 bytes, then we have 8 of those.
1855          * Scramble content within the blocks in the same cacheline to
1856          * speed things up.
1857          */
1858         offset = (io_u->start_time.tv_nsec ^ boffset) & 7;
1859
1860         for (i = 0; i < nr_blocks; i++) {
1861                 /*
1862                  * Fill offset into start of cacheline, time into end
1863                  * of cacheline
1864                  */
1865                 iptr = (void *) p + (offset << 6);
1866                 *iptr = boffset;
1867
1868                 iptr = (void *) p + 64 - 2 * sizeof(uint64_t);
1869                 iptr[0] = io_u->start_time.tv_sec;
1870                 iptr[1] = io_u->start_time.tv_nsec;
1871
1872                 p += 512;
1873                 boffset += 512;
1874         }
1875 }
1876
1877 /*
1878  * Return an io_u to be processed. Gets a buflen and offset, sets direction,
1879  * etc. The returned io_u is fully ready to be prepped, populated and submitted.
1880  */
1881 struct io_u *get_io_u(struct thread_data *td)
1882 {
1883         struct fio_file *f;
1884         struct io_u *io_u;
1885         int do_scramble = 0;
1886         long ret = 0;
1887
1888         io_u = __get_io_u(td);
1889         if (!io_u) {
1890                 dprint(FD_IO, "__get_io_u failed\n");
1891                 return NULL;
1892         }
1893
1894         if (check_get_verify(td, io_u))
1895                 goto out;
1896         if (check_get_trim(td, io_u))
1897                 goto out;
1898
1899         /*
1900          * from a requeue, io_u already setup
1901          */
1902         if (io_u->file)
1903                 goto out;
1904
1905         /*
1906          * If using an iolog, grab next piece if any available.
1907          */
1908         if (td->flags & TD_F_READ_IOLOG) {
1909                 if (read_iolog_get(td, io_u))
1910                         goto err_put;
1911         } else if (set_io_u_file(td, io_u)) {
1912                 ret = -EBUSY;
1913                 dprint(FD_IO, "io_u %p, setting file failed\n", io_u);
1914                 goto err_put;
1915         }
1916
1917         f = io_u->file;
1918         if (!f) {
1919                 dprint(FD_IO, "io_u %p, setting file failed\n", io_u);
1920                 goto err_put;
1921         }
1922
1923         assert(fio_file_open(f));
1924
1925         if (ddir_rw(io_u->ddir) && !multi_range_trim(td, io_u)) {
1926                 if (!io_u->buflen && !td_ioengine_flagged(td, FIO_NOIO)) {
1927                         dprint(FD_IO, "get_io_u: zero buflen on %p\n", io_u);
1928                         goto err_put;
1929                 }
1930
1931                 f->last_start[io_u->ddir] = io_u->offset;
1932                 f->last_pos[io_u->ddir] = io_u->offset + io_u->buflen;
1933
1934                 if (io_u->ddir == DDIR_WRITE) {
1935                         if (td->flags & TD_F_REFILL_BUFFERS) {
1936                                 io_u_fill_buffer(td, io_u,
1937                                         td->o.min_bs[DDIR_WRITE],
1938                                         io_u->buflen);
1939                         } else if ((td->flags & TD_F_SCRAMBLE_BUFFERS) &&
1940                                    !(td->flags & TD_F_COMPRESS) &&
1941                                    !(td->flags & TD_F_DO_VERIFY)) {
1942                                 do_scramble = 1;
1943                         }
1944                 } else if (io_u->ddir == DDIR_READ) {
1945                         /*
1946                          * Reset the buf_filled parameters so next time if the
1947                          * buffer is used for writes it is refilled.
1948                          */
1949                         io_u->buf_filled_len = 0;
1950                 }
1951         }
1952
1953         /*
1954          * Set io data pointers.
1955          */
1956         io_u->xfer_buf = io_u->buf;
1957         io_u->xfer_buflen = io_u->buflen;
1958
1959         /*
1960          * Remember the issuing context priority. The IO engine may change this.
1961          */
1962         io_u->ioprio = td->ioprio;
1963         io_u->clat_prio_index = 0;
1964 out:
1965         assert(io_u->file);
1966         if (!td_io_prep(td, io_u)) {
1967                 if (!td->o.disable_lat)
1968                         fio_gettime(&io_u->start_time, NULL);
1969
1970                 if (do_scramble)
1971                         small_content_scramble(io_u);
1972
1973                 return io_u;
1974         }
1975 err_put:
1976         dprint(FD_IO, "get_io_u failed\n");
1977         put_io_u(td, io_u);
1978         return ERR_PTR(ret);
1979 }
1980
1981 static void __io_u_log_error(struct thread_data *td, struct io_u *io_u)
1982 {
1983         enum error_type_bit eb = td_error_type(io_u->ddir, io_u->error);
1984
1985         if (td_non_fatal_error(td, eb, io_u->error) && !td->o.error_dump)
1986                 return;
1987
1988         log_err("fio: io_u error%s%s: %s: %s offset=%llu, buflen=%llu\n",
1989                 io_u->file ? " on file " : "",
1990                 io_u->file ? io_u->file->file_name : "",
1991                 (io_u->flags & IO_U_F_DEVICE_ERROR) ?
1992                         "Device-specific error" : strerror(io_u->error),
1993                 io_ddir_name(io_u->ddir),
1994                 io_u->offset, io_u->xfer_buflen);
1995
1996         zbd_log_err(td, io_u);
1997
1998         if (td->io_ops->errdetails) {
1999                 char *err = td->io_ops->errdetails(td, io_u);
2000
2001                 if (err) {
2002                         log_err("fio: %s\n", err);
2003                         free(err);
2004                 }
2005         }
2006
2007         if (!td->error)
2008                 td_verror(td, io_u->error, "io_u error");
2009 }
2010
2011 void io_u_log_error(struct thread_data *td, struct io_u *io_u)
2012 {
2013         __io_u_log_error(td, io_u);
2014         if (td->parent)
2015                 __io_u_log_error(td->parent, io_u);
2016 }
2017
2018 static inline bool gtod_reduce(struct thread_data *td)
2019 {
2020         return (td->o.disable_clat && td->o.disable_slat && td->o.disable_bw)
2021                         || td->o.gtod_reduce;
2022 }
2023
2024 static void trim_block_info(struct thread_data *td, struct io_u *io_u)
2025 {
2026         uint32_t *info = io_u_block_info(td, io_u);
2027
2028         if (BLOCK_INFO_STATE(*info) >= BLOCK_STATE_TRIM_FAILURE)
2029                 return;
2030
2031         *info = BLOCK_INFO(BLOCK_STATE_TRIMMED, BLOCK_INFO_TRIMS(*info) + 1);
2032 }
2033
2034 static void account_io_completion(struct thread_data *td, struct io_u *io_u,
2035                                   struct io_completion_data *icd,
2036                                   const enum fio_ddir idx, unsigned int bytes)
2037 {
2038         const int no_reduce = !gtod_reduce(td);
2039         unsigned long long llnsec = 0;
2040
2041         if (td->parent)
2042                 td = td->parent;
2043
2044         if (!td->o.stats || td_ioengine_flagged(td, FIO_NOSTATS))
2045                 return;
2046
2047         if (no_reduce)
2048                 llnsec = ntime_since(&io_u->issue_time, &icd->time);
2049
2050         if (!td->o.disable_lat) {
2051                 unsigned long long tnsec;
2052
2053                 tnsec = ntime_since(&io_u->start_time, &icd->time);
2054                 add_lat_sample(td, idx, tnsec, bytes, io_u);
2055
2056                 if (td->flags & TD_F_PROFILE_OPS) {
2057                         struct prof_io_ops *ops = &td->prof_io_ops;
2058
2059                         if (ops->io_u_lat)
2060                                 icd->error = ops->io_u_lat(td, tnsec);
2061                 }
2062
2063                 if (ddir_rw(idx)) {
2064                         if (td->o.max_latency[idx] && tnsec > td->o.max_latency[idx])
2065                                 lat_fatal(td, io_u, icd, tnsec, td->o.max_latency[idx]);
2066                         if (td->o.latency_target && tnsec > td->o.latency_target) {
2067                                 if (lat_target_failed(td))
2068                                         lat_fatal(td, io_u, icd, tnsec, td->o.latency_target);
2069                         }
2070                 }
2071         }
2072
2073         if (ddir_rw(idx)) {
2074                 if (!td->o.disable_clat) {
2075                         add_clat_sample(td, idx, llnsec, bytes, io_u);
2076                         io_u_mark_latency(td, llnsec);
2077                 }
2078
2079                 if (!td->o.disable_bw && per_unit_log(td->bw_log))
2080                         add_bw_sample(td, io_u, bytes, llnsec);
2081
2082                 if (no_reduce && per_unit_log(td->iops_log))
2083                         add_iops_sample(td, io_u, bytes);
2084         } else if (ddir_sync(idx) && !td->o.disable_clat)
2085                 add_sync_clat_sample(&td->ts, llnsec);
2086
2087         if (td->ts.nr_block_infos && io_u->ddir == DDIR_TRIM)
2088                 trim_block_info(td, io_u);
2089 }
2090
2091 static void file_log_write_comp(const struct thread_data *td, struct fio_file *f,
2092                                 uint64_t offset, unsigned int bytes)
2093 {
2094         if (!f)
2095                 return;
2096
2097         if (f->first_write == -1ULL || offset < f->first_write)
2098                 f->first_write = offset;
2099         if (f->last_write == -1ULL || ((offset + bytes) > f->last_write))
2100                 f->last_write = offset + bytes;
2101 }
2102
2103 static bool should_account(struct thread_data *td)
2104 {
2105         return ramp_time_over(td) && (td->runstate == TD_RUNNING ||
2106                                            td->runstate == TD_VERIFYING);
2107 }
2108
2109 static void io_completed(struct thread_data *td, struct io_u **io_u_ptr,
2110                          struct io_completion_data *icd)
2111 {
2112         struct io_u *io_u = *io_u_ptr;
2113         enum fio_ddir ddir = io_u->ddir;
2114         struct fio_file *f = io_u->file;
2115
2116         dprint_io_u(io_u, "complete");
2117
2118         assert(io_u->flags & IO_U_F_FLIGHT);
2119         io_u_clear_inflight_flags(td, io_u);
2120         invalidate_inflight(td, io_u);
2121
2122         if (td->o.zone_mode == ZONE_MODE_ZBD && td->o.recover_zbd_write_error &&
2123             io_u->error && io_u->ddir == DDIR_WRITE &&
2124             !td_ioengine_flagged(td, FIO_SYNCIO))
2125                 zbd_recover_write_error(td, io_u);
2126
2127         /*
2128          * Mark IO ok to verify
2129          */
2130         if (io_u->ipo) {
2131                 /*
2132                  * Remove errored entry from the verification list
2133                  */
2134                 if (io_u->error)
2135                         unlog_io_piece(td, io_u);
2136                 else {
2137                         atomic_store_release(&io_u->ipo->flags,
2138                                         io_u->ipo->flags & ~IP_F_IN_FLIGHT);
2139                 }
2140         }
2141
2142         if (ddir_sync(ddir)) {
2143                 if (io_u->error)
2144                         goto error;
2145                 if (f) {
2146                         f->first_write = -1ULL;
2147                         f->last_write = -1ULL;
2148                 }
2149                 if (should_account(td))
2150                         account_io_completion(td, io_u, icd, ddir, io_u->buflen);
2151                 return;
2152         }
2153
2154         td->last_ddir_completed = ddir;
2155
2156         if (!io_u->error && ddir_rw(ddir)) {
2157                 unsigned long long bytes = io_u->xfer_buflen - io_u->resid;
2158                 int ret;
2159
2160                 /*
2161                  * Make sure we notice short IO from here, and requeue them
2162                  * appropriately!
2163                  */
2164                 if (bytes && io_u->resid) {
2165                         io_u->xfer_buflen = io_u->resid;
2166                         io_u->xfer_buf += bytes;
2167                         io_u->offset += bytes;
2168                         td->ts.short_io_u[io_u->ddir]++;
2169                         if (io_u->offset < io_u->file->real_file_size) {
2170                                 requeue_io_u(td, io_u_ptr);
2171                                 return;
2172                         }
2173                 }
2174
2175                 td->io_blocks[ddir]++;
2176                 td->io_bytes[ddir] += bytes;
2177
2178                 if (!(io_u->flags & IO_U_F_VER_LIST)) {
2179                         td->this_io_blocks[ddir]++;
2180                         td->this_io_bytes[ddir] += bytes;
2181                 }
2182
2183                 if (ddir == DDIR_WRITE)
2184                         file_log_write_comp(td, f, io_u->offset, bytes);
2185
2186                 if (should_account(td))
2187                         account_io_completion(td, io_u, icd, ddir, bytes);
2188
2189                 icd->bytes_done[ddir] += bytes;
2190
2191                 if (io_u->end_io) {
2192                         ret = io_u->end_io(td, io_u_ptr);
2193                         io_u = *io_u_ptr;
2194                         if (ret && !icd->error)
2195                                 icd->error = ret;
2196                 }
2197         } else if (io_u->error) {
2198 error:
2199                 icd->error = io_u->error;
2200                 io_u_log_error(td, io_u);
2201         }
2202         if (icd->error) {
2203                 enum error_type_bit eb = td_error_type(ddir, icd->error);
2204
2205                 if (!td_non_fatal_error(td, eb, icd->error))
2206                         return;
2207
2208                 /*
2209                  * If there is a non_fatal error, then add to the error count
2210                  * and clear all the errors.
2211                  */
2212                 update_error_count(td, icd->error);
2213                 td_clear_error(td);
2214                 icd->error = 0;
2215                 if (io_u)
2216                         io_u->error = 0;
2217         }
2218 }
2219
2220 static void init_icd(struct thread_data *td, struct io_completion_data *icd,
2221                      int nr)
2222 {
2223         int ddir;
2224
2225         if (!gtod_reduce(td))
2226                 fio_gettime(&icd->time, NULL);
2227
2228         icd->nr = nr;
2229
2230         icd->error = 0;
2231         for (ddir = 0; ddir < DDIR_RWDIR_CNT; ddir++)
2232                 icd->bytes_done[ddir] = 0;
2233 }
2234
2235 static void ios_completed(struct thread_data *td,
2236                           struct io_completion_data *icd)
2237 {
2238         struct io_u *io_u;
2239         int i;
2240
2241         for (i = 0; i < icd->nr; i++) {
2242                 io_u = td->io_ops->event(td, i);
2243
2244                 io_completed(td, &io_u, icd);
2245
2246                 if (io_u)
2247                         put_io_u(td, io_u);
2248         }
2249 }
2250
2251 static void io_u_update_bytes_done(struct thread_data *td,
2252                                    struct io_completion_data *icd)
2253 {
2254         int ddir;
2255
2256         if (td->runstate == TD_VERIFYING) {
2257                 td->bytes_verified += icd->bytes_done[DDIR_READ];
2258                 if (td_write(td))
2259                         return;
2260         }
2261
2262         for (ddir = 0; ddir < DDIR_RWDIR_CNT; ddir++)
2263                 td->bytes_done[ddir] += icd->bytes_done[ddir];
2264 }
2265
2266 /*
2267  * Complete a single io_u for the sync engines.
2268  */
2269 int io_u_sync_complete(struct thread_data *td, struct io_u *io_u)
2270 {
2271         struct io_completion_data icd;
2272
2273         init_icd(td, &icd, 1);
2274         io_completed(td, &io_u, &icd);
2275
2276         if (io_u)
2277                 put_io_u(td, io_u);
2278
2279         if (icd.error) {
2280                 td_verror(td, icd.error, "io_u_sync_complete");
2281                 return -1;
2282         }
2283
2284         io_u_update_bytes_done(td, &icd);
2285
2286         return 0;
2287 }
2288
2289 /*
2290  * Called to complete min_events number of io for the async engines.
2291  */
2292 int io_u_queued_complete(struct thread_data *td, int min_evts)
2293 {
2294         struct io_completion_data icd;
2295         struct timespec *tvp = NULL;
2296         int ret;
2297         struct timespec ts = { .tv_sec = 0, .tv_nsec = 0, };
2298
2299         dprint(FD_IO, "io_u_queued_complete: min=%d\n", min_evts);
2300
2301         if (!min_evts)
2302                 tvp = &ts;
2303         else if (min_evts > td->cur_depth)
2304                 min_evts = td->cur_depth;
2305
2306         /* No worries, td_io_getevents fixes min and max if they are
2307          * set incorrectly */
2308         ret = td_io_getevents(td, min_evts, td->o.iodepth_batch_complete_max, tvp);
2309         if (ret < 0) {
2310                 td_verror(td, -ret, "td_io_getevents");
2311                 return ret;
2312         } else if (!ret)
2313                 return ret;
2314
2315         init_icd(td, &icd, ret);
2316         ios_completed(td, &icd);
2317         if (icd.error) {
2318                 td_verror(td, icd.error, "io_u_queued_complete");
2319                 return -1;
2320         }
2321
2322         io_u_update_bytes_done(td, &icd);
2323
2324         return ret;
2325 }
2326
2327 /*
2328  * Call when io_u is really queued, to update the submission latency.
2329  */
2330 void io_u_queued(struct thread_data *td, struct io_u *io_u)
2331 {
2332         if (!td->o.disable_slat && ramp_time_over(td) && td->o.stats) {
2333                 if (td->parent)
2334                         td = td->parent;
2335                 add_slat_sample(td, io_u);
2336         }
2337 }
2338
2339 /*
2340  * See if we should reuse the last seed, if dedupe is enabled
2341  */
2342 static struct frand_state *get_buf_state(struct thread_data *td)
2343 {
2344         unsigned int v;
2345         unsigned long long i;
2346
2347         if (!td->o.dedupe_percentage)
2348                 return &td->buf_state;
2349         else if (td->o.dedupe_percentage == 100) {
2350                 frand_copy(&td->buf_state_prev, &td->buf_state);
2351                 return &td->buf_state;
2352         }
2353
2354         v = rand_between(&td->dedupe_state, 1, 100);
2355
2356         if (v <= td->o.dedupe_percentage)
2357                 switch (td->o.dedupe_mode) {
2358                 case DEDUPE_MODE_REPEAT:
2359                         /*
2360                         * The caller advances the returned frand_state.
2361                         * A copy of prev should be returned instead since
2362                         * a subsequent intention to generate a deduped buffer
2363                         * might result in generating a unique one
2364                         */
2365                         frand_copy(&td->buf_state_ret, &td->buf_state_prev);
2366                         return &td->buf_state_ret;
2367                 case DEDUPE_MODE_WORKING_SET:
2368                         i = rand_between(&td->dedupe_working_set_index_state, 0, td->num_unique_pages - 1);
2369                         frand_copy(&td->buf_state_ret, &td->dedupe_working_set_states[i]);
2370                         return &td->buf_state_ret;
2371                 default:
2372                         log_err("unexpected dedupe mode %u\n", td->o.dedupe_mode);
2373                         assert(0);
2374                 }
2375
2376         return &td->buf_state;
2377 }
2378
2379 static void save_buf_state(struct thread_data *td, struct frand_state *rs)
2380 {
2381         if (td->o.dedupe_percentage == 100)
2382                 frand_copy(rs, &td->buf_state_prev);
2383         else if (rs == &td->buf_state)
2384                 frand_copy(&td->buf_state_prev, rs);
2385 }
2386
2387 void fill_io_buffer(struct thread_data *td, void *buf, unsigned long long min_write,
2388                     unsigned long long max_bs)
2389 {
2390         struct thread_options *o = &td->o;
2391
2392         if (o->mem_type == MEM_CUDA_MALLOC)
2393                 return;
2394
2395         if (o->compress_percentage || o->dedupe_percentage) {
2396                 unsigned int perc = td->o.compress_percentage;
2397                 struct frand_state *rs = NULL;
2398                 unsigned long long left = max_bs;
2399                 unsigned long long this_write;
2400
2401                 do {
2402                         /*
2403                          * Buffers are either entirely dedupe-able or not.
2404                          * If we choose to dedup, the buffer should undergo
2405                          * the same manipulation as the original write. Which
2406                          * means we should retrack the steps we took for compression
2407                          * as well.
2408                          */
2409                         if (!rs)
2410                                 rs = get_buf_state(td);
2411
2412                         min_write = min(min_write, left);
2413
2414                         this_write = min_not_zero(min_write,
2415                                                 (unsigned long long) td->o.compress_chunk);
2416
2417                         fill_random_buf_percentage(rs, buf, perc,
2418                                 this_write, this_write,
2419                                 o->buffer_pattern,
2420                                 o->buffer_pattern_bytes);
2421
2422                         buf += this_write;
2423                         left -= this_write;
2424                         save_buf_state(td, rs);
2425                 } while (left);
2426         } else if (o->buffer_pattern_bytes)
2427                 fill_buffer_pattern(td, buf, max_bs);
2428         else if (o->zero_buffers)
2429                 memset(buf, 0, max_bs);
2430         else
2431                 fill_random_buf(get_buf_state(td), buf, max_bs);
2432 }
2433
2434 /*
2435  * "randomly" fill the buffer contents
2436  */
2437 void io_u_fill_buffer(struct thread_data *td, struct io_u *io_u,
2438                       unsigned long long min_write, unsigned long long max_bs)
2439 {
2440         io_u->buf_filled_len = 0;
2441         fill_io_buffer(td, io_u->buf, min_write, max_bs);
2442 }
2443
2444 static int do_sync_file_range(const struct thread_data *td,
2445                               struct fio_file *f)
2446 {
2447         uint64_t offset, nbytes;
2448
2449         offset = f->first_write;
2450         nbytes = f->last_write - f->first_write;
2451
2452         if (!nbytes)
2453                 return 0;
2454
2455         return sync_file_range(f->fd, offset, nbytes, td->o.sync_file_range);
2456 }
2457
2458 int do_io_u_sync(const struct thread_data *td, struct io_u *io_u)
2459 {
2460         int ret;
2461
2462         if (io_u->ddir == DDIR_SYNC) {
2463 #ifdef CONFIG_FCNTL_SYNC
2464                 ret = fcntl(io_u->file->fd, F_FULLFSYNC);
2465 #else
2466                 ret = fsync(io_u->file->fd);
2467 #endif
2468         } else if (io_u->ddir == DDIR_DATASYNC) {
2469 #ifdef CONFIG_FDATASYNC
2470                 ret = fdatasync(io_u->file->fd);
2471 #else
2472                 ret = io_u->xfer_buflen;
2473                 io_u->error = EINVAL;
2474 #endif
2475         } else if (io_u->ddir == DDIR_SYNC_FILE_RANGE)
2476                 ret = do_sync_file_range(td, io_u->file);
2477         else {
2478                 ret = io_u->xfer_buflen;
2479                 io_u->error = EINVAL;
2480         }
2481
2482         if (ret < 0)
2483                 io_u->error = errno;
2484
2485         return ret;
2486 }
2487
2488 int do_io_u_trim(struct thread_data *td, struct io_u *io_u)
2489 {
2490 #ifndef FIO_HAVE_TRIM
2491         io_u->error = EINVAL;
2492         return 0;
2493 #else
2494         struct fio_file *f = io_u->file;
2495         int ret;
2496
2497         if (td->o.zone_mode == ZONE_MODE_ZBD) {
2498                 ret = zbd_do_io_u_trim(td, io_u);
2499                 if (ret == io_u_completed)
2500                         return io_u->xfer_buflen;
2501                 if (ret)
2502                         goto err;
2503         }
2504
2505         ret = os_trim(f, io_u->offset, io_u->xfer_buflen);
2506         if (!ret)
2507                 return io_u->xfer_buflen;
2508
2509 err:
2510         io_u->error = ret;
2511         return 0;
2512 #endif
2513 }