t/io_uring: avoid truncation of offset on 32-bit builds
[fio.git] / t / io_uring.c
1 #include <stdio.h>
2 #include <errno.h>
3 #include <assert.h>
4 #include <stdlib.h>
5 #include <stddef.h>
6 #include <signal.h>
7 #include <inttypes.h>
8 #include <math.h>
9
10 #ifdef CONFIG_LIBAIO
11 #include <libaio.h>
12 #endif
13
14 #ifdef CONFIG_LIBNUMA
15 #include <numa.h>
16 #endif
17
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <sys/ioctl.h>
21 #include <sys/syscall.h>
22 #include <sys/resource.h>
23 #include <sys/mman.h>
24 #include <sys/uio.h>
25 #include <linux/fs.h>
26 #include <fcntl.h>
27 #include <unistd.h>
28 #include <string.h>
29 #include <pthread.h>
30 #include <sched.h>
31
32 #include "../arch/arch.h"
33 #include "../os/os.h"
34 #include "../lib/types.h"
35 #include "../lib/roundup.h"
36 #include "../lib/rand.h"
37 #include "../minmax.h"
38 #include "../os/linux/io_uring.h"
39 #include "../engines/nvme.h"
40
41 struct io_sq_ring {
42         unsigned *head;
43         unsigned *tail;
44         unsigned *ring_mask;
45         unsigned *ring_entries;
46         unsigned *flags;
47         unsigned *array;
48 };
49
50 struct io_cq_ring {
51         unsigned *head;
52         unsigned *tail;
53         unsigned *ring_mask;
54         unsigned *ring_entries;
55         struct io_uring_cqe *cqes;
56 };
57
58 #define DEPTH                   128
59 #define BATCH_SUBMIT            32
60 #define BATCH_COMPLETE          32
61 #define BS                      4096
62
63 #define MAX_FDS                 16
64
65 static unsigned sq_ring_mask, cq_ring_mask;
66
67 struct file {
68         unsigned long max_blocks;
69         unsigned long max_size;
70         unsigned long cur_off;
71         unsigned pending_ios;
72         unsigned int nsid;      /* nsid field required for nvme-passthrough */
73         unsigned int lba_shift; /* lba_shift field required for nvme-passthrough */
74         int real_fd;
75         int fixed_fd;
76         int fileno;
77 };
78
79 #define PLAT_BITS               6
80 #define PLAT_VAL                (1 << PLAT_BITS)
81 #define PLAT_GROUP_NR           29
82 #define PLAT_NR                 (PLAT_GROUP_NR * PLAT_VAL)
83
84 struct submitter {
85         pthread_t thread;
86         int ring_fd;
87         int enter_ring_fd;
88         int index;
89         struct io_sq_ring sq_ring;
90         struct io_uring_sqe *sqes;
91         struct io_cq_ring cq_ring;
92         int inflight;
93         int tid;
94         unsigned long reaps;
95         unsigned long done;
96         unsigned long calls;
97         volatile int finish;
98
99         __s32 *fds;
100
101         struct taus258_state rand_state;
102
103         unsigned long *clock_batch;
104         int clock_index;
105         unsigned long *plat;
106
107 #ifdef CONFIG_LIBAIO
108         io_context_t aio_ctx;
109 #endif
110
111         int numa_node;
112         const char *filename;
113
114         struct file files[MAX_FDS];
115         unsigned nr_files;
116         unsigned cur_file;
117         struct iovec iovecs[];
118 };
119
120 static struct submitter *submitter;
121 static volatile int finish;
122 static int stats_running;
123 static unsigned long max_iops;
124 static long t_io_uring_page_size;
125
126 static int depth = DEPTH;
127 static int batch_submit = BATCH_SUBMIT;
128 static int batch_complete = BATCH_COMPLETE;
129 static int bs = BS;
130 static int polled = 1;          /* use IO polling */
131 static int fixedbufs = 1;       /* use fixed user buffers */
132 static int dma_map;             /* pre-map DMA buffers */
133 static int register_files = 1;  /* use fixed files */
134 static int buffered = 0;        /* use buffered IO, not O_DIRECT */
135 static int sq_thread_poll = 0;  /* use kernel submission/poller thread */
136 static int sq_thread_cpu = -1;  /* pin above thread to this CPU */
137 static int do_nop = 0;          /* no-op SQ ring commands */
138 static int nthreads = 1;
139 static int stats = 0;           /* generate IO stats */
140 static int aio = 0;             /* use libaio */
141 static int runtime = 0;         /* runtime */
142 static int random_io = 1;       /* random or sequential IO */
143 static int register_ring = 1;   /* register ring */
144 static int use_sync = 0;        /* use preadv2 */
145 static int numa_placement = 0;  /* set to node of device */
146 static int pt = 0;              /* passthrough I/O or not */
147
148 static unsigned long tsc_rate;
149
150 #define TSC_RATE_FILE   "tsc-rate"
151
152 static int vectored = 1;
153
154 static float plist[] = { 1.0, 5.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0,
155                         80.0, 90.0, 95.0, 99.0, 99.5, 99.9, 99.95, 99.99 };
156 static int plist_len = 17;
157
158 #ifndef IORING_REGISTER_MAP_BUFFERS
159 #define IORING_REGISTER_MAP_BUFFERS     26
160 struct io_uring_map_buffers {
161         __s32   fd;
162         __u32   buf_start;
163         __u32   buf_end;
164         __u32   flags;
165         __u64   rsvd[2];
166 };
167 #endif
168
169 static int nvme_identify(int fd, __u32 nsid, enum nvme_identify_cns cns,
170                          enum nvme_csi csi, void *data)
171 {
172         struct nvme_passthru_cmd cmd = {
173                 .opcode         = nvme_admin_identify,
174                 .nsid           = nsid,
175                 .addr           = (__u64)(uintptr_t)data,
176                 .data_len       = NVME_IDENTIFY_DATA_SIZE,
177                 .cdw10          = cns,
178                 .cdw11          = csi << NVME_IDENTIFY_CSI_SHIFT,
179                 .timeout_ms     = NVME_DEFAULT_IOCTL_TIMEOUT,
180         };
181
182         return ioctl(fd, NVME_IOCTL_ADMIN_CMD, &cmd);
183 }
184
185 static int nvme_get_info(int fd, __u32 *nsid, __u32 *lba_sz, __u64 *nlba)
186 {
187         struct nvme_id_ns ns;
188         int namespace_id;
189         int err;
190
191         namespace_id = ioctl(fd, NVME_IOCTL_ID);
192         if (namespace_id < 0) {
193                 fprintf(stderr, "error failed to fetch namespace-id\n");
194                 close(fd);
195                 return -errno;
196         }
197
198         /*
199          * Identify namespace to get namespace-id, namespace size in LBA's
200          * and LBA data size.
201          */
202         err = nvme_identify(fd, namespace_id, NVME_IDENTIFY_CNS_NS,
203                                 NVME_CSI_NVM, &ns);
204         if (err) {
205                 fprintf(stderr, "error failed to fetch identify namespace\n");
206                 close(fd);
207                 return err;
208         }
209
210         *nsid = namespace_id;
211         *lba_sz = 1 << ns.lbaf[(ns.flbas & 0x0f)].ds;
212         *nlba = ns.nsze;
213
214         return 0;
215 }
216
217 static unsigned long cycles_to_nsec(unsigned long cycles)
218 {
219         uint64_t val;
220
221         if (!tsc_rate)
222                 return cycles;
223
224         val = cycles * 1000000000ULL;
225         return val / tsc_rate;
226 }
227
228 static unsigned long plat_idx_to_val(unsigned int idx)
229 {
230         unsigned int error_bits;
231         unsigned long k, base;
232
233         assert(idx < PLAT_NR);
234
235         /* MSB <= (PLAT_BITS-1), cannot be rounded off. Use
236          * all bits of the sample as index */
237         if (idx < (PLAT_VAL << 1))
238                 return cycles_to_nsec(idx);
239
240         /* Find the group and compute the minimum value of that group */
241         error_bits = (idx >> PLAT_BITS) - 1;
242         base = ((unsigned long) 1) << (error_bits + PLAT_BITS);
243
244         /* Find its bucket number of the group */
245         k = idx % PLAT_VAL;
246
247         /* Return the mean of the range of the bucket */
248         return cycles_to_nsec(base + ((k + 0.5) * (1 << error_bits)));
249 }
250
251 unsigned int calculate_clat_percentiles(unsigned long *io_u_plat,
252                 unsigned long nr, unsigned long **output,
253                 unsigned long *maxv, unsigned long *minv)
254 {
255         unsigned long sum = 0;
256         unsigned int len = plist_len, i, j = 0;
257         unsigned long *ovals = NULL;
258         bool is_last;
259
260         *minv = -1UL;
261         *maxv = 0;
262
263         ovals = malloc(len * sizeof(*ovals));
264         if (!ovals)
265                 return 0;
266
267         /*
268          * Calculate bucket values, note down max and min values
269          */
270         is_last = false;
271         for (i = 0; i < PLAT_NR && !is_last; i++) {
272                 sum += io_u_plat[i];
273                 while (sum >= ((long double) plist[j] / 100.0 * nr)) {
274                         assert(plist[j] <= 100.0);
275
276                         ovals[j] = plat_idx_to_val(i);
277                         if (ovals[j] < *minv)
278                                 *minv = ovals[j];
279                         if (ovals[j] > *maxv)
280                                 *maxv = ovals[j];
281
282                         is_last = (j == len - 1) != 0;
283                         if (is_last)
284                                 break;
285
286                         j++;
287                 }
288         }
289
290         if (!is_last)
291                 fprintf(stderr, "error calculating latency percentiles\n");
292
293         *output = ovals;
294         return len;
295 }
296
297 static void show_clat_percentiles(unsigned long *io_u_plat, unsigned long nr,
298                                   unsigned int precision)
299 {
300         unsigned int divisor, len, i, j = 0;
301         unsigned long minv, maxv;
302         unsigned long *ovals;
303         int per_line, scale_down, time_width;
304         bool is_last;
305         char fmt[32];
306
307         len = calculate_clat_percentiles(io_u_plat, nr, &ovals, &maxv, &minv);
308         if (!len || !ovals)
309                 goto out;
310
311         if (!tsc_rate) {
312                 scale_down = 0;
313                 divisor = 1;
314                 printf("    percentiles (tsc ticks):\n     |");
315         } else if (minv > 2000 && maxv > 99999) {
316                 scale_down = 1;
317                 divisor = 1000;
318                 printf("    percentiles (usec):\n     |");
319         } else {
320                 scale_down = 0;
321                 divisor = 1;
322                 printf("    percentiles (nsec):\n     |");
323         }
324
325         time_width = max(5, (int) (log10(maxv / divisor) + 1));
326         snprintf(fmt, sizeof(fmt), " %%%u.%ufth=[%%%dllu]%%c", precision + 3,
327                         precision, time_width);
328         /* fmt will be something like " %5.2fth=[%4llu]%c" */
329         per_line = (80 - 7) / (precision + 10 + time_width);
330
331         for (j = 0; j < len; j++) {
332                 /* for formatting */
333                 if (j != 0 && (j % per_line) == 0)
334                         printf("     |");
335
336                 /* end of the list */
337                 is_last = (j == len - 1) != 0;
338
339                 for (i = 0; i < scale_down; i++)
340                         ovals[j] = (ovals[j] + 999) / 1000;
341
342                 printf(fmt, plist[j], ovals[j], is_last ? '\n' : ',');
343
344                 if (is_last)
345                         break;
346
347                 if ((j % per_line) == per_line - 1)     /* for formatting */
348                         printf("\n");
349         }
350
351 out:
352         free(ovals);
353 }
354
355 #ifdef ARCH_HAVE_CPU_CLOCK
356 static unsigned int plat_val_to_idx(unsigned long val)
357 {
358         unsigned int msb, error_bits, base, offset, idx;
359
360         /* Find MSB starting from bit 0 */
361         if (val == 0)
362                 msb = 0;
363         else
364                 msb = (sizeof(val)*8) - __builtin_clzll(val) - 1;
365
366         /*
367          * MSB <= (PLAT_BITS-1), cannot be rounded off. Use
368          * all bits of the sample as index
369          */
370         if (msb <= PLAT_BITS)
371                 return val;
372
373         /* Compute the number of error bits to discard*/
374         error_bits = msb - PLAT_BITS;
375
376         /* Compute the number of buckets before the group */
377         base = (error_bits + 1) << PLAT_BITS;
378
379         /*
380          * Discard the error bits and apply the mask to find the
381          * index for the buckets in the group
382          */
383         offset = (PLAT_VAL - 1) & (val >> error_bits);
384
385         /* Make sure the index does not exceed (array size - 1) */
386         idx = (base + offset) < (PLAT_NR - 1) ?
387                 (base + offset) : (PLAT_NR - 1);
388
389         return idx;
390 }
391 #endif
392
393 static void add_stat(struct submitter *s, int clock_index, int nr)
394 {
395 #ifdef ARCH_HAVE_CPU_CLOCK
396         unsigned long cycles;
397         unsigned int pidx;
398
399         if (!s->finish && clock_index) {
400                 cycles = get_cpu_clock();
401                 cycles -= s->clock_batch[clock_index];
402                 pidx = plat_val_to_idx(cycles);
403                 s->plat[pidx] += nr;
404         }
405 #endif
406 }
407
408 static int io_uring_map_buffers(struct submitter *s)
409 {
410         struct io_uring_map_buffers map = {
411                 .fd             = s->files[0].real_fd,
412                 .buf_end        = depth,
413         };
414
415         if (do_nop)
416                 return 0;
417         if (s->nr_files > 1)
418                 fprintf(stdout, "Mapping buffers may not work with multiple files\n");
419
420         return syscall(__NR_io_uring_register, s->ring_fd,
421                         IORING_REGISTER_MAP_BUFFERS, &map, 1);
422 }
423
424 static int io_uring_register_buffers(struct submitter *s)
425 {
426         if (do_nop)
427                 return 0;
428
429         return syscall(__NR_io_uring_register, s->ring_fd,
430                         IORING_REGISTER_BUFFERS, s->iovecs, roundup_pow2(depth));
431 }
432
433 static int io_uring_register_files(struct submitter *s)
434 {
435         int i;
436
437         if (do_nop)
438                 return 0;
439
440         s->fds = calloc(s->nr_files, sizeof(__s32));
441         for (i = 0; i < s->nr_files; i++) {
442                 s->fds[i] = s->files[i].real_fd;
443                 s->files[i].fixed_fd = i;
444         }
445
446         return syscall(__NR_io_uring_register, s->ring_fd,
447                         IORING_REGISTER_FILES, s->fds, s->nr_files);
448 }
449
450 static int io_uring_setup(unsigned entries, struct io_uring_params *p)
451 {
452         int ret;
453
454         /*
455          * Clamp CQ ring size at our SQ ring size, we don't need more entries
456          * than that.
457          */
458         p->flags |= IORING_SETUP_CQSIZE;
459         p->cq_entries = entries;
460
461         p->flags |= IORING_SETUP_COOP_TASKRUN;
462         p->flags |= IORING_SETUP_SINGLE_ISSUER;
463         p->flags |= IORING_SETUP_DEFER_TASKRUN;
464 retry:
465         ret = syscall(__NR_io_uring_setup, entries, p);
466         if (!ret)
467                 return 0;
468
469         if (errno == EINVAL && p->flags & IORING_SETUP_COOP_TASKRUN) {
470                 p->flags &= ~IORING_SETUP_COOP_TASKRUN;
471                 goto retry;
472         }
473         if (errno == EINVAL && p->flags & IORING_SETUP_SINGLE_ISSUER) {
474                 p->flags &= ~IORING_SETUP_SINGLE_ISSUER;
475                 goto retry;
476         }
477         if (errno == EINVAL && p->flags & IORING_SETUP_DEFER_TASKRUN) {
478                 p->flags &= ~IORING_SETUP_DEFER_TASKRUN;
479                 goto retry;
480         }
481
482         return ret;
483 }
484
485 static void io_uring_probe(int fd)
486 {
487         struct io_uring_probe *p;
488         int ret;
489
490         p = malloc(sizeof(*p) + 256 * sizeof(struct io_uring_probe_op));
491         if (!p)
492                 return;
493
494         memset(p, 0, sizeof(*p) + 256 * sizeof(struct io_uring_probe_op));
495         ret = syscall(__NR_io_uring_register, fd, IORING_REGISTER_PROBE, p, 256);
496         if (ret < 0)
497                 goto out;
498
499         if (IORING_OP_READ > p->ops_len)
500                 goto out;
501
502         if ((p->ops[IORING_OP_READ].flags & IO_URING_OP_SUPPORTED))
503                 vectored = 0;
504 out:
505         free(p);
506 }
507
508 static int io_uring_enter(struct submitter *s, unsigned int to_submit,
509                           unsigned int min_complete, unsigned int flags)
510 {
511         if (register_ring)
512                 flags |= IORING_ENTER_REGISTERED_RING;
513 #ifdef FIO_ARCH_HAS_SYSCALL
514         return __do_syscall6(__NR_io_uring_enter, s->enter_ring_fd, to_submit,
515                                 min_complete, flags, NULL, 0);
516 #else
517         return syscall(__NR_io_uring_enter, s->enter_ring_fd, to_submit,
518                         min_complete, flags, NULL, 0);
519 #endif
520 }
521
522 static unsigned file_depth(struct submitter *s)
523 {
524         return (depth + s->nr_files - 1) / s->nr_files;
525 }
526
527 static unsigned long long get_offset(struct submitter *s, struct file *f)
528 {
529         unsigned long long offset;
530         long r;
531
532         if (random_io) {
533                 unsigned long long block;
534
535                 r = __rand64(&s->rand_state);
536                 block = r % f->max_blocks;
537                 offset = block * (unsigned long long) bs;
538         } else {
539                 offset = f->cur_off;
540                 f->cur_off += bs;
541                 if (f->cur_off + bs > f->max_size)
542                         f->cur_off = 0;
543         }
544
545         return offset;
546 }
547
548 static void init_io(struct submitter *s, unsigned index)
549 {
550         struct io_uring_sqe *sqe = &s->sqes[index];
551         struct file *f;
552
553         if (do_nop) {
554                 sqe->opcode = IORING_OP_NOP;
555                 return;
556         }
557
558         if (s->nr_files == 1) {
559                 f = &s->files[0];
560         } else {
561                 f = &s->files[s->cur_file];
562                 if (f->pending_ios >= file_depth(s)) {
563                         s->cur_file++;
564                         if (s->cur_file == s->nr_files)
565                                 s->cur_file = 0;
566                         f = &s->files[s->cur_file];
567                 }
568         }
569         f->pending_ios++;
570
571         if (register_files) {
572                 sqe->flags = IOSQE_FIXED_FILE;
573                 sqe->fd = f->fixed_fd;
574         } else {
575                 sqe->flags = 0;
576                 sqe->fd = f->real_fd;
577         }
578         if (fixedbufs) {
579                 sqe->opcode = IORING_OP_READ_FIXED;
580                 sqe->addr = (unsigned long) s->iovecs[index].iov_base;
581                 sqe->len = bs;
582                 sqe->buf_index = index;
583         } else if (!vectored) {
584                 sqe->opcode = IORING_OP_READ;
585                 sqe->addr = (unsigned long) s->iovecs[index].iov_base;
586                 sqe->len = bs;
587                 sqe->buf_index = 0;
588         } else {
589                 sqe->opcode = IORING_OP_READV;
590                 sqe->addr = (unsigned long) &s->iovecs[index];
591                 sqe->len = 1;
592                 sqe->buf_index = 0;
593         }
594         sqe->ioprio = 0;
595         sqe->off = get_offset(s, f);
596         sqe->user_data = (unsigned long) f->fileno;
597         if (stats && stats_running)
598                 sqe->user_data |= ((uint64_t)s->clock_index << 32);
599 }
600
601 static void init_io_pt(struct submitter *s, unsigned index)
602 {
603         struct io_uring_sqe *sqe = &s->sqes[index << 1];
604         unsigned long offset;
605         struct file *f;
606         struct nvme_uring_cmd *cmd;
607         unsigned long long slba;
608         unsigned long long nlb;
609         long r;
610
611         if (s->nr_files == 1) {
612                 f = &s->files[0];
613         } else {
614                 f = &s->files[s->cur_file];
615                 if (f->pending_ios >= file_depth(s)) {
616                         s->cur_file++;
617                         if (s->cur_file == s->nr_files)
618                                 s->cur_file = 0;
619                         f = &s->files[s->cur_file];
620                 }
621         }
622         f->pending_ios++;
623
624         if (random_io) {
625                 r = __rand64(&s->rand_state);
626                 offset = (r % (f->max_blocks - 1)) * bs;
627         } else {
628                 offset = f->cur_off;
629                 f->cur_off += bs;
630                 if (f->cur_off + bs > f->max_size)
631                         f->cur_off = 0;
632         }
633
634         if (register_files) {
635                 sqe->fd = f->fixed_fd;
636                 sqe->flags = IOSQE_FIXED_FILE;
637         } else {
638                 sqe->fd = f->real_fd;
639                 sqe->flags = 0;
640         }
641         sqe->opcode = IORING_OP_URING_CMD;
642         sqe->user_data = (unsigned long) f->fileno;
643         if (stats)
644                 sqe->user_data |= ((__u64) s->clock_index << 32ULL);
645         sqe->cmd_op = NVME_URING_CMD_IO;
646         slba = offset >> f->lba_shift;
647         nlb = (bs >> f->lba_shift) - 1;
648         cmd = (struct nvme_uring_cmd *)&sqe->cmd;
649         /* cdw10 and cdw11 represent starting slba*/
650         cmd->cdw10 = slba & 0xffffffff;
651         cmd->cdw11 = slba >> 32;
652         /* cdw12 represent number of lba to be read*/
653         cmd->cdw12 = nlb;
654         cmd->addr = (unsigned long) s->iovecs[index].iov_base;
655         cmd->data_len = bs;
656         if (fixedbufs) {
657                 sqe->uring_cmd_flags = IORING_URING_CMD_FIXED;
658                 sqe->buf_index = index;
659         }
660         cmd->nsid = f->nsid;
661         cmd->opcode = 2;
662 }
663
664 static int prep_more_ios_uring(struct submitter *s, int max_ios)
665 {
666         struct io_sq_ring *ring = &s->sq_ring;
667         unsigned head, index, tail, next_tail, prepped = 0;
668
669         if (sq_thread_poll)
670                 head = atomic_load_acquire(ring->head);
671         else
672                 head = *ring->head;
673
674         next_tail = tail = *ring->tail;
675         do {
676                 next_tail++;
677                 if (next_tail == head)
678                         break;
679
680                 index = tail & sq_ring_mask;
681                 if (pt)
682                         init_io_pt(s, index);
683                 else
684                         init_io(s, index);
685                 prepped++;
686                 tail = next_tail;
687         } while (prepped < max_ios);
688
689         if (prepped)
690                 atomic_store_release(ring->tail, tail);
691         return prepped;
692 }
693
694 static int get_file_size(struct file *f)
695 {
696         struct stat st;
697
698         if (fstat(f->real_fd, &st) < 0)
699                 return -1;
700         if (pt) {
701                 __u64 nlba;
702                 __u32 lbs;
703                 int ret;
704
705                 if (!S_ISCHR(st.st_mode)) {
706                         fprintf(stderr, "passthrough works with only nvme-ns "
707                                         "generic devices (/dev/ngXnY)\n");
708                         return -1;
709                 }
710                 ret = nvme_get_info(f->real_fd, &f->nsid, &lbs, &nlba);
711                 if (ret)
712                         return -1;
713                 if ((bs % lbs) != 0) {
714                         printf("error: bs:%d should be a multiple logical_block_size:%d\n",
715                                         bs, lbs);
716                         return -1;
717                 }
718                 f->max_blocks = nlba / bs;
719                 f->max_size = nlba;
720                 f->lba_shift = ilog2(lbs);
721                 return 0;
722         } else if (S_ISBLK(st.st_mode)) {
723                 unsigned long long bytes;
724
725                 if (ioctl(f->real_fd, BLKGETSIZE64, &bytes) != 0)
726                         return -1;
727
728                 f->max_blocks = bytes / bs;
729                 f->max_size = bytes;
730                 return 0;
731         } else if (S_ISREG(st.st_mode)) {
732                 f->max_blocks = st.st_size / bs;
733                 f->max_size = st.st_size;
734                 return 0;
735         }
736
737         return -1;
738 }
739
740 static int reap_events_uring(struct submitter *s)
741 {
742         struct io_cq_ring *ring = &s->cq_ring;
743         struct io_uring_cqe *cqe;
744         unsigned head, reaped = 0;
745         int last_idx = -1, stat_nr = 0;
746
747         head = *ring->head;
748         do {
749                 struct file *f;
750
751                 if (head == atomic_load_acquire(ring->tail))
752                         break;
753                 cqe = &ring->cqes[head & cq_ring_mask];
754                 if (!do_nop) {
755                         int fileno = cqe->user_data & 0xffffffff;
756
757                         f = &s->files[fileno];
758                         f->pending_ios--;
759                         if (cqe->res != bs) {
760                                 printf("io: unexpected ret=%d\n", cqe->res);
761                                 if (polled && cqe->res == -EOPNOTSUPP)
762                                         printf("Your filesystem/driver/kernel doesn't support polled IO\n");
763                                 return -1;
764                         }
765                 }
766                 if (stats) {
767                         int clock_index = cqe->user_data >> 32;
768
769                         if (last_idx != clock_index) {
770                                 if (last_idx != -1) {
771                                         add_stat(s, last_idx, stat_nr);
772                                         stat_nr = 0;
773                                 }
774                                 last_idx = clock_index;
775                         }
776                         stat_nr++;
777                 }
778                 reaped++;
779                 head++;
780         } while (1);
781
782         if (stat_nr)
783                 add_stat(s, last_idx, stat_nr);
784
785         if (reaped) {
786                 s->inflight -= reaped;
787                 atomic_store_release(ring->head, head);
788         }
789         return reaped;
790 }
791
792 static int reap_events_uring_pt(struct submitter *s)
793 {
794         struct io_cq_ring *ring = &s->cq_ring;
795         struct io_uring_cqe *cqe;
796         unsigned head, reaped = 0;
797         int last_idx = -1, stat_nr = 0;
798         unsigned index;
799         int fileno;
800
801         head = *ring->head;
802         do {
803                 struct file *f;
804
805                 if (head == atomic_load_acquire(ring->tail))
806                         break;
807                 index = head & cq_ring_mask;
808                 cqe = &ring->cqes[index << 1];
809                 fileno = cqe->user_data & 0xffffffff;
810                 f = &s->files[fileno];
811                 f->pending_ios--;
812
813                 if (cqe->res != 0) {
814                         printf("io: unexpected ret=%d\n", cqe->res);
815                         if (polled && cqe->res == -EINVAL)
816                                 printf("passthrough doesn't support polled IO\n");
817                         return -1;
818                 }
819                 if (stats) {
820                         int clock_index = cqe->user_data >> 32;
821
822                         if (last_idx != clock_index) {
823                                 if (last_idx != -1) {
824                                         add_stat(s, last_idx, stat_nr);
825                                         stat_nr = 0;
826                                 }
827                                 last_idx = clock_index;
828                         }
829                         stat_nr++;
830                 }
831                 reaped++;
832                 head++;
833         } while (1);
834
835         if (stat_nr)
836                 add_stat(s, last_idx, stat_nr);
837
838         if (reaped) {
839                 s->inflight -= reaped;
840                 atomic_store_release(ring->head, head);
841         }
842         return reaped;
843 }
844
845 static void set_affinity(struct submitter *s)
846 {
847 #ifdef CONFIG_LIBNUMA
848         struct bitmask *mask;
849
850         if (s->numa_node == -1)
851                 return;
852
853         numa_set_preferred(s->numa_node);
854
855         mask = numa_allocate_cpumask();
856         numa_node_to_cpus(s->numa_node, mask);
857         numa_sched_setaffinity(s->tid, mask);
858 #endif
859 }
860
861 static int detect_node(struct submitter *s, const char *name)
862 {
863 #ifdef CONFIG_LIBNUMA
864         const char *base = basename(name);
865         char str[128];
866         int ret, fd, node;
867
868         if (pt)
869                 sprintf(str, "/sys/class/nvme-generic/%s/device/numa_node", base);
870         else
871                 sprintf(str, "/sys/block/%s/device/numa_node", base);
872         fd = open(str, O_RDONLY);
873         if (fd < 0)
874                 return -1;
875
876         ret = read(fd, str, sizeof(str));
877         if (ret < 0) {
878                 close(fd);
879                 return -1;
880         }
881         node = atoi(str);
882         s->numa_node = node;
883         close(fd);
884 #else
885         s->numa_node = -1;
886 #endif
887         return 0;
888 }
889
890 static int setup_aio(struct submitter *s)
891 {
892 #ifdef CONFIG_LIBAIO
893         if (polled) {
894                 fprintf(stderr, "aio does not support polled IO\n");
895                 polled = 0;
896         }
897         if (sq_thread_poll) {
898                 fprintf(stderr, "aio does not support SQPOLL IO\n");
899                 sq_thread_poll = 0;
900         }
901         if (do_nop) {
902                 fprintf(stderr, "aio does not support polled IO\n");
903                 do_nop = 0;
904         }
905         if (fixedbufs || register_files) {
906                 fprintf(stderr, "aio does not support registered files or buffers\n");
907                 fixedbufs = register_files = 0;
908         }
909
910         return io_queue_init(roundup_pow2(depth), &s->aio_ctx);
911 #else
912         fprintf(stderr, "Legacy AIO not available on this system/build\n");
913         errno = EINVAL;
914         return -1;
915 #endif
916 }
917
918 static int setup_ring(struct submitter *s)
919 {
920         struct io_sq_ring *sring = &s->sq_ring;
921         struct io_cq_ring *cring = &s->cq_ring;
922         struct io_uring_params p;
923         int ret, fd, i;
924         void *ptr;
925         size_t len;
926
927         memset(&p, 0, sizeof(p));
928
929         if (polled && !do_nop)
930                 p.flags |= IORING_SETUP_IOPOLL;
931         if (sq_thread_poll) {
932                 p.flags |= IORING_SETUP_SQPOLL;
933                 if (sq_thread_cpu != -1) {
934                         p.flags |= IORING_SETUP_SQ_AFF;
935                         p.sq_thread_cpu = sq_thread_cpu;
936                 }
937         }
938         if (pt) {
939                 p.flags |= IORING_SETUP_SQE128;
940                 p.flags |= IORING_SETUP_CQE32;
941         }
942
943         fd = io_uring_setup(depth, &p);
944         if (fd < 0) {
945                 perror("io_uring_setup");
946                 return 1;
947         }
948         s->ring_fd = s->enter_ring_fd = fd;
949
950         io_uring_probe(fd);
951
952         if (fixedbufs) {
953                 struct rlimit rlim;
954
955                 rlim.rlim_cur = RLIM_INFINITY;
956                 rlim.rlim_max = RLIM_INFINITY;
957                 /* ignore potential error, not needed on newer kernels */
958                 setrlimit(RLIMIT_MEMLOCK, &rlim);
959
960                 ret = io_uring_register_buffers(s);
961                 if (ret < 0) {
962                         perror("io_uring_register_buffers");
963                         return 1;
964                 }
965
966                 if (dma_map) {
967                         ret = io_uring_map_buffers(s);
968                         if (ret < 0) {
969                                 perror("io_uring_map_buffers");
970                                 return 1;
971                         }
972                 }
973         }
974
975         if (register_files) {
976                 ret = io_uring_register_files(s);
977                 if (ret < 0) {
978                         perror("io_uring_register_files");
979                         return 1;
980                 }
981         }
982
983         ptr = mmap(0, p.sq_off.array + p.sq_entries * sizeof(__u32),
984                         PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd,
985                         IORING_OFF_SQ_RING);
986         sring->head = ptr + p.sq_off.head;
987         sring->tail = ptr + p.sq_off.tail;
988         sring->ring_mask = ptr + p.sq_off.ring_mask;
989         sring->ring_entries = ptr + p.sq_off.ring_entries;
990         sring->flags = ptr + p.sq_off.flags;
991         sring->array = ptr + p.sq_off.array;
992         sq_ring_mask = *sring->ring_mask;
993
994         if (p.flags & IORING_SETUP_SQE128)
995                 len = 2 * p.sq_entries * sizeof(struct io_uring_sqe);
996         else
997                 len = p.sq_entries * sizeof(struct io_uring_sqe);
998         s->sqes = mmap(0, len,
999                         PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd,
1000                         IORING_OFF_SQES);
1001
1002         if (p.flags & IORING_SETUP_CQE32) {
1003                 len = p.cq_off.cqes +
1004                         2 * p.cq_entries * sizeof(struct io_uring_cqe);
1005         } else {
1006                 len = p.cq_off.cqes +
1007                         p.cq_entries * sizeof(struct io_uring_cqe);
1008         }
1009         ptr = mmap(0, len,
1010                         PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd,
1011                         IORING_OFF_CQ_RING);
1012         cring->head = ptr + p.cq_off.head;
1013         cring->tail = ptr + p.cq_off.tail;
1014         cring->ring_mask = ptr + p.cq_off.ring_mask;
1015         cring->ring_entries = ptr + p.cq_off.ring_entries;
1016         cring->cqes = ptr + p.cq_off.cqes;
1017         cq_ring_mask = *cring->ring_mask;
1018
1019         for (i = 0; i < p.sq_entries; i++)
1020                 sring->array[i] = i;
1021
1022         return 0;
1023 }
1024
1025 static void *allocate_mem(struct submitter *s, int size)
1026 {
1027         void *buf;
1028
1029 #ifdef CONFIG_LIBNUMA
1030         if (s->numa_node != -1)
1031                 return numa_alloc_onnode(size, s->numa_node);
1032 #endif
1033
1034         if (posix_memalign(&buf, t_io_uring_page_size, bs)) {
1035                 printf("failed alloc\n");
1036                 return NULL;
1037         }
1038
1039         return buf;
1040 }
1041
1042 static int submitter_init(struct submitter *s)
1043 {
1044         int i, nr_batch, err;
1045         static int init_printed;
1046         char buf[80];
1047         s->tid = gettid();
1048         printf("submitter=%d, tid=%d, file=%s, node=%d\n", s->index, s->tid,
1049                                                         s->filename, s->numa_node);
1050
1051         set_affinity(s);
1052
1053         __init_rand64(&s->rand_state, s->tid);
1054         srand48(s->tid);
1055
1056         for (i = 0; i < MAX_FDS; i++)
1057                 s->files[i].fileno = i;
1058
1059         for (i = 0; i < roundup_pow2(depth); i++) {
1060                 void *buf;
1061
1062                 buf = allocate_mem(s, bs);
1063                 if (!buf)
1064                         return 1;
1065                 s->iovecs[i].iov_base = buf;
1066                 s->iovecs[i].iov_len = bs;
1067         }
1068
1069         if (use_sync) {
1070                 sprintf(buf, "Engine=preadv2\n");
1071                 err = 0;
1072         } else if (!aio) {
1073                 err = setup_ring(s);
1074                 sprintf(buf, "Engine=io_uring, sq_ring=%d, cq_ring=%d\n", *s->sq_ring.ring_entries, *s->cq_ring.ring_entries);
1075         } else {
1076                 sprintf(buf, "Engine=aio\n");
1077                 err = setup_aio(s);
1078         }
1079         if (err) {
1080                 printf("queue setup failed: %s, %d\n", strerror(errno), err);
1081                 return 1;
1082         }
1083
1084         if (!init_printed) {
1085                 printf("polled=%d, fixedbufs=%d/%d, register_files=%d, buffered=%d, QD=%d\n", polled, fixedbufs, dma_map, register_files, buffered, depth);
1086                 printf("%s", buf);
1087                 init_printed = 1;
1088         }
1089
1090         if (stats) {
1091                 nr_batch = roundup_pow2(depth / batch_submit);
1092                 if (nr_batch < 2)
1093                         nr_batch = 2;
1094                 s->clock_batch = calloc(nr_batch, sizeof(unsigned long));
1095                 s->clock_index = 1;
1096
1097                 s->plat = calloc(PLAT_NR, sizeof(unsigned long));
1098         } else {
1099                 s->clock_batch = NULL;
1100                 s->plat = NULL;
1101                 nr_batch = 0;
1102         }
1103         /* perform the expensive command initialization part for passthrough here
1104          * rather than in the fast path
1105          */
1106         if (pt) {
1107                 for (i = 0; i < roundup_pow2(depth); i++) {
1108                         struct io_uring_sqe *sqe = &s->sqes[i << 1];
1109
1110                         memset(&sqe->cmd, 0, sizeof(struct nvme_uring_cmd));
1111                 }
1112         }
1113         return nr_batch;
1114 }
1115
1116 #ifdef CONFIG_LIBAIO
1117 static int prep_more_ios_aio(struct submitter *s, int max_ios, struct iocb *iocbs)
1118 {
1119         uint64_t data;
1120         struct file *f;
1121         unsigned index;
1122
1123         index = 0;
1124         while (index < max_ios) {
1125                 struct iocb *iocb = &iocbs[index];
1126
1127                 if (s->nr_files == 1) {
1128                         f = &s->files[0];
1129                 } else {
1130                         f = &s->files[s->cur_file];
1131                         if (f->pending_ios >= file_depth(s)) {
1132                                 s->cur_file++;
1133                                 if (s->cur_file == s->nr_files)
1134                                         s->cur_file = 0;
1135                                 f = &s->files[s->cur_file];
1136                         }
1137                 }
1138                 f->pending_ios++;
1139
1140                 io_prep_pread(iocb, f->real_fd, s->iovecs[index].iov_base,
1141                                 s->iovecs[index].iov_len, get_offset(s, f));
1142
1143                 data = f->fileno;
1144                 if (stats && stats_running)
1145                         data |= (((uint64_t) s->clock_index) << 32);
1146                 iocb->data = (void *) (uintptr_t) data;
1147                 index++;
1148         }
1149         return index;
1150 }
1151
1152 static int reap_events_aio(struct submitter *s, struct io_event *events, int evs)
1153 {
1154         int last_idx = -1, stat_nr = 0;
1155         int reaped = 0;
1156
1157         while (evs) {
1158                 uint64_t data = (uintptr_t) events[reaped].data;
1159                 struct file *f = &s->files[data & 0xffffffff];
1160
1161                 f->pending_ios--;
1162                 if (events[reaped].res != bs) {
1163                         printf("io: unexpected ret=%ld\n", events[reaped].res);
1164                         return -1;
1165                 }
1166                 if (stats) {
1167                         int clock_index = data >> 32;
1168
1169                         if (last_idx != clock_index) {
1170                                 if (last_idx != -1) {
1171                                         add_stat(s, last_idx, stat_nr);
1172                                         stat_nr = 0;
1173                                 }
1174                                 last_idx = clock_index;
1175                         }
1176                         stat_nr++;
1177                 }
1178                 reaped++;
1179                 evs--;
1180         }
1181
1182         if (stat_nr)
1183                 add_stat(s, last_idx, stat_nr);
1184
1185         s->inflight -= reaped;
1186         s->done += reaped;
1187         return reaped;
1188 }
1189
1190 static void *submitter_aio_fn(void *data)
1191 {
1192         struct submitter *s = data;
1193         int i, ret, prepped;
1194         struct iocb **iocbsptr;
1195         struct iocb *iocbs;
1196         struct io_event *events;
1197 #ifdef ARCH_HAVE_CPU_CLOCK
1198         int nr_batch = submitter_init(s);
1199 #else
1200         submitter_init(s);
1201 #endif
1202
1203         iocbsptr = calloc(depth, sizeof(struct iocb *));
1204         iocbs = calloc(depth, sizeof(struct iocb));
1205         events = calloc(depth, sizeof(struct io_event));
1206
1207         for (i = 0; i < depth; i++)
1208                 iocbsptr[i] = &iocbs[i];
1209
1210         prepped = 0;
1211         do {
1212                 int to_wait, to_submit, to_prep;
1213
1214                 if (!prepped && s->inflight < depth) {
1215                         to_prep = min(depth - s->inflight, batch_submit);
1216                         prepped = prep_more_ios_aio(s, to_prep, iocbs);
1217 #ifdef ARCH_HAVE_CPU_CLOCK
1218                         if (prepped && stats) {
1219                                 s->clock_batch[s->clock_index] = get_cpu_clock();
1220                                 s->clock_index = (s->clock_index + 1) & (nr_batch - 1);
1221                         }
1222 #endif
1223                 }
1224                 s->inflight += prepped;
1225                 to_submit = prepped;
1226
1227                 if (to_submit && (s->inflight + to_submit <= depth))
1228                         to_wait = 0;
1229                 else
1230                         to_wait = min(s->inflight + to_submit, batch_complete);
1231
1232                 ret = io_submit(s->aio_ctx, to_submit, iocbsptr);
1233                 s->calls++;
1234                 if (ret < 0) {
1235                         perror("io_submit");
1236                         break;
1237                 } else if (ret != to_submit) {
1238                         printf("submitted %d, wanted %d\n", ret, to_submit);
1239                         break;
1240                 }
1241                 prepped = 0;
1242
1243                 while (to_wait) {
1244                         int r;
1245
1246                         s->calls++;
1247                         r = io_getevents(s->aio_ctx, to_wait, to_wait, events, NULL);
1248                         if (r < 0) {
1249                                 perror("io_getevents");
1250                                 break;
1251                         } else if (r != to_wait) {
1252                                 printf("r=%d, wait=%d\n", r, to_wait);
1253                                 break;
1254                         }
1255                         r = reap_events_aio(s, events, r);
1256                         s->reaps += r;
1257                         to_wait -= r;
1258                 }
1259         } while (!s->finish);
1260
1261         free(iocbsptr);
1262         free(iocbs);
1263         free(events);
1264         finish = 1;
1265         return NULL;
1266 }
1267 #endif
1268
1269 static void io_uring_unregister_ring(struct submitter *s)
1270 {
1271         struct io_uring_rsrc_update up = {
1272                 .offset = s->enter_ring_fd,
1273         };
1274
1275         syscall(__NR_io_uring_register, s->ring_fd, IORING_UNREGISTER_RING_FDS,
1276                 &up, 1);
1277 }
1278
1279 static int io_uring_register_ring(struct submitter *s)
1280 {
1281         struct io_uring_rsrc_update up = {
1282                 .data   = s->ring_fd,
1283                 .offset = -1U,
1284         };
1285         int ret;
1286
1287         ret = syscall(__NR_io_uring_register, s->ring_fd,
1288                         IORING_REGISTER_RING_FDS, &up, 1);
1289         if (ret == 1) {
1290                 s->enter_ring_fd = up.offset;
1291                 return 0;
1292         }
1293         register_ring = 0;
1294         return -1;
1295 }
1296
1297 static void *submitter_uring_fn(void *data)
1298 {
1299         struct submitter *s = data;
1300         struct io_sq_ring *ring = &s->sq_ring;
1301         int ret, prepped;
1302 #ifdef ARCH_HAVE_CPU_CLOCK
1303         int nr_batch = submitter_init(s);
1304 #else
1305         submitter_init(s);
1306 #endif
1307
1308         if (register_ring)
1309                 io_uring_register_ring(s);
1310
1311         prepped = 0;
1312         do {
1313                 int to_wait, to_submit, this_reap, to_prep;
1314                 unsigned ring_flags = 0;
1315
1316                 if (!prepped && s->inflight < depth) {
1317                         to_prep = min(depth - s->inflight, batch_submit);
1318                         prepped = prep_more_ios_uring(s, to_prep);
1319 #ifdef ARCH_HAVE_CPU_CLOCK
1320                         if (prepped && stats) {
1321                                 s->clock_batch[s->clock_index] = get_cpu_clock();
1322                                 s->clock_index = (s->clock_index + 1) & (nr_batch - 1);
1323                         }
1324 #endif
1325                 }
1326                 s->inflight += prepped;
1327 submit_more:
1328                 to_submit = prepped;
1329 submit:
1330                 if (to_submit && (s->inflight + to_submit <= depth))
1331                         to_wait = 0;
1332                 else
1333                         to_wait = min(s->inflight + to_submit, batch_complete);
1334
1335                 /*
1336                  * Only need to call io_uring_enter if we're not using SQ thread
1337                  * poll, or if IORING_SQ_NEED_WAKEUP is set.
1338                  */
1339                 if (sq_thread_poll)
1340                         ring_flags = atomic_load_acquire(ring->flags);
1341                 if (!sq_thread_poll || ring_flags & IORING_SQ_NEED_WAKEUP) {
1342                         unsigned flags = 0;
1343
1344                         if (to_wait)
1345                                 flags = IORING_ENTER_GETEVENTS;
1346                         if (ring_flags & IORING_SQ_NEED_WAKEUP)
1347                                 flags |= IORING_ENTER_SQ_WAKEUP;
1348                         ret = io_uring_enter(s, to_submit, to_wait, flags);
1349                         s->calls++;
1350                 } else {
1351                         /* for SQPOLL, we submitted it all effectively */
1352                         ret = to_submit;
1353                 }
1354
1355                 /*
1356                  * For non SQ thread poll, we already got the events we needed
1357                  * through the io_uring_enter() above. For SQ thread poll, we
1358                  * need to loop here until we find enough events.
1359                  */
1360                 this_reap = 0;
1361                 do {
1362                         int r;
1363
1364                         if (pt)
1365                                 r = reap_events_uring_pt(s);
1366                         else
1367                                 r = reap_events_uring(s);
1368                         if (r == -1) {
1369                                 s->finish = 1;
1370                                 break;
1371                         } else if (r > 0)
1372                                 this_reap += r;
1373                 } while (sq_thread_poll && this_reap < to_wait);
1374                 s->reaps += this_reap;
1375
1376                 if (ret >= 0) {
1377                         if (!ret) {
1378                                 to_submit = 0;
1379                                 if (s->inflight)
1380                                         goto submit;
1381                                 continue;
1382                         } else if (ret < to_submit) {
1383                                 int diff = to_submit - ret;
1384
1385                                 s->done += ret;
1386                                 prepped -= diff;
1387                                 goto submit_more;
1388                         }
1389                         s->done += ret;
1390                         prepped = 0;
1391                         continue;
1392                 } else if (ret < 0) {
1393                         if (errno == EAGAIN) {
1394                                 if (s->finish)
1395                                         break;
1396                                 if (this_reap)
1397                                         goto submit;
1398                                 to_submit = 0;
1399                                 goto submit;
1400                         }
1401                         printf("io_submit: %s\n", strerror(errno));
1402                         break;
1403                 }
1404         } while (!s->finish);
1405
1406         if (register_ring)
1407                 io_uring_unregister_ring(s);
1408
1409         finish = 1;
1410         return NULL;
1411 }
1412
1413 #ifdef CONFIG_PWRITEV2
1414 static void *submitter_sync_fn(void *data)
1415 {
1416         struct submitter *s = data;
1417         int ret;
1418
1419         submitter_init(s);
1420
1421         do {
1422                 uint64_t offset;
1423                 struct file *f;
1424
1425                 if (s->nr_files == 1) {
1426                         f = &s->files[0];
1427                 } else {
1428                         f = &s->files[s->cur_file];
1429                         if (f->pending_ios >= file_depth(s)) {
1430                                 s->cur_file++;
1431                                 if (s->cur_file == s->nr_files)
1432                                         s->cur_file = 0;
1433                                 f = &s->files[s->cur_file];
1434                         }
1435                 }
1436                 f->pending_ios++;
1437
1438 #ifdef ARCH_HAVE_CPU_CLOCK
1439                 if (stats)
1440                         s->clock_batch[s->clock_index] = get_cpu_clock();
1441 #endif
1442
1443                 s->inflight++;
1444                 s->calls++;
1445
1446                 offset = get_offset(s, f);
1447                 if (polled)
1448                         ret = preadv2(f->real_fd, &s->iovecs[0], 1, offset, RWF_HIPRI);
1449                 else
1450                         ret = preadv2(f->real_fd, &s->iovecs[0], 1, offset, 0);
1451
1452                 if (ret < 0) {
1453                         perror("preadv2");
1454                         break;
1455                 } else if (ret != bs) {
1456                         break;
1457                 }
1458
1459                 s->done++;
1460                 s->inflight--;
1461                 f->pending_ios--;
1462                 if (stats)
1463                         add_stat(s, s->clock_index, 1);
1464         } while (!s->finish);
1465
1466         finish = 1;
1467         return NULL;
1468 }
1469 #else
1470 static void *submitter_sync_fn(void *data)
1471 {
1472         finish = 1;
1473         return NULL;
1474 }
1475 #endif
1476
1477 static struct submitter *get_submitter(int offset)
1478 {
1479         void *ret;
1480
1481         ret = submitter;
1482         if (offset)
1483                 ret += offset * (sizeof(*submitter) + depth * sizeof(struct iovec));
1484         return ret;
1485 }
1486
1487 static void do_finish(const char *reason)
1488 {
1489         int j;
1490
1491         printf("Exiting on %s\n", reason);
1492         for (j = 0; j < nthreads; j++) {
1493                 struct submitter *s = get_submitter(j);
1494                 s->finish = 1;
1495         }
1496         if (max_iops > 1000000) {
1497                 double miops = (double) max_iops / 1000000.0;
1498                 printf("Maximum IOPS=%.2fM\n", miops);
1499         } else if (max_iops > 100000) {
1500                 double kiops = (double) max_iops / 1000.0;
1501                 printf("Maximum IOPS=%.2fK\n", kiops);
1502         } else {
1503                 printf("Maximum IOPS=%lu\n", max_iops);
1504         }
1505         finish = 1;
1506 }
1507
1508 static void sig_int(int sig)
1509 {
1510         do_finish("signal");
1511 }
1512
1513 static void arm_sig_int(void)
1514 {
1515         struct sigaction act;
1516
1517         memset(&act, 0, sizeof(act));
1518         act.sa_handler = sig_int;
1519         act.sa_flags = SA_RESTART;
1520         sigaction(SIGINT, &act, NULL);
1521
1522         /* Windows uses SIGBREAK as a quit signal from other applications */
1523 #ifdef WIN32
1524         sigaction(SIGBREAK, &act, NULL);
1525 #endif
1526 }
1527
1528 static void usage(char *argv, int status)
1529 {
1530         char runtime_str[16];
1531         snprintf(runtime_str, sizeof(runtime_str), "%d", runtime);
1532         printf("%s [options] -- [filenames]\n"
1533                 " -d <int>  : IO Depth, default %d\n"
1534                 " -s <int>  : Batch submit, default %d\n"
1535                 " -c <int>  : Batch complete, default %d\n"
1536                 " -b <int>  : Block size, default %d\n"
1537                 " -p <bool> : Polled IO, default %d\n"
1538                 " -B <bool> : Fixed buffers, default %d\n"
1539                 " -D <bool> : DMA map fixed buffers, default %d\n"
1540                 " -F <bool> : Register files, default %d\n"
1541                 " -n <int>  : Number of threads, default %d\n"
1542                 " -O <bool> : Use O_DIRECT, default %d\n"
1543                 " -N <bool> : Perform just no-op requests, default %d\n"
1544                 " -t <bool> : Track IO latencies, default %d\n"
1545                 " -T <int>  : TSC rate in HZ\n"
1546                 " -r <int>  : Runtime in seconds, default %s\n"
1547                 " -R <bool> : Use random IO, default %d\n"
1548                 " -a <bool> : Use legacy aio, default %d\n"
1549                 " -S <bool> : Use sync IO (preadv2), default %d\n"
1550                 " -X <bool> : Use registered ring %d\n"
1551                 " -P <bool> : Automatically place on device home node %d\n"
1552                 " -u <bool> : Use nvme-passthrough I/O, default %d\n",
1553                 argv, DEPTH, BATCH_SUBMIT, BATCH_COMPLETE, BS, polled,
1554                 fixedbufs, dma_map, register_files, nthreads, !buffered, do_nop,
1555                 stats, runtime == 0 ? "unlimited" : runtime_str, random_io, aio,
1556                 use_sync, register_ring, numa_placement, pt);
1557         exit(status);
1558 }
1559
1560 static void read_tsc_rate(void)
1561 {
1562         char buffer[32];
1563         int fd, ret;
1564
1565         if (tsc_rate)
1566                 return;
1567
1568         fd = open(TSC_RATE_FILE, O_RDONLY);
1569         if (fd < 0)
1570                 return;
1571
1572         ret = read(fd, buffer, sizeof(buffer));
1573         if (ret < 0) {
1574                 close(fd);
1575                 return;
1576         }
1577
1578         tsc_rate = strtoul(buffer, NULL, 10);
1579         printf("Using TSC rate %luHz\n", tsc_rate);
1580         close(fd);
1581 }
1582
1583 static void write_tsc_rate(void)
1584 {
1585         char buffer[32];
1586         struct stat sb;
1587         int fd, ret;
1588
1589         if (!stat(TSC_RATE_FILE, &sb))
1590                 return;
1591
1592         fd = open(TSC_RATE_FILE, O_WRONLY | O_CREAT, 0644);
1593         if (fd < 0)
1594                 return;
1595
1596         memset(buffer, 0, sizeof(buffer));
1597         sprintf(buffer, "%lu", tsc_rate);
1598         ret = write(fd, buffer, strlen(buffer));
1599         if (ret < 0)
1600                 perror("write");
1601         close(fd);
1602 }
1603
1604 int main(int argc, char *argv[])
1605 {
1606         struct submitter *s;
1607         unsigned long done, calls, reap;
1608         int i, j, flags, fd, opt, threads_per_f, threads_rem = 0, nfiles;
1609         struct file f;
1610         void *ret;
1611
1612         if (!do_nop && argc < 2)
1613                 usage(argv[0], 1);
1614
1615         while ((opt = getopt(argc, argv, "d:s:c:b:p:B:F:n:N:O:t:T:a:r:D:R:X:S:P:u:h?")) != -1) {
1616                 switch (opt) {
1617                 case 'a':
1618                         aio = !!atoi(optarg);
1619                         break;
1620                 case 'd':
1621                         depth = atoi(optarg);
1622                         break;
1623                 case 's':
1624                         batch_submit = atoi(optarg);
1625                         if (!batch_submit)
1626                                 batch_submit = 1;
1627                         break;
1628                 case 'c':
1629                         batch_complete = atoi(optarg);
1630                         if (!batch_complete)
1631                                 batch_complete = 1;
1632                         break;
1633                 case 'b':
1634                         bs = atoi(optarg);
1635                         break;
1636                 case 'p':
1637                         polled = !!atoi(optarg);
1638                         break;
1639                 case 'B':
1640                         fixedbufs = !!atoi(optarg);
1641                         break;
1642                 case 'F':
1643                         register_files = !!atoi(optarg);
1644                         break;
1645                 case 'n':
1646                         nthreads = atoi(optarg);
1647                         if (!nthreads) {
1648                                 printf("Threads must be non-zero\n");
1649                                 usage(argv[0], 1);
1650                         }
1651                         break;
1652                 case 'N':
1653                         do_nop = !!atoi(optarg);
1654                         break;
1655                 case 'O':
1656                         buffered = !atoi(optarg);
1657                         break;
1658                 case 't':
1659 #ifndef ARCH_HAVE_CPU_CLOCK
1660                         fprintf(stderr, "Stats not supported on this CPU\n");
1661                         return 1;
1662 #endif
1663                         stats = !!atoi(optarg);
1664                         break;
1665                 case 'T':
1666 #ifndef ARCH_HAVE_CPU_CLOCK
1667                         fprintf(stderr, "Stats not supported on this CPU\n");
1668                         return 1;
1669 #endif
1670                         tsc_rate = strtoul(optarg, NULL, 10);
1671                         write_tsc_rate();
1672                         break;
1673                 case 'r':
1674                         runtime = atoi(optarg);
1675                         break;
1676                 case 'D':
1677                         dma_map = !!atoi(optarg);
1678                         break;
1679                 case 'R':
1680                         random_io = !!atoi(optarg);
1681                         break;
1682                 case 'X':
1683                         register_ring = !!atoi(optarg);
1684                         break;
1685                 case 'S':
1686 #ifdef CONFIG_PWRITEV2
1687                         use_sync = !!atoi(optarg);
1688 #else
1689                         fprintf(stderr, "preadv2 not supported\n");
1690                         exit(1);
1691 #endif
1692                         break;
1693                 case 'P':
1694                         numa_placement = !!atoi(optarg);
1695                         break;
1696                 case 'u':
1697                         pt = !!atoi(optarg);
1698                         break;
1699                 case 'h':
1700                 case '?':
1701                 default:
1702                         usage(argv[0], 0);
1703                         break;
1704                 }
1705         }
1706
1707         if (stats)
1708                 read_tsc_rate();
1709
1710         if (batch_complete > depth)
1711                 batch_complete = depth;
1712         if (batch_submit > depth)
1713                 batch_submit = depth;
1714         if (!fixedbufs && dma_map)
1715                 dma_map = 0;
1716
1717         submitter = calloc(nthreads, sizeof(*submitter) +
1718                                 roundup_pow2(depth) * sizeof(struct iovec));
1719         for (j = 0; j < nthreads; j++) {
1720                 s = get_submitter(j);
1721                 s->numa_node = -1;
1722                 s->index = j;
1723                 s->done = s->calls = s->reaps = 0;
1724         }
1725
1726         flags = O_RDONLY | O_NOATIME;
1727         if (!buffered)
1728                 flags |= O_DIRECT;
1729
1730         j = 0;
1731         i = optind;
1732         nfiles = argc - i;
1733         if (!do_nop) {
1734                 if (!nfiles) {
1735                         printf("No files specified\n");
1736                         usage(argv[0], 1);
1737                 }
1738                 threads_per_f = nthreads / nfiles;
1739                 /* make sure each thread gets assigned files */
1740                 if (threads_per_f == 0) {
1741                         threads_per_f = 1;
1742                 } else {
1743                         threads_rem = nthreads - threads_per_f * nfiles;
1744                 }
1745         }
1746         while (!do_nop && i < argc) {
1747                 int k, limit;
1748
1749                 memset(&f, 0, sizeof(f));
1750
1751                 fd = open(argv[i], flags);
1752                 if (fd < 0) {
1753                         perror("open");
1754                         return 1;
1755                 }
1756                 f.real_fd = fd;
1757                 if (get_file_size(&f)) {
1758                         printf("failed getting size of device/file\n");
1759                         return 1;
1760                 }
1761                 if (f.max_blocks <= 1) {
1762                         printf("Zero file/device size?\n");
1763                         return 1;
1764                 }
1765                 f.max_blocks--;
1766
1767                 limit = threads_per_f;
1768                 limit += threads_rem > 0 ? 1 : 0;
1769                 for (k = 0; k < limit; k++) {
1770                         s = get_submitter((j + k) % nthreads);
1771
1772                         if (s->nr_files == MAX_FDS) {
1773                                 printf("Max number of files (%d) reached\n", MAX_FDS);
1774                                 break;
1775                         }
1776
1777                         memcpy(&s->files[s->nr_files], &f, sizeof(f));
1778
1779                         if (numa_placement)
1780                                 detect_node(s, argv[i]);
1781
1782                         s->filename = argv[i];
1783                         s->nr_files++;
1784                 }
1785                 threads_rem--;
1786                 i++;
1787                 j += limit;
1788         }
1789
1790         arm_sig_int();
1791
1792         t_io_uring_page_size = sysconf(_SC_PAGESIZE);
1793         if (t_io_uring_page_size < 0)
1794                 t_io_uring_page_size = 4096;
1795
1796         for (j = 0; j < nthreads; j++) {
1797                 s = get_submitter(j);
1798                 if (use_sync)
1799                         pthread_create(&s->thread, NULL, submitter_sync_fn, s);
1800                 else if (!aio)
1801                         pthread_create(&s->thread, NULL, submitter_uring_fn, s);
1802 #ifdef CONFIG_LIBAIO
1803                 else
1804                         pthread_create(&s->thread, NULL, submitter_aio_fn, s);
1805 #endif
1806         }
1807
1808         reap = calls = done = 0;
1809         do {
1810                 unsigned long this_done = 0;
1811                 unsigned long this_reap = 0;
1812                 unsigned long this_call = 0;
1813                 unsigned long rpc = 0, ipc = 0;
1814                 unsigned long iops, bw;
1815
1816                 sleep(1);
1817                 if (runtime && !--runtime)
1818                         do_finish("timeout");
1819
1820                 /* don't print partial run, if interrupted by signal */
1821                 if (finish)
1822                         break;
1823
1824                 /* one second in to the run, enable stats */
1825                 if (stats)
1826                         stats_running = 1;
1827
1828                 for (j = 0; j < nthreads; j++) {
1829                         s = get_submitter(j);
1830                         this_done += s->done;
1831                         this_call += s->calls;
1832                         this_reap += s->reaps;
1833                 }
1834                 if (this_call - calls) {
1835                         rpc = (this_done - done) / (this_call - calls);
1836                         ipc = (this_reap - reap) / (this_call - calls);
1837                 } else
1838                         rpc = ipc = -1;
1839                 iops = this_done - done;
1840                 if (bs > 1048576)
1841                         bw = iops * (bs / 1048576);
1842                 else
1843                         bw = iops / (1048576 / bs);
1844                 if (iops > 1000000) {
1845                         double miops = (double) iops / 1000000.0;
1846                         printf("IOPS=%.2fM, ", miops);
1847                 } else if (iops > 100000) {
1848                         double kiops = (double) iops / 1000.0;
1849                         printf("IOPS=%.2fK, ", kiops);
1850                 } else {
1851                         printf("IOPS=%lu, ", iops);
1852                 }
1853                 max_iops = max(max_iops, iops);
1854                 if (!do_nop) {
1855                         if (bw > 2000) {
1856                                 double bw_g = (double) bw / 1000.0;
1857
1858                                 printf("BW=%.2fGiB/s, ", bw_g);
1859                         } else {
1860                                 printf("BW=%luMiB/s, ", bw);
1861                         }
1862                 }
1863                 printf("IOS/call=%ld/%ld\n", rpc, ipc);
1864                 done = this_done;
1865                 calls = this_call;
1866                 reap = this_reap;
1867         } while (!finish);
1868
1869         for (j = 0; j < nthreads; j++) {
1870                 s = get_submitter(j);
1871                 pthread_join(s->thread, &ret);
1872                 close(s->ring_fd);
1873
1874                 if (stats) {
1875                         unsigned long nr;
1876
1877                         printf("%d: Latency percentiles:\n", s->tid);
1878                         for (i = 0, nr = 0; i < PLAT_NR; i++)
1879                                 nr += s->plat[i];
1880                         show_clat_percentiles(s->plat, nr, 4);
1881                         free(s->clock_batch);
1882                         free(s->plat);
1883                 }
1884         }
1885
1886         free(submitter);
1887         return 0;
1888 }