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