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