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