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