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