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