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