Rework file random map
[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/bitmap.h"
14
15 struct io_completion_data {
16         int nr;                         /* input */
17
18         int error;                      /* output */
19         unsigned long bytes_done[DDIR_RWDIR_CNT];       /* output */
20         struct timeval time;            /* output */
21 };
22
23 /*
24  * The ->io_bitmap contains a map of blocks we have or have not done io
25  * to yet. Used to make sure we cover the entire range in a fair fashion.
26  */
27 static int random_map_free(struct fio_file *f, const unsigned long long block)
28 {
29         return !bitmap_isset(f->io_bitmap, block);
30 }
31
32 /*
33  * Mark a given offset as used in the map.
34  */
35 static void mark_random_map(struct thread_data *td, struct io_u *io_u)
36 {
37         unsigned int min_bs = td->o.rw_min_bs;
38         struct fio_file *f = io_u->file;
39         unsigned long long block;
40         unsigned int nr_blocks;
41
42         block = (io_u->offset - f->file_offset) / (unsigned long long) min_bs;
43         nr_blocks = (io_u->buflen + min_bs - 1) / min_bs;
44
45         nr_blocks = bitmap_set_nr(f->io_bitmap, block, nr_blocks);
46
47         if ((nr_blocks * min_bs) < io_u->buflen)
48                 io_u->buflen = nr_blocks * min_bs;
49 }
50
51 static unsigned long long last_block(struct thread_data *td, struct fio_file *f,
52                                      enum fio_ddir ddir)
53 {
54         unsigned long long max_blocks;
55         unsigned long long max_size;
56
57         assert(ddir_rw(ddir));
58
59         /*
60          * Hmm, should we make sure that ->io_size <= ->real_file_size?
61          */
62         max_size = f->io_size;
63         if (max_size > f->real_file_size)
64                 max_size = f->real_file_size;
65
66         if (td->o.zone_range)
67                 max_size = td->o.zone_range;
68
69         max_blocks = max_size / (unsigned long long) td->o.ba[ddir];
70         if (!max_blocks)
71                 return 0;
72
73         return max_blocks;
74 }
75
76 static int __get_next_rand_offset(struct thread_data *td, struct fio_file *f,
77                                   enum fio_ddir ddir, unsigned long long *b)
78 {
79         unsigned long long rmax, r, lastb;
80
81         lastb = last_block(td, f, ddir);
82         if (!lastb)
83                 return 1;
84
85         rmax = td->o.use_os_rand ? OS_RAND_MAX : FRAND_MAX;
86
87         if (td->o.use_os_rand) {
88                 rmax = OS_RAND_MAX;
89                 r = os_random_long(&td->random_state);
90         } else {
91                 rmax = FRAND_MAX;
92                 r = __rand(&td->__random_state);
93         }
94
95         *b = (lastb - 1) * (r / ((unsigned long long) rmax + 1.0));
96
97         dprint(FD_RANDOM, "off rand %llu\n", r);
98
99         /*
100          * if we are not maintaining a random map, we are done.
101          */
102         if (!file_randommap(td, f))
103                 goto ret;
104
105         /*
106          * calculate map offset and check if it's free
107          */
108         if (random_map_free(f, *b))
109                 goto ret;
110
111         dprint(FD_RANDOM, "get_next_rand_offset: offset %llu busy\n", *b);
112
113         *b = bitmap_next_free(f->io_bitmap, *b);
114         if (*b == (uint64_t) -1ULL)
115                 return 1;
116 ret:
117         return 0;
118 }
119
120 static int __get_next_rand_offset_zipf(struct thread_data *td,
121                                        struct fio_file *f, enum fio_ddir ddir,
122                                        unsigned long long *b)
123 {
124         *b = zipf_next(&f->zipf);
125         return 0;
126 }
127
128 static int __get_next_rand_offset_pareto(struct thread_data *td,
129                                          struct fio_file *f, enum fio_ddir ddir,
130                                          unsigned long long *b)
131 {
132         *b = pareto_next(&f->zipf);
133         return 0;
134 }
135
136 static int get_next_rand_offset(struct thread_data *td, struct fio_file *f,
137                                 enum fio_ddir ddir, unsigned long long *b)
138 {
139         if (td->o.random_distribution == FIO_RAND_DIST_RANDOM)
140                 return __get_next_rand_offset(td, f, ddir, b);
141         else if (td->o.random_distribution == FIO_RAND_DIST_ZIPF)
142                 return __get_next_rand_offset_zipf(td, f, ddir, b);
143         else if (td->o.random_distribution == FIO_RAND_DIST_PARETO)
144                 return __get_next_rand_offset_pareto(td, f, ddir, b);
145
146         log_err("fio: unknown random distribution: %d\n", td->o.random_distribution);
147         return 1;
148 }
149
150 static int get_next_rand_block(struct thread_data *td, struct fio_file *f,
151                                enum fio_ddir ddir, unsigned long long *b)
152 {
153         if (!get_next_rand_offset(td, f, ddir, b))
154                 return 0;
155
156         if (td->o.time_based) {
157                 fio_file_reset(f);
158                 if (!get_next_rand_offset(td, f, ddir, b))
159                         return 0;
160         }
161
162         dprint(FD_IO, "%s: rand offset failed, last=%llu, size=%llu\n",
163                         f->file_name, f->last_pos, f->real_file_size);
164         return 1;
165 }
166
167 static int get_next_seq_offset(struct thread_data *td, struct fio_file *f,
168                                enum fio_ddir ddir, unsigned long long *offset)
169 {
170         assert(ddir_rw(ddir));
171
172         if (f->last_pos >= f->io_size + get_start_offset(td) && td->o.time_based)
173                 f->last_pos = f->last_pos - f->io_size;
174
175         if (f->last_pos < f->real_file_size) {
176                 unsigned long long pos;
177
178                 if (f->last_pos == f->file_offset && td->o.ddir_seq_add < 0)
179                         f->last_pos = f->real_file_size;
180
181                 pos = f->last_pos - f->file_offset;
182                 if (pos)
183                         pos += td->o.ddir_seq_add;
184
185                 *offset = pos;
186                 return 0;
187         }
188
189         return 1;
190 }
191
192 static int get_next_block(struct thread_data *td, struct io_u *io_u,
193                           enum fio_ddir ddir, int rw_seq)
194 {
195         struct fio_file *f = io_u->file;
196         unsigned long long b, offset;
197         int ret;
198
199         assert(ddir_rw(ddir));
200
201         b = offset = -1ULL;
202
203         if (rw_seq) {
204                 if (td_random(td))
205                         ret = get_next_rand_block(td, f, ddir, &b);
206                 else
207                         ret = get_next_seq_offset(td, f, ddir, &offset);
208         } else {
209                 io_u->flags |= IO_U_F_BUSY_OK;
210
211                 if (td->o.rw_seq == RW_SEQ_SEQ) {
212                         ret = get_next_seq_offset(td, f, ddir, &offset);
213                         if (ret)
214                                 ret = get_next_rand_block(td, f, ddir, &b);
215                 } else if (td->o.rw_seq == RW_SEQ_IDENT) {
216                         if (f->last_start != -1ULL)
217                                 offset = f->last_start - f->file_offset;
218                         else
219                                 offset = 0;
220                         ret = 0;
221                 } else {
222                         log_err("fio: unknown rw_seq=%d\n", td->o.rw_seq);
223                         ret = 1;
224                 }
225         }
226         
227         if (!ret) {
228                 if (offset != -1ULL)
229                         io_u->offset = offset;
230                 else if (b != -1ULL)
231                         io_u->offset = b * td->o.ba[ddir];
232                 else {
233                         log_err("fio: bug in offset generation: offset=%llu, b=%llu\n",
234                                                                 offset, b);
235                         ret = 1;
236                 }
237         }
238
239         return ret;
240 }
241
242 /*
243  * For random io, generate a random new block and see if it's used. Repeat
244  * until we find a free one. For sequential io, just return the end of
245  * the last io issued.
246  */
247 static int __get_next_offset(struct thread_data *td, struct io_u *io_u)
248 {
249         struct fio_file *f = io_u->file;
250         enum fio_ddir ddir = io_u->ddir;
251         int rw_seq_hit = 0;
252
253         assert(ddir_rw(ddir));
254
255         if (td->o.ddir_seq_nr && !--td->ddir_seq_nr) {
256                 rw_seq_hit = 1;
257                 td->ddir_seq_nr = td->o.ddir_seq_nr;
258         }
259
260         if (get_next_block(td, io_u, ddir, rw_seq_hit))
261                 return 1;
262
263         if (io_u->offset >= f->io_size) {
264                 dprint(FD_IO, "get_next_offset: offset %llu >= io_size %llu\n",
265                                         io_u->offset, f->io_size);
266                 return 1;
267         }
268
269         io_u->offset += f->file_offset;
270         if (io_u->offset >= f->real_file_size) {
271                 dprint(FD_IO, "get_next_offset: offset %llu >= size %llu\n",
272                                         io_u->offset, f->real_file_size);
273                 return 1;
274         }
275
276         return 0;
277 }
278
279 static int get_next_offset(struct thread_data *td, struct io_u *io_u)
280 {
281         struct prof_io_ops *ops = &td->prof_io_ops;
282
283         if (ops->fill_io_u_off)
284                 return ops->fill_io_u_off(td, io_u);
285
286         return __get_next_offset(td, io_u);
287 }
288
289 static inline int io_u_fits(struct thread_data *td, struct io_u *io_u,
290                             unsigned int buflen)
291 {
292         struct fio_file *f = io_u->file;
293
294         return io_u->offset + buflen <= f->io_size + get_start_offset(td);
295 }
296
297 static unsigned int __get_next_buflen(struct thread_data *td, struct io_u *io_u)
298 {
299         const int ddir = io_u->ddir;
300         unsigned int buflen = 0;
301         unsigned int minbs, maxbs;
302         unsigned long r, rand_max;
303
304         assert(ddir_rw(ddir));
305
306         minbs = td->o.min_bs[ddir];
307         maxbs = td->o.max_bs[ddir];
308
309         if (minbs == maxbs)
310                 return minbs;
311
312         /*
313          * If we can't satisfy the min block size from here, then fail
314          */
315         if (!io_u_fits(td, io_u, minbs))
316                 return 0;
317
318         if (td->o.use_os_rand)
319                 rand_max = OS_RAND_MAX;
320         else
321                 rand_max = FRAND_MAX;
322
323         do {
324                 if (td->o.use_os_rand)
325                         r = os_random_long(&td->bsrange_state);
326                 else
327                         r = __rand(&td->__bsrange_state);
328
329                 if (!td->o.bssplit_nr[ddir]) {
330                         buflen = 1 + (unsigned int) ((double) maxbs *
331                                         (r / (rand_max + 1.0)));
332                         if (buflen < minbs)
333                                 buflen = minbs;
334                 } else {
335                         long perc = 0;
336                         unsigned int i;
337
338                         for (i = 0; i < td->o.bssplit_nr[ddir]; i++) {
339                                 struct bssplit *bsp = &td->o.bssplit[ddir][i];
340
341                                 buflen = bsp->bs;
342                                 perc += bsp->perc;
343                                 if ((r <= ((rand_max / 100L) * perc)) &&
344                                     io_u_fits(td, io_u, buflen))
345                                         break;
346                         }
347                 }
348
349                 if (!td->o.bs_unaligned && is_power_of_2(minbs))
350                         buflen = (buflen + minbs - 1) & ~(minbs - 1);
351
352         } while (!io_u_fits(td, io_u, buflen));
353
354         return buflen;
355 }
356
357 static unsigned int get_next_buflen(struct thread_data *td, struct io_u *io_u)
358 {
359         struct prof_io_ops *ops = &td->prof_io_ops;
360
361         if (ops->fill_io_u_size)
362                 return ops->fill_io_u_size(td, io_u);
363
364         return __get_next_buflen(td, io_u);
365 }
366
367 static void set_rwmix_bytes(struct thread_data *td)
368 {
369         unsigned int diff;
370
371         /*
372          * we do time or byte based switch. this is needed because
373          * buffered writes may issue a lot quicker than they complete,
374          * whereas reads do not.
375          */
376         diff = td->o.rwmix[td->rwmix_ddir ^ 1];
377         td->rwmix_issues = (td->io_issues[td->rwmix_ddir] * diff) / 100;
378 }
379
380 static inline enum fio_ddir get_rand_ddir(struct thread_data *td)
381 {
382         unsigned int v;
383         unsigned long r;
384
385         if (td->o.use_os_rand) {
386                 r = os_random_long(&td->rwmix_state);
387                 v = 1 + (int) (100.0 * (r / (OS_RAND_MAX + 1.0)));
388         } else {
389                 r = __rand(&td->__rwmix_state);
390                 v = 1 + (int) (100.0 * (r / (FRAND_MAX + 1.0)));
391         }
392
393         if (v <= td->o.rwmix[DDIR_READ])
394                 return DDIR_READ;
395
396         return DDIR_WRITE;
397 }
398
399 static enum fio_ddir rate_ddir(struct thread_data *td, enum fio_ddir ddir)
400 {
401         enum fio_ddir odir = ddir ^ 1;
402         struct timeval t;
403         long usec;
404
405         assert(ddir_rw(ddir));
406
407         if (td->rate_pending_usleep[ddir] <= 0)
408                 return ddir;
409
410         /*
411          * We have too much pending sleep in this direction. See if we
412          * should switch.
413          */
414         if (td_rw(td)) {
415                 /*
416                  * Other direction does not have too much pending, switch
417                  */
418                 if (td->rate_pending_usleep[odir] < 100000)
419                         return odir;
420
421                 /*
422                  * Both directions have pending sleep. Sleep the minimum time
423                  * and deduct from both.
424                  */
425                 if (td->rate_pending_usleep[ddir] <=
426                         td->rate_pending_usleep[odir]) {
427                         usec = td->rate_pending_usleep[ddir];
428                 } else {
429                         usec = td->rate_pending_usleep[odir];
430                         ddir = odir;
431                 }
432         } else
433                 usec = td->rate_pending_usleep[ddir];
434
435         /*
436          * We are going to sleep, ensure that we flush anything pending as
437          * not to skew our latency numbers.
438          *
439          * Changed to only monitor 'in flight' requests here instead of the
440          * td->cur_depth, b/c td->cur_depth does not accurately represent
441          * io's that have been actually submitted to an async engine,
442          * and cur_depth is meaningless for sync engines.
443          */
444         if (td->io_u_in_flight) {
445                 int fio_unused ret;
446
447                 ret = io_u_queued_complete(td, td->io_u_in_flight, NULL);
448         }
449
450         fio_gettime(&t, NULL);
451         usec_sleep(td, usec);
452         usec = utime_since_now(&t);
453
454         td->rate_pending_usleep[ddir] -= usec;
455
456         odir = ddir ^ 1;
457         if (td_rw(td) && __should_check_rate(td, odir))
458                 td->rate_pending_usleep[odir] -= usec;
459
460         if (ddir_trim(ddir))
461                 return ddir;
462         return ddir;
463 }
464
465 /*
466  * Return the data direction for the next io_u. If the job is a
467  * mixed read/write workload, check the rwmix cycle and switch if
468  * necessary.
469  */
470 static enum fio_ddir get_rw_ddir(struct thread_data *td)
471 {
472         enum fio_ddir ddir;
473
474         /*
475          * see if it's time to fsync
476          */
477         if (td->o.fsync_blocks &&
478            !(td->io_issues[DDIR_WRITE] % td->o.fsync_blocks) &&
479              td->io_issues[DDIR_WRITE] && should_fsync(td))
480                 return DDIR_SYNC;
481
482         /*
483          * see if it's time to fdatasync
484          */
485         if (td->o.fdatasync_blocks &&
486            !(td->io_issues[DDIR_WRITE] % td->o.fdatasync_blocks) &&
487              td->io_issues[DDIR_WRITE] && should_fsync(td))
488                 return DDIR_DATASYNC;
489
490         /*
491          * see if it's time to sync_file_range
492          */
493         if (td->sync_file_range_nr &&
494            !(td->io_issues[DDIR_WRITE] % td->sync_file_range_nr) &&
495              td->io_issues[DDIR_WRITE] && should_fsync(td))
496                 return DDIR_SYNC_FILE_RANGE;
497
498         if (td_rw(td)) {
499                 /*
500                  * Check if it's time to seed a new data direction.
501                  */
502                 if (td->io_issues[td->rwmix_ddir] >= td->rwmix_issues) {
503                         /*
504                          * Put a top limit on how many bytes we do for
505                          * one data direction, to avoid overflowing the
506                          * ranges too much
507                          */
508                         ddir = get_rand_ddir(td);
509
510                         if (ddir != td->rwmix_ddir)
511                                 set_rwmix_bytes(td);
512
513                         td->rwmix_ddir = ddir;
514                 }
515                 ddir = td->rwmix_ddir;
516         } else if (td_read(td))
517                 ddir = DDIR_READ;
518         else if (td_write(td))
519                 ddir = DDIR_WRITE;
520         else
521                 ddir = DDIR_TRIM;
522
523         td->rwmix_ddir = rate_ddir(td, ddir);
524         return td->rwmix_ddir;
525 }
526
527 static void set_rw_ddir(struct thread_data *td, struct io_u *io_u)
528 {
529         io_u->ddir = get_rw_ddir(td);
530
531         if (io_u->ddir == DDIR_WRITE && (td->io_ops->flags & FIO_BARRIER) &&
532             td->o.barrier_blocks &&
533            !(td->io_issues[DDIR_WRITE] % td->o.barrier_blocks) &&
534              td->io_issues[DDIR_WRITE])
535                 io_u->flags |= IO_U_F_BARRIER;
536 }
537
538 void put_file_log(struct thread_data *td, struct fio_file *f)
539 {
540         int ret = put_file(td, f);
541
542         if (ret)
543                 td_verror(td, ret, "file close");
544 }
545
546 void put_io_u(struct thread_data *td, struct io_u *io_u)
547 {
548         td_io_u_lock(td);
549
550         if (io_u->file && !(io_u->flags & IO_U_F_FREE_DEF))
551                 put_file_log(td, io_u->file);
552         io_u->file = NULL;
553         io_u->flags &= ~IO_U_F_FREE_DEF;
554         io_u->flags |= IO_U_F_FREE;
555
556         if (io_u->flags & IO_U_F_IN_CUR_DEPTH)
557                 td->cur_depth--;
558         flist_del_init(&io_u->list);
559         flist_add(&io_u->list, &td->io_u_freelist);
560         td_io_u_unlock(td);
561         td_io_u_free_notify(td);
562 }
563
564 void clear_io_u(struct thread_data *td, struct io_u *io_u)
565 {
566         io_u->flags &= ~IO_U_F_FLIGHT;
567         put_io_u(td, io_u);
568 }
569
570 void requeue_io_u(struct thread_data *td, struct io_u **io_u)
571 {
572         struct io_u *__io_u = *io_u;
573
574         dprint(FD_IO, "requeue %p\n", __io_u);
575
576         td_io_u_lock(td);
577
578         __io_u->flags |= IO_U_F_FREE;
579         if ((__io_u->flags & IO_U_F_FLIGHT) && ddir_rw(__io_u->ddir))
580                 td->io_issues[__io_u->ddir]--;
581
582         __io_u->flags &= ~IO_U_F_FLIGHT;
583         if (__io_u->flags & IO_U_F_IN_CUR_DEPTH)
584                 td->cur_depth--;
585         flist_del(&__io_u->list);
586         flist_add_tail(&__io_u->list, &td->io_u_requeues);
587         td_io_u_unlock(td);
588         *io_u = NULL;
589 }
590
591 static int fill_io_u(struct thread_data *td, struct io_u *io_u)
592 {
593         if (td->io_ops->flags & FIO_NOIO)
594                 goto out;
595
596         set_rw_ddir(td, io_u);
597
598         /*
599          * fsync() or fdatasync() or trim etc, we are done
600          */
601         if (!ddir_rw(io_u->ddir))
602                 goto out;
603
604         /*
605          * See if it's time to switch to a new zone
606          */
607         if (td->zone_bytes >= td->o.zone_size && td->o.zone_skip) {
608                 td->zone_bytes = 0;
609                 io_u->file->file_offset += td->o.zone_range + td->o.zone_skip;
610                 io_u->file->last_pos = io_u->file->file_offset;
611                 td->io_skip_bytes += td->o.zone_skip;
612         }
613
614         /*
615          * No log, let the seq/rand engine retrieve the next buflen and
616          * position.
617          */
618         if (get_next_offset(td, io_u)) {
619                 dprint(FD_IO, "io_u %p, failed getting offset\n", io_u);
620                 return 1;
621         }
622
623         io_u->buflen = get_next_buflen(td, io_u);
624         if (!io_u->buflen) {
625                 dprint(FD_IO, "io_u %p, failed getting buflen\n", io_u);
626                 return 1;
627         }
628
629         if (io_u->offset + io_u->buflen > io_u->file->real_file_size) {
630                 dprint(FD_IO, "io_u %p, offset too large\n", io_u);
631                 dprint(FD_IO, "  off=%llu/%lu > %llu\n", io_u->offset,
632                                 io_u->buflen, io_u->file->real_file_size);
633                 return 1;
634         }
635
636         /*
637          * mark entry before potentially trimming io_u
638          */
639         if (td_random(td) && file_randommap(td, io_u->file))
640                 mark_random_map(td, io_u);
641
642         /*
643          * If using a write iolog, store this entry.
644          */
645 out:
646         dprint_io_u(io_u, "fill_io_u");
647         td->zone_bytes += io_u->buflen;
648         log_io_u(td, io_u);
649         return 0;
650 }
651
652 static void __io_u_mark_map(unsigned int *map, unsigned int nr)
653 {
654         int idx = 0;
655
656         switch (nr) {
657         default:
658                 idx = 6;
659                 break;
660         case 33 ... 64:
661                 idx = 5;
662                 break;
663         case 17 ... 32:
664                 idx = 4;
665                 break;
666         case 9 ... 16:
667                 idx = 3;
668                 break;
669         case 5 ... 8:
670                 idx = 2;
671                 break;
672         case 1 ... 4:
673                 idx = 1;
674         case 0:
675                 break;
676         }
677
678         map[idx]++;
679 }
680
681 void io_u_mark_submit(struct thread_data *td, unsigned int nr)
682 {
683         __io_u_mark_map(td->ts.io_u_submit, nr);
684         td->ts.total_submit++;
685 }
686
687 void io_u_mark_complete(struct thread_data *td, unsigned int nr)
688 {
689         __io_u_mark_map(td->ts.io_u_complete, nr);
690         td->ts.total_complete++;
691 }
692
693 void io_u_mark_depth(struct thread_data *td, unsigned int nr)
694 {
695         int idx = 0;
696
697         switch (td->cur_depth) {
698         default:
699                 idx = 6;
700                 break;
701         case 32 ... 63:
702                 idx = 5;
703                 break;
704         case 16 ... 31:
705                 idx = 4;
706                 break;
707         case 8 ... 15:
708                 idx = 3;
709                 break;
710         case 4 ... 7:
711                 idx = 2;
712                 break;
713         case 2 ... 3:
714                 idx = 1;
715         case 1:
716                 break;
717         }
718
719         td->ts.io_u_map[idx] += nr;
720 }
721
722 static void io_u_mark_lat_usec(struct thread_data *td, unsigned long usec)
723 {
724         int idx = 0;
725
726         assert(usec < 1000);
727
728         switch (usec) {
729         case 750 ... 999:
730                 idx = 9;
731                 break;
732         case 500 ... 749:
733                 idx = 8;
734                 break;
735         case 250 ... 499:
736                 idx = 7;
737                 break;
738         case 100 ... 249:
739                 idx = 6;
740                 break;
741         case 50 ... 99:
742                 idx = 5;
743                 break;
744         case 20 ... 49:
745                 idx = 4;
746                 break;
747         case 10 ... 19:
748                 idx = 3;
749                 break;
750         case 4 ... 9:
751                 idx = 2;
752                 break;
753         case 2 ... 3:
754                 idx = 1;
755         case 0 ... 1:
756                 break;
757         }
758
759         assert(idx < FIO_IO_U_LAT_U_NR);
760         td->ts.io_u_lat_u[idx]++;
761 }
762
763 static void io_u_mark_lat_msec(struct thread_data *td, unsigned long msec)
764 {
765         int idx = 0;
766
767         switch (msec) {
768         default:
769                 idx = 11;
770                 break;
771         case 1000 ... 1999:
772                 idx = 10;
773                 break;
774         case 750 ... 999:
775                 idx = 9;
776                 break;
777         case 500 ... 749:
778                 idx = 8;
779                 break;
780         case 250 ... 499:
781                 idx = 7;
782                 break;
783         case 100 ... 249:
784                 idx = 6;
785                 break;
786         case 50 ... 99:
787                 idx = 5;
788                 break;
789         case 20 ... 49:
790                 idx = 4;
791                 break;
792         case 10 ... 19:
793                 idx = 3;
794                 break;
795         case 4 ... 9:
796                 idx = 2;
797                 break;
798         case 2 ... 3:
799                 idx = 1;
800         case 0 ... 1:
801                 break;
802         }
803
804         assert(idx < FIO_IO_U_LAT_M_NR);
805         td->ts.io_u_lat_m[idx]++;
806 }
807
808 static void io_u_mark_latency(struct thread_data *td, unsigned long usec)
809 {
810         if (usec < 1000)
811                 io_u_mark_lat_usec(td, usec);
812         else
813                 io_u_mark_lat_msec(td, usec / 1000);
814 }
815
816 /*
817  * Get next file to service by choosing one at random
818  */
819 static struct fio_file *get_next_file_rand(struct thread_data *td,
820                                            enum fio_file_flags goodf,
821                                            enum fio_file_flags badf)
822 {
823         struct fio_file *f;
824         int fno;
825
826         do {
827                 int opened = 0;
828                 unsigned long r;
829
830                 if (td->o.use_os_rand) {
831                         r = os_random_long(&td->next_file_state);
832                         fno = (unsigned int) ((double) td->o.nr_files
833                                 * (r / (OS_RAND_MAX + 1.0)));
834                 } else {
835                         r = __rand(&td->__next_file_state);
836                         fno = (unsigned int) ((double) td->o.nr_files
837                                 * (r / (FRAND_MAX + 1.0)));
838                 }
839
840                 f = td->files[fno];
841                 if (fio_file_done(f))
842                         continue;
843
844                 if (!fio_file_open(f)) {
845                         int err;
846
847                         err = td_io_open_file(td, f);
848                         if (err)
849                                 continue;
850                         opened = 1;
851                 }
852
853                 if ((!goodf || (f->flags & goodf)) && !(f->flags & badf)) {
854                         dprint(FD_FILE, "get_next_file_rand: %p\n", f);
855                         return f;
856                 }
857                 if (opened)
858                         td_io_close_file(td, f);
859         } while (1);
860 }
861
862 /*
863  * Get next file to service by doing round robin between all available ones
864  */
865 static struct fio_file *get_next_file_rr(struct thread_data *td, int goodf,
866                                          int badf)
867 {
868         unsigned int old_next_file = td->next_file;
869         struct fio_file *f;
870
871         do {
872                 int opened = 0;
873
874                 f = td->files[td->next_file];
875
876                 td->next_file++;
877                 if (td->next_file >= td->o.nr_files)
878                         td->next_file = 0;
879
880                 dprint(FD_FILE, "trying file %s %x\n", f->file_name, f->flags);
881                 if (fio_file_done(f)) {
882                         f = NULL;
883                         continue;
884                 }
885
886                 if (!fio_file_open(f)) {
887                         int err;
888
889                         err = td_io_open_file(td, f);
890                         if (err) {
891                                 dprint(FD_FILE, "error %d on open of %s\n",
892                                         err, f->file_name);
893                                 f = NULL;
894                                 continue;
895                         }
896                         opened = 1;
897                 }
898
899                 dprint(FD_FILE, "goodf=%x, badf=%x, ff=%x\n", goodf, badf,
900                                                                 f->flags);
901                 if ((!goodf || (f->flags & goodf)) && !(f->flags & badf))
902                         break;
903
904                 if (opened)
905                         td_io_close_file(td, f);
906
907                 f = NULL;
908         } while (td->next_file != old_next_file);
909
910         dprint(FD_FILE, "get_next_file_rr: %p\n", f);
911         return f;
912 }
913
914 static struct fio_file *__get_next_file(struct thread_data *td)
915 {
916         struct fio_file *f;
917
918         assert(td->o.nr_files <= td->files_index);
919
920         if (td->nr_done_files >= td->o.nr_files) {
921                 dprint(FD_FILE, "get_next_file: nr_open=%d, nr_done=%d,"
922                                 " nr_files=%d\n", td->nr_open_files,
923                                                   td->nr_done_files,
924                                                   td->o.nr_files);
925                 return NULL;
926         }
927
928         f = td->file_service_file;
929         if (f && fio_file_open(f) && !fio_file_closing(f)) {
930                 if (td->o.file_service_type == FIO_FSERVICE_SEQ)
931                         goto out;
932                 if (td->file_service_left--)
933                         goto out;
934         }
935
936         if (td->o.file_service_type == FIO_FSERVICE_RR ||
937             td->o.file_service_type == FIO_FSERVICE_SEQ)
938                 f = get_next_file_rr(td, FIO_FILE_open, FIO_FILE_closing);
939         else
940                 f = get_next_file_rand(td, FIO_FILE_open, FIO_FILE_closing);
941
942         td->file_service_file = f;
943         td->file_service_left = td->file_service_nr - 1;
944 out:
945         dprint(FD_FILE, "get_next_file: %p [%s]\n", f, f->file_name);
946         return f;
947 }
948
949 static struct fio_file *get_next_file(struct thread_data *td)
950 {
951         struct prof_io_ops *ops = &td->prof_io_ops;
952
953         if (ops->get_next_file)
954                 return ops->get_next_file(td);
955
956         return __get_next_file(td);
957 }
958
959 static int set_io_u_file(struct thread_data *td, struct io_u *io_u)
960 {
961         struct fio_file *f;
962
963         do {
964                 f = get_next_file(td);
965                 if (!f)
966                         return 1;
967
968                 io_u->file = f;
969                 get_file(f);
970
971                 if (!fill_io_u(td, io_u))
972                         break;
973
974                 put_file_log(td, f);
975                 td_io_close_file(td, f);
976                 io_u->file = NULL;
977                 fio_file_set_done(f);
978                 td->nr_done_files++;
979                 dprint(FD_FILE, "%s: is done (%d of %d)\n", f->file_name,
980                                         td->nr_done_files, td->o.nr_files);
981         } while (1);
982
983         return 0;
984 }
985
986
987 struct io_u *__get_io_u(struct thread_data *td)
988 {
989         struct io_u *io_u = NULL;
990
991         td_io_u_lock(td);
992
993 again:
994         if (!flist_empty(&td->io_u_requeues))
995                 io_u = flist_entry(td->io_u_requeues.next, struct io_u, list);
996         else if (!queue_full(td)) {
997                 io_u = flist_entry(td->io_u_freelist.next, struct io_u, list);
998
999                 io_u->buflen = 0;
1000                 io_u->resid = 0;
1001                 io_u->file = NULL;
1002                 io_u->end_io = NULL;
1003         }
1004
1005         if (io_u) {
1006                 assert(io_u->flags & IO_U_F_FREE);
1007                 io_u->flags &= ~(IO_U_F_FREE | IO_U_F_FREE_DEF);
1008                 io_u->flags &= ~(IO_U_F_TRIMMED | IO_U_F_BARRIER);
1009                 io_u->flags &= ~IO_U_F_VER_LIST;
1010
1011                 io_u->error = 0;
1012                 flist_del(&io_u->list);
1013                 flist_add_tail(&io_u->list, &td->io_u_busylist);
1014                 td->cur_depth++;
1015                 io_u->flags |= IO_U_F_IN_CUR_DEPTH;
1016         } else if (td->o.verify_async) {
1017                 /*
1018                  * We ran out, wait for async verify threads to finish and
1019                  * return one
1020                  */
1021                 pthread_cond_wait(&td->free_cond, &td->io_u_lock);
1022                 goto again;
1023         }
1024
1025         td_io_u_unlock(td);
1026         return io_u;
1027 }
1028
1029 static int check_get_trim(struct thread_data *td, struct io_u *io_u)
1030 {
1031         if (td->o.trim_backlog && td->trim_entries) {
1032                 int get_trim = 0;
1033
1034                 if (td->trim_batch) {
1035                         td->trim_batch--;
1036                         get_trim = 1;
1037                 } else if (!(td->io_hist_len % td->o.trim_backlog) &&
1038                          td->last_ddir != DDIR_READ) {
1039                         td->trim_batch = td->o.trim_batch;
1040                         if (!td->trim_batch)
1041                                 td->trim_batch = td->o.trim_backlog;
1042                         get_trim = 1;
1043                 }
1044
1045                 if (get_trim && !get_next_trim(td, io_u))
1046                         return 1;
1047         }
1048
1049         return 0;
1050 }
1051
1052 static int check_get_verify(struct thread_data *td, struct io_u *io_u)
1053 {
1054         if (td->o.verify_backlog && td->io_hist_len) {
1055                 int get_verify = 0;
1056
1057                 if (td->verify_batch)
1058                         get_verify = 1;
1059                 else if (!(td->io_hist_len % td->o.verify_backlog) &&
1060                          td->last_ddir != DDIR_READ) {
1061                         td->verify_batch = td->o.verify_batch;
1062                         if (!td->verify_batch)
1063                                 td->verify_batch = td->o.verify_backlog;
1064                         get_verify = 1;
1065                 }
1066
1067                 if (get_verify && !get_next_verify(td, io_u)) {
1068                         td->verify_batch--;
1069                         return 1;
1070                 }
1071         }
1072
1073         return 0;
1074 }
1075
1076 /*
1077  * Fill offset and start time into the buffer content, to prevent too
1078  * easy compressible data for simple de-dupe attempts. Do this for every
1079  * 512b block in the range, since that should be the smallest block size
1080  * we can expect from a device.
1081  */
1082 static void small_content_scramble(struct io_u *io_u)
1083 {
1084         unsigned int i, nr_blocks = io_u->buflen / 512;
1085         unsigned long long boffset;
1086         unsigned int offset;
1087         void *p, *end;
1088
1089         if (!nr_blocks)
1090                 return;
1091
1092         p = io_u->xfer_buf;
1093         boffset = io_u->offset;
1094         io_u->buf_filled_len = 0;
1095
1096         for (i = 0; i < nr_blocks; i++) {
1097                 /*
1098                  * Fill the byte offset into a "random" start offset of
1099                  * the buffer, given by the product of the usec time
1100                  * and the actual offset.
1101                  */
1102                 offset = (io_u->start_time.tv_usec ^ boffset) & 511;
1103                 offset &= ~(sizeof(unsigned long long) - 1);
1104                 if (offset >= 512 - sizeof(unsigned long long))
1105                         offset -= sizeof(unsigned long long);
1106                 memcpy(p + offset, &boffset, sizeof(boffset));
1107
1108                 end = p + 512 - sizeof(io_u->start_time);
1109                 memcpy(end, &io_u->start_time, sizeof(io_u->start_time));
1110                 p += 512;
1111                 boffset += 512;
1112         }
1113 }
1114
1115 /*
1116  * Return an io_u to be processed. Gets a buflen and offset, sets direction,
1117  * etc. The returned io_u is fully ready to be prepped and submitted.
1118  */
1119 struct io_u *get_io_u(struct thread_data *td)
1120 {
1121         struct fio_file *f;
1122         struct io_u *io_u;
1123         int do_scramble = 0;
1124
1125         io_u = __get_io_u(td);
1126         if (!io_u) {
1127                 dprint(FD_IO, "__get_io_u failed\n");
1128                 return NULL;
1129         }
1130
1131         if (check_get_verify(td, io_u))
1132                 goto out;
1133         if (check_get_trim(td, io_u))
1134                 goto out;
1135
1136         /*
1137          * from a requeue, io_u already setup
1138          */
1139         if (io_u->file)
1140                 goto out;
1141
1142         /*
1143          * If using an iolog, grab next piece if any available.
1144          */
1145         if (td->o.read_iolog_file) {
1146                 if (read_iolog_get(td, io_u))
1147                         goto err_put;
1148         } else if (set_io_u_file(td, io_u)) {
1149                 dprint(FD_IO, "io_u %p, setting file failed\n", io_u);
1150                 goto err_put;
1151         }
1152
1153         f = io_u->file;
1154         assert(fio_file_open(f));
1155
1156         if (ddir_rw(io_u->ddir)) {
1157                 if (!io_u->buflen && !(td->io_ops->flags & FIO_NOIO)) {
1158                         dprint(FD_IO, "get_io_u: zero buflen on %p\n", io_u);
1159                         goto err_put;
1160                 }
1161
1162                 f->last_start = io_u->offset;
1163                 f->last_pos = io_u->offset + io_u->buflen;
1164
1165                 if (io_u->ddir == DDIR_WRITE) {
1166                         if (td->o.refill_buffers) {
1167                                 io_u_fill_buffer(td, io_u,
1168                                         io_u->xfer_buflen, io_u->xfer_buflen);
1169                         } else if (td->o.scramble_buffers)
1170                                 do_scramble = 1;
1171                         if (td->o.verify != VERIFY_NONE) {
1172                                 populate_verify_io_u(td, io_u);
1173                                 do_scramble = 0;
1174                         }
1175                 } else if (io_u->ddir == DDIR_READ) {
1176                         /*
1177                          * Reset the buf_filled parameters so next time if the
1178                          * buffer is used for writes it is refilled.
1179                          */
1180                         io_u->buf_filled_len = 0;
1181                 }
1182         }
1183
1184         /*
1185          * Set io data pointers.
1186          */
1187         io_u->xfer_buf = io_u->buf;
1188         io_u->xfer_buflen = io_u->buflen;
1189
1190 out:
1191         assert(io_u->file);
1192         if (!td_io_prep(td, io_u)) {
1193                 if (!td->o.disable_slat)
1194                         fio_gettime(&io_u->start_time, NULL);
1195                 if (do_scramble)
1196                         small_content_scramble(io_u);
1197                 return io_u;
1198         }
1199 err_put:
1200         dprint(FD_IO, "get_io_u failed\n");
1201         put_io_u(td, io_u);
1202         return NULL;
1203 }
1204
1205 void io_u_log_error(struct thread_data *td, struct io_u *io_u)
1206 {
1207         enum error_type_bit eb = td_error_type(io_u->ddir, io_u->error);
1208         const char *msg[] = { "read", "write", "sync", "datasync",
1209                                 "sync_file_range", "wait", "trim" };
1210
1211         if (td_non_fatal_error(td, eb, io_u->error) && !td->o.error_dump)
1212                 return;
1213
1214         log_err("fio: io_u error");
1215
1216         if (io_u->file)
1217                 log_err(" on file %s", io_u->file->file_name);
1218
1219         log_err(": %s\n", strerror(io_u->error));
1220
1221         log_err("     %s offset=%llu, buflen=%lu\n", msg[io_u->ddir],
1222                                         io_u->offset, io_u->xfer_buflen);
1223
1224         if (!td->error)
1225                 td_verror(td, io_u->error, "io_u error");
1226 }
1227
1228 static void account_io_completion(struct thread_data *td, struct io_u *io_u,
1229                                   struct io_completion_data *icd,
1230                                   const enum fio_ddir idx, unsigned int bytes)
1231 {
1232         unsigned long lusec = 0;
1233
1234         if (!td->o.disable_clat || !td->o.disable_bw)
1235                 lusec = utime_since(&io_u->issue_time, &icd->time);
1236
1237         if (!td->o.disable_lat) {
1238                 unsigned long tusec;
1239
1240                 tusec = utime_since(&io_u->start_time, &icd->time);
1241                 add_lat_sample(td, idx, tusec, bytes);
1242
1243                 if (td->o.max_latency && tusec > td->o.max_latency) {
1244                         if (!td->error)
1245                                 log_err("fio: latency of %lu usec exceeds specified max (%u usec)\n", tusec, td->o.max_latency);
1246                         td_verror(td, ETIMEDOUT, "max latency exceeded");
1247                         icd->error = ETIMEDOUT;
1248                 }
1249         }
1250
1251         if (!td->o.disable_clat) {
1252                 add_clat_sample(td, idx, lusec, bytes);
1253                 io_u_mark_latency(td, lusec);
1254         }
1255
1256         if (!td->o.disable_bw)
1257                 add_bw_sample(td, idx, bytes, &icd->time);
1258
1259         add_iops_sample(td, idx, &icd->time);
1260 }
1261
1262 static long long usec_for_io(struct thread_data *td, enum fio_ddir ddir)
1263 {
1264         unsigned long long secs, remainder, bps, bytes;
1265         bytes = td->this_io_bytes[ddir];
1266         bps = td->rate_bps[ddir];
1267         secs = bytes / bps;
1268         remainder = bytes % bps;
1269         return remainder * 1000000 / bps + secs * 1000000;
1270 }
1271
1272 static void io_completed(struct thread_data *td, struct io_u *io_u,
1273                          struct io_completion_data *icd)
1274 {
1275         struct fio_file *f;
1276
1277         dprint_io_u(io_u, "io complete");
1278
1279         td_io_u_lock(td);
1280         assert(io_u->flags & IO_U_F_FLIGHT);
1281         io_u->flags &= ~(IO_U_F_FLIGHT | IO_U_F_BUSY_OK);
1282         td_io_u_unlock(td);
1283
1284         if (ddir_sync(io_u->ddir)) {
1285                 td->last_was_sync = 1;
1286                 f = io_u->file;
1287                 if (f) {
1288                         f->first_write = -1ULL;
1289                         f->last_write = -1ULL;
1290                 }
1291                 return;
1292         }
1293
1294         td->last_was_sync = 0;
1295         td->last_ddir = io_u->ddir;
1296
1297         if (!io_u->error && ddir_rw(io_u->ddir)) {
1298                 unsigned int bytes = io_u->buflen - io_u->resid;
1299                 const enum fio_ddir idx = io_u->ddir;
1300                 const enum fio_ddir odx = io_u->ddir ^ 1;
1301                 int ret;
1302
1303                 td->io_blocks[idx]++;
1304                 td->this_io_blocks[idx]++;
1305                 td->io_bytes[idx] += bytes;
1306
1307                 if (!(io_u->flags & IO_U_F_VER_LIST))
1308                         td->this_io_bytes[idx] += bytes;
1309
1310                 if (idx == DDIR_WRITE) {
1311                         f = io_u->file;
1312                         if (f) {
1313                                 if (f->first_write == -1ULL ||
1314                                     io_u->offset < f->first_write)
1315                                         f->first_write = io_u->offset;
1316                                 if (f->last_write == -1ULL ||
1317                                     ((io_u->offset + bytes) > f->last_write))
1318                                         f->last_write = io_u->offset + bytes;
1319                         }
1320                 }
1321
1322                 if (ramp_time_over(td) && (td->runstate == TD_RUNNING ||
1323                                            td->runstate == TD_VERIFYING)) {
1324                         account_io_completion(td, io_u, icd, idx, bytes);
1325
1326                         if (__should_check_rate(td, idx)) {
1327                                 td->rate_pending_usleep[idx] =
1328                                         (usec_for_io(td, idx) -
1329                                          utime_since_now(&td->start));
1330                         }
1331                         if (idx != DDIR_TRIM && __should_check_rate(td, odx))
1332                                 td->rate_pending_usleep[odx] =
1333                                         (usec_for_io(td, odx) -
1334                                          utime_since_now(&td->start));
1335                 }
1336
1337                 if (td_write(td) && idx == DDIR_WRITE &&
1338                     td->o.do_verify &&
1339                     td->o.verify != VERIFY_NONE)
1340                         log_io_piece(td, io_u);
1341
1342                 icd->bytes_done[idx] += bytes;
1343
1344                 if (io_u->end_io) {
1345                         ret = io_u->end_io(td, io_u);
1346                         if (ret && !icd->error)
1347                                 icd->error = ret;
1348                 }
1349         } else if (io_u->error) {
1350                 icd->error = io_u->error;
1351                 io_u_log_error(td, io_u);
1352         }
1353         if (icd->error) {
1354                 enum error_type_bit eb = td_error_type(io_u->ddir, icd->error);
1355                 if (!td_non_fatal_error(td, eb, icd->error))
1356                         return;
1357                 /*
1358                  * If there is a non_fatal error, then add to the error count
1359                  * and clear all the errors.
1360                  */
1361                 update_error_count(td, icd->error);
1362                 td_clear_error(td);
1363                 icd->error = 0;
1364                 io_u->error = 0;
1365         }
1366 }
1367
1368 static void init_icd(struct thread_data *td, struct io_completion_data *icd,
1369                      int nr)
1370 {
1371         int ddir;
1372         if (!td->o.disable_clat || !td->o.disable_bw)
1373                 fio_gettime(&icd->time, NULL);
1374
1375         icd->nr = nr;
1376
1377         icd->error = 0;
1378         for (ddir = DDIR_READ; ddir < DDIR_RWDIR_CNT; ddir++)
1379                 icd->bytes_done[ddir] = 0;
1380 }
1381
1382 static void ios_completed(struct thread_data *td,
1383                           struct io_completion_data *icd)
1384 {
1385         struct io_u *io_u;
1386         int i;
1387
1388         for (i = 0; i < icd->nr; i++) {
1389                 io_u = td->io_ops->event(td, i);
1390
1391                 io_completed(td, io_u, icd);
1392
1393                 if (!(io_u->flags & IO_U_F_FREE_DEF))
1394                         put_io_u(td, io_u);
1395         }
1396 }
1397
1398 /*
1399  * Complete a single io_u for the sync engines.
1400  */
1401 int io_u_sync_complete(struct thread_data *td, struct io_u *io_u,
1402                        unsigned long *bytes)
1403 {
1404         struct io_completion_data icd;
1405
1406         init_icd(td, &icd, 1);
1407         io_completed(td, io_u, &icd);
1408
1409         if (!(io_u->flags & IO_U_F_FREE_DEF))
1410                 put_io_u(td, io_u);
1411
1412         if (icd.error) {
1413                 td_verror(td, icd.error, "io_u_sync_complete");
1414                 return -1;
1415         }
1416
1417         if (bytes) {
1418                 int ddir;
1419
1420                 for (ddir = DDIR_READ; ddir < DDIR_RWDIR_CNT; ddir++)
1421                         bytes[ddir] += icd.bytes_done[ddir];
1422         }
1423
1424         return 0;
1425 }
1426
1427 /*
1428  * Called to complete min_events number of io for the async engines.
1429  */
1430 int io_u_queued_complete(struct thread_data *td, int min_evts,
1431                          unsigned long *bytes)
1432 {
1433         struct io_completion_data icd;
1434         struct timespec *tvp = NULL;
1435         int ret;
1436         struct timespec ts = { .tv_sec = 0, .tv_nsec = 0, };
1437
1438         dprint(FD_IO, "io_u_queued_completed: min=%d\n", min_evts);
1439
1440         if (!min_evts)
1441                 tvp = &ts;
1442
1443         ret = td_io_getevents(td, min_evts, td->o.iodepth_batch_complete, tvp);
1444         if (ret < 0) {
1445                 td_verror(td, -ret, "td_io_getevents");
1446                 return ret;
1447         } else if (!ret)
1448                 return ret;
1449
1450         init_icd(td, &icd, ret);
1451         ios_completed(td, &icd);
1452         if (icd.error) {
1453                 td_verror(td, icd.error, "io_u_queued_complete");
1454                 return -1;
1455         }
1456
1457         if (bytes) {
1458                 int ddir;
1459
1460                 for (ddir = DDIR_READ; ddir < DDIR_RWDIR_CNT; ddir++)
1461                         bytes[ddir] += icd.bytes_done[ddir];
1462         }
1463
1464         return 0;
1465 }
1466
1467 /*
1468  * Call when io_u is really queued, to update the submission latency.
1469  */
1470 void io_u_queued(struct thread_data *td, struct io_u *io_u)
1471 {
1472         if (!td->o.disable_slat) {
1473                 unsigned long slat_time;
1474
1475                 slat_time = utime_since(&io_u->start_time, &io_u->issue_time);
1476                 add_slat_sample(td, io_u->ddir, slat_time, io_u->xfer_buflen);
1477         }
1478 }
1479
1480 /*
1481  * "randomly" fill the buffer contents
1482  */
1483 void io_u_fill_buffer(struct thread_data *td, struct io_u *io_u,
1484                       unsigned int min_write, unsigned int max_bs)
1485 {
1486         io_u->buf_filled_len = 0;
1487
1488         if (!td->o.zero_buffers) {
1489                 unsigned int perc = td->o.compress_percentage;
1490
1491                 if (perc) {
1492                         unsigned int seg = min_write;
1493
1494                         seg = min(min_write, td->o.compress_chunk);
1495                         fill_random_buf_percentage(&td->buf_state, io_u->buf,
1496                                                 perc, seg, max_bs);
1497                 } else
1498                         fill_random_buf(&td->buf_state, io_u->buf, max_bs);
1499         } else
1500                 memset(io_u->buf, 0, max_bs);
1501 }