t/io_uring: add test support for pre mapping DMA buffers
[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 #include <sys/types.h>
15 #include <sys/stat.h>
16 #include <sys/ioctl.h>
17 #include <sys/syscall.h>
18 #include <sys/resource.h>
19 #include <sys/mman.h>
20 #include <sys/uio.h>
21 #include <linux/fs.h>
22 #include <fcntl.h>
23 #include <unistd.h>
24 #include <string.h>
25 #include <pthread.h>
26 #include <sched.h>
27
28 #include "../arch/arch.h"
29 #include "../lib/types.h"
30 #include "../lib/roundup.h"
31 #include "../minmax.h"
32 #include "../os/linux/io_uring.h"
33
34 struct io_sq_ring {
35         unsigned *head;
36         unsigned *tail;
37         unsigned *ring_mask;
38         unsigned *ring_entries;
39         unsigned *flags;
40         unsigned *array;
41 };
42
43 struct io_cq_ring {
44         unsigned *head;
45         unsigned *tail;
46         unsigned *ring_mask;
47         unsigned *ring_entries;
48         struct io_uring_cqe *cqes;
49 };
50
51 #define DEPTH                   128
52 #define BATCH_SUBMIT            32
53 #define BATCH_COMPLETE          32
54 #define BS                      4096
55
56 #define MAX_FDS                 16
57
58 static unsigned sq_ring_mask, cq_ring_mask;
59
60 struct file {
61         unsigned long max_blocks;
62         unsigned pending_ios;
63         int real_fd;
64         int fixed_fd;
65         int fileno;
66 };
67
68 #define PLAT_BITS               6
69 #define PLAT_VAL                (1 << PLAT_BITS)
70 #define PLAT_GROUP_NR           29
71 #define PLAT_NR                 (PLAT_GROUP_NR * PLAT_VAL)
72
73 struct submitter {
74         pthread_t thread;
75         int ring_fd;
76         int index;
77         struct io_sq_ring sq_ring;
78         struct io_uring_sqe *sqes;
79         struct io_cq_ring cq_ring;
80         int inflight;
81         int tid;
82         unsigned long reaps;
83         unsigned long done;
84         unsigned long calls;
85         volatile int finish;
86
87         __s32 *fds;
88
89         unsigned long *clock_batch;
90         int clock_index;
91         unsigned long *plat;
92
93 #ifdef CONFIG_LIBAIO
94         io_context_t aio_ctx;
95 #endif
96
97         struct file files[MAX_FDS];
98         unsigned nr_files;
99         unsigned cur_file;
100         struct iovec iovecs[];
101 };
102
103 static struct submitter *submitter;
104 static volatile int finish;
105 static int stats_running;
106
107 static int depth = DEPTH;
108 static int batch_submit = BATCH_SUBMIT;
109 static int batch_complete = BATCH_COMPLETE;
110 static int bs = BS;
111 static int polled = 1;          /* use IO polling */
112 static int fixedbufs = 1;       /* use fixed user buffers */
113 static int dma_map;             /* pre-map DMA buffers */
114 static int register_files = 1;  /* use fixed files */
115 static int buffered = 0;        /* use buffered IO, not O_DIRECT */
116 static int sq_thread_poll = 0;  /* use kernel submission/poller thread */
117 static int sq_thread_cpu = -1;  /* pin above thread to this CPU */
118 static int do_nop = 0;          /* no-op SQ ring commands */
119 static int nthreads = 1;
120 static int stats = 0;           /* generate IO stats */
121 static int aio = 0;             /* use libaio */
122 static int runtime = 0; /* runtime */
123
124 static unsigned long tsc_rate;
125
126 #define TSC_RATE_FILE   "tsc-rate"
127
128 static int vectored = 1;
129
130 static float plist[] = { 1.0, 5.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0,
131                         80.0, 90.0, 95.0, 99.0, 99.5, 99.9, 99.95, 99.99 };
132 static int plist_len = 17;
133
134 #ifndef IORING_REGISTER_MAP_BUFFERS
135 #define IORING_REGISTER_MAP_BUFFERS     20
136 struct io_uring_map_buffers {
137         __s32   fd;
138         __u32   buf_start;
139         __u32   buf_end;
140         __u32   dir;
141 };
142 #endif
143
144 static unsigned long cycles_to_nsec(unsigned long cycles)
145 {
146         uint64_t val;
147
148         if (!tsc_rate)
149                 return cycles;
150
151         val = cycles * 1000000000ULL;
152         return val / tsc_rate;
153 }
154
155 static unsigned long plat_idx_to_val(unsigned int idx)
156 {
157         unsigned int error_bits;
158         unsigned long k, base;
159
160         assert(idx < PLAT_NR);
161
162         /* MSB <= (PLAT_BITS-1), cannot be rounded off. Use
163          * all bits of the sample as index */
164         if (idx < (PLAT_VAL << 1))
165                 return cycles_to_nsec(idx);
166
167         /* Find the group and compute the minimum value of that group */
168         error_bits = (idx >> PLAT_BITS) - 1;
169         base = ((unsigned long) 1) << (error_bits + PLAT_BITS);
170
171         /* Find its bucket number of the group */
172         k = idx % PLAT_VAL;
173
174         /* Return the mean of the range of the bucket */
175         return cycles_to_nsec(base + ((k + 0.5) * (1 << error_bits)));
176 }
177
178 unsigned int calc_clat_percentiles(unsigned long *io_u_plat, unsigned long nr,
179                                    unsigned long **output,
180                                    unsigned long *maxv, unsigned long *minv)
181 {
182         unsigned long sum = 0;
183         unsigned int len = plist_len, i, j = 0;
184         unsigned long *ovals = NULL;
185         bool is_last;
186
187         *minv = -1ULL;
188         *maxv = 0;
189
190         ovals = malloc(len * sizeof(*ovals));
191         if (!ovals)
192                 return 0;
193
194         /*
195          * Calculate bucket values, note down max and min values
196          */
197         is_last = false;
198         for (i = 0; i < PLAT_NR && !is_last; i++) {
199                 sum += io_u_plat[i];
200                 while (sum >= ((long double) plist[j] / 100.0 * nr)) {
201                         assert(plist[j] <= 100.0);
202
203                         ovals[j] = plat_idx_to_val(i);
204                         if (ovals[j] < *minv)
205                                 *minv = ovals[j];
206                         if (ovals[j] > *maxv)
207                                 *maxv = ovals[j];
208
209                         is_last = (j == len - 1) != 0;
210                         if (is_last)
211                                 break;
212
213                         j++;
214                 }
215         }
216
217         if (!is_last)
218                 fprintf(stderr, "error calculating latency percentiles\n");
219
220         *output = ovals;
221         return len;
222 }
223
224 static void show_clat_percentiles(unsigned long *io_u_plat, unsigned long nr,
225                                   unsigned int precision)
226 {
227         unsigned int divisor, len, i, j = 0;
228         unsigned long minv, maxv;
229         unsigned long *ovals;
230         int per_line, scale_down, time_width;
231         bool is_last;
232         char fmt[32];
233
234         len = calc_clat_percentiles(io_u_plat, nr, &ovals, &maxv, &minv);
235         if (!len || !ovals)
236                 goto out;
237
238         if (!tsc_rate) {
239                 scale_down = 0;
240                 divisor = 1;
241                 printf("    percentiles (tsc ticks):\n     |");
242         } else if (minv > 2000 && maxv > 99999) {
243                 scale_down = 1;
244                 divisor = 1000;
245                 printf("    percentiles (usec):\n     |");
246         } else {
247                 scale_down = 0;
248                 divisor = 1;
249                 printf("    percentiles (nsec):\n     |");
250         }
251
252         time_width = max(5, (int) (log10(maxv / divisor) + 1));
253         snprintf(fmt, sizeof(fmt), " %%%u.%ufth=[%%%dllu]%%c", precision + 3,
254                         precision, time_width);
255         /* fmt will be something like " %5.2fth=[%4llu]%c" */
256         per_line = (80 - 7) / (precision + 10 + time_width);
257
258         for (j = 0; j < len; j++) {
259                 /* for formatting */
260                 if (j != 0 && (j % per_line) == 0)
261                         printf("     |");
262
263                 /* end of the list */
264                 is_last = (j == len - 1) != 0;
265
266                 for (i = 0; i < scale_down; i++)
267                         ovals[j] = (ovals[j] + 999) / 1000;
268
269                 printf(fmt, plist[j], ovals[j], is_last ? '\n' : ',');
270
271                 if (is_last)
272                         break;
273
274                 if ((j % per_line) == per_line - 1)     /* for formatting */
275                         printf("\n");
276         }
277
278 out:
279         free(ovals);
280 }
281
282 static unsigned int plat_val_to_idx(unsigned long val)
283 {
284         unsigned int msb, error_bits, base, offset, idx;
285
286         /* Find MSB starting from bit 0 */
287         if (val == 0)
288                 msb = 0;
289         else
290                 msb = (sizeof(val)*8) - __builtin_clzll(val) - 1;
291
292         /*
293          * MSB <= (PLAT_BITS-1), cannot be rounded off. Use
294          * all bits of the sample as index
295          */
296         if (msb <= PLAT_BITS)
297                 return val;
298
299         /* Compute the number of error bits to discard*/
300         error_bits = msb - PLAT_BITS;
301
302         /* Compute the number of buckets before the group */
303         base = (error_bits + 1) << PLAT_BITS;
304
305         /*
306          * Discard the error bits and apply the mask to find the
307          * index for the buckets in the group
308          */
309         offset = (PLAT_VAL - 1) & (val >> error_bits);
310
311         /* Make sure the index does not exceed (array size - 1) */
312         idx = (base + offset) < (PLAT_NR - 1) ?
313                 (base + offset) : (PLAT_NR - 1);
314
315         return idx;
316 }
317
318 static void add_stat(struct submitter *s, int clock_index, int nr)
319 {
320 #ifdef ARCH_HAVE_CPU_CLOCK
321         unsigned long cycles;
322         unsigned int pidx;
323
324         if (!s->finish && clock_index) {
325                 cycles = get_cpu_clock();
326                 cycles -= s->clock_batch[clock_index];
327                 pidx = plat_val_to_idx(cycles);
328                 s->plat[pidx] += nr;
329         }
330 #endif
331 }
332
333 static int io_uring_map_buffers(struct submitter *s)
334 {
335         struct io_uring_map_buffers map = {
336                 .fd             = s->files[0].real_fd,
337                 .buf_start      = 0,
338                 .buf_end        = depth,
339                 .dir            = 0,
340         };
341
342         if (do_nop)
343                 return 0;
344         if (s->nr_files > 1) {
345                 fprintf(stderr, "Can't map buffers with multiple files\n");
346                 return -1;
347         }
348
349         return syscall(__NR_io_uring_register, s->ring_fd,
350                         IORING_REGISTER_MAP_BUFFERS, &map, 1);
351 }
352
353 static int io_uring_register_buffers(struct submitter *s)
354 {
355         if (do_nop)
356                 return 0;
357
358         return syscall(__NR_io_uring_register, s->ring_fd,
359                         IORING_REGISTER_BUFFERS, s->iovecs, depth);
360 }
361
362 static int io_uring_register_files(struct submitter *s)
363 {
364         int i;
365
366         if (do_nop)
367                 return 0;
368
369         s->fds = calloc(s->nr_files, sizeof(__s32));
370         for (i = 0; i < s->nr_files; i++) {
371                 s->fds[i] = s->files[i].real_fd;
372                 s->files[i].fixed_fd = i;
373         }
374
375         return syscall(__NR_io_uring_register, s->ring_fd,
376                         IORING_REGISTER_FILES, s->fds, s->nr_files);
377 }
378
379 static int io_uring_setup(unsigned entries, struct io_uring_params *p)
380 {
381         return syscall(__NR_io_uring_setup, entries, p);
382 }
383
384 static void io_uring_probe(int fd)
385 {
386         struct io_uring_probe *p;
387         int ret;
388
389         p = malloc(sizeof(*p) + 256 * sizeof(struct io_uring_probe_op));
390         if (!p)
391                 return;
392
393         memset(p, 0, sizeof(*p) + 256 * sizeof(struct io_uring_probe_op));
394         ret = syscall(__NR_io_uring_register, fd, IORING_REGISTER_PROBE, p, 256);
395         if (ret < 0)
396                 goto out;
397
398         if (IORING_OP_READ > p->ops_len)
399                 goto out;
400
401         if ((p->ops[IORING_OP_READ].flags & IO_URING_OP_SUPPORTED))
402                 vectored = 0;
403 out:
404         free(p);
405 }
406
407 static int io_uring_enter(struct submitter *s, unsigned int to_submit,
408                           unsigned int min_complete, unsigned int flags)
409 {
410         return syscall(__NR_io_uring_enter, s->ring_fd, to_submit, min_complete,
411                         flags, NULL, 0);
412 }
413
414 #ifndef CONFIG_HAVE_GETTID
415 static int gettid(void)
416 {
417         return syscall(__NR_gettid);
418 }
419 #endif
420
421 static unsigned file_depth(struct submitter *s)
422 {
423         return (depth + s->nr_files - 1) / s->nr_files;
424 }
425
426 static void init_io(struct submitter *s, unsigned index)
427 {
428         struct io_uring_sqe *sqe = &s->sqes[index];
429         unsigned long offset;
430         struct file *f;
431         long r;
432
433         if (do_nop) {
434                 sqe->opcode = IORING_OP_NOP;
435                 return;
436         }
437
438         if (s->nr_files == 1) {
439                 f = &s->files[0];
440         } else {
441                 f = &s->files[s->cur_file];
442                 if (f->pending_ios >= file_depth(s)) {
443                         s->cur_file++;
444                         if (s->cur_file == s->nr_files)
445                                 s->cur_file = 0;
446                         f = &s->files[s->cur_file];
447                 }
448         }
449         f->pending_ios++;
450
451         r = lrand48();
452         offset = (r % (f->max_blocks - 1)) * bs;
453
454         if (register_files) {
455                 sqe->flags = IOSQE_FIXED_FILE;
456                 sqe->fd = f->fixed_fd;
457         } else {
458                 sqe->flags = 0;
459                 sqe->fd = f->real_fd;
460         }
461         if (fixedbufs) {
462                 sqe->opcode = IORING_OP_READ_FIXED;
463                 sqe->addr = (unsigned long) s->iovecs[index].iov_base;
464                 sqe->len = bs;
465                 sqe->buf_index = index;
466         } else if (!vectored) {
467                 sqe->opcode = IORING_OP_READ;
468                 sqe->addr = (unsigned long) s->iovecs[index].iov_base;
469                 sqe->len = bs;
470                 sqe->buf_index = 0;
471         } else {
472                 sqe->opcode = IORING_OP_READV;
473                 sqe->addr = (unsigned long) &s->iovecs[index];
474                 sqe->len = 1;
475                 sqe->buf_index = 0;
476         }
477         sqe->ioprio = 0;
478         sqe->off = offset;
479         sqe->user_data = (unsigned long) f->fileno;
480         if (stats && stats_running)
481                 sqe->user_data |= ((unsigned long)s->clock_index << 32);
482 }
483
484 static int prep_more_ios_uring(struct submitter *s, int max_ios)
485 {
486         struct io_sq_ring *ring = &s->sq_ring;
487         unsigned index, tail, next_tail, prepped = 0;
488
489         next_tail = tail = *ring->tail;
490         do {
491                 next_tail++;
492                 if (next_tail == atomic_load_acquire(ring->head))
493                         break;
494
495                 index = tail & sq_ring_mask;
496                 init_io(s, index);
497                 ring->array[index] = index;
498                 prepped++;
499                 tail = next_tail;
500         } while (prepped < max_ios);
501
502         if (prepped)
503                 atomic_store_release(ring->tail, tail);
504         return prepped;
505 }
506
507 static int get_file_size(struct file *f)
508 {
509         struct stat st;
510
511         if (fstat(f->real_fd, &st) < 0)
512                 return -1;
513         if (S_ISBLK(st.st_mode)) {
514                 unsigned long long bytes;
515
516                 if (ioctl(f->real_fd, BLKGETSIZE64, &bytes) != 0)
517                         return -1;
518
519                 f->max_blocks = bytes / bs;
520                 return 0;
521         } else if (S_ISREG(st.st_mode)) {
522                 f->max_blocks = st.st_size / bs;
523                 return 0;
524         }
525
526         return -1;
527 }
528
529 static int reap_events_uring(struct submitter *s)
530 {
531         struct io_cq_ring *ring = &s->cq_ring;
532         struct io_uring_cqe *cqe;
533         unsigned head, reaped = 0;
534         int last_idx = -1, stat_nr = 0;
535
536         head = *ring->head;
537         do {
538                 struct file *f;
539
540                 read_barrier();
541                 if (head == atomic_load_acquire(ring->tail))
542                         break;
543                 cqe = &ring->cqes[head & cq_ring_mask];
544                 if (!do_nop) {
545                         int fileno = cqe->user_data & 0xffffffff;
546
547                         f = &s->files[fileno];
548                         f->pending_ios--;
549                         if (cqe->res != bs) {
550                                 printf("io: unexpected ret=%d\n", cqe->res);
551                                 if (polled && cqe->res == -EOPNOTSUPP)
552                                         printf("Your filesystem/driver/kernel doesn't support polled IO\n");
553                                 return -1;
554                         }
555                 }
556                 if (stats) {
557                         int clock_index = cqe->user_data >> 32;
558
559                         if (last_idx != clock_index) {
560                                 if (last_idx != -1) {
561                                         add_stat(s, last_idx, stat_nr);
562                                         stat_nr = 0;
563                                 }
564                                 last_idx = clock_index;
565                         }
566                         stat_nr++;
567                 }
568                 reaped++;
569                 head++;
570         } while (1);
571
572         if (stat_nr)
573                 add_stat(s, last_idx, stat_nr);
574
575         if (reaped) {
576                 s->inflight -= reaped;
577                 atomic_store_release(ring->head, head);
578         }
579         return reaped;
580 }
581
582 static int submitter_init(struct submitter *s)
583 {
584         int i, nr_batch;
585
586         s->tid = gettid();
587         printf("submitter=%d, tid=%d\n", s->index, s->tid);
588
589         srand48(pthread_self());
590
591         for (i = 0; i < MAX_FDS; i++)
592                 s->files[i].fileno = i;
593
594         if (stats) {
595                 nr_batch = roundup_pow2(depth / batch_submit);
596                 if (nr_batch < 2)
597                         nr_batch = 2;
598                 s->clock_batch = calloc(nr_batch, sizeof(unsigned long));
599                 s->clock_index = 1;
600
601                 s->plat = calloc(PLAT_NR, sizeof(unsigned long));
602         } else {
603                 s->clock_batch = NULL;
604                 s->plat = NULL;
605                 nr_batch = 0;
606         }
607
608         return nr_batch;
609 }
610
611 #ifdef CONFIG_LIBAIO
612 static int prep_more_ios_aio(struct submitter *s, int max_ios, struct iocb *iocbs)
613 {
614         unsigned long offset, data;
615         struct file *f;
616         unsigned index;
617         long r;
618
619         index = 0;
620         while (index < max_ios) {
621                 struct iocb *iocb = &iocbs[index];
622
623                 if (s->nr_files == 1) {
624                         f = &s->files[0];
625                 } else {
626                         f = &s->files[s->cur_file];
627                         if (f->pending_ios >= file_depth(s)) {
628                                 s->cur_file++;
629                                 if (s->cur_file == s->nr_files)
630                                         s->cur_file = 0;
631                                 f = &s->files[s->cur_file];
632                         }
633                 }
634                 f->pending_ios++;
635
636                 r = lrand48();
637                 offset = (r % (f->max_blocks - 1)) * bs;
638                 io_prep_pread(iocb, f->real_fd, s->iovecs[index].iov_base,
639                                 s->iovecs[index].iov_len, offset);
640
641                 data = f->fileno;
642                 if (stats && stats_running)
643                         data |= ((unsigned long) s->clock_index << 32);
644                 iocb->data = (void *) (uintptr_t) data;
645                 index++;
646         }
647         return index;
648 }
649
650 static int reap_events_aio(struct submitter *s, struct io_event *events, int evs)
651 {
652         int last_idx = -1, stat_nr = 0;
653         int reaped = 0;
654
655         while (evs) {
656                 unsigned long data = (uintptr_t) events[reaped].data;
657                 struct file *f = &s->files[data & 0xffffffff];
658
659                 f->pending_ios--;
660                 if (events[reaped].res != bs) {
661                         printf("io: unexpected ret=%ld\n", events[reaped].res);
662                         return -1;
663                 }
664                 if (stats) {
665                         int clock_index = data >> 32;
666
667                         if (last_idx != clock_index) {
668                                 if (last_idx != -1) {
669                                         add_stat(s, last_idx, stat_nr);
670                                         stat_nr = 0;
671                                 }
672                                 last_idx = clock_index;
673                         }
674                         stat_nr++;
675                 }
676                 reaped++;
677                 evs--;
678         }
679
680         if (stat_nr)
681                 add_stat(s, last_idx, stat_nr);
682
683         s->inflight -= reaped;
684         s->done += reaped;
685         return reaped;
686 }
687
688 static void *submitter_aio_fn(void *data)
689 {
690         struct submitter *s = data;
691         int i, ret, prepped, nr_batch;
692         struct iocb **iocbsptr;
693         struct iocb *iocbs;
694         struct io_event *events;
695
696         nr_batch = submitter_init(s);
697
698         iocbsptr = calloc(depth, sizeof(struct iocb *));
699         iocbs = calloc(depth, sizeof(struct iocb));
700         events = calloc(depth, sizeof(struct io_event));
701
702         for (i = 0; i < depth; i++)
703                 iocbsptr[i] = &iocbs[i];
704
705         prepped = 0;
706         do {
707                 int to_wait, to_submit, to_prep;
708
709                 if (!prepped && s->inflight < depth) {
710                         to_prep = min(depth - s->inflight, batch_submit);
711                         prepped = prep_more_ios_aio(s, to_prep, iocbs);
712 #ifdef ARCH_HAVE_CPU_CLOCK
713                         if (prepped && stats) {
714                                 s->clock_batch[s->clock_index] = get_cpu_clock();
715                                 s->clock_index = (s->clock_index + 1) & (nr_batch - 1);
716                         }
717 #endif
718                 }
719                 s->inflight += prepped;
720                 to_submit = prepped;
721
722                 if (to_submit && (s->inflight + to_submit <= depth))
723                         to_wait = 0;
724                 else
725                         to_wait = min(s->inflight + to_submit, batch_complete);
726
727                 ret = io_submit(s->aio_ctx, to_submit, iocbsptr);
728                 s->calls++;
729                 if (ret < 0) {
730                         perror("io_submit");
731                         break;
732                 } else if (ret != to_submit) {
733                         printf("submitted %d, wanted %d\n", ret, to_submit);
734                         break;
735                 }
736                 prepped = 0;
737
738                 while (to_wait) {
739                         int r;
740
741                         s->calls++;
742                         r = io_getevents(s->aio_ctx, to_wait, to_wait, events, NULL);
743                         if (r < 0) {
744                                 perror("io_getevents");
745                                 break;
746                         } else if (r != to_wait) {
747                                 printf("r=%d, wait=%d\n", r, to_wait);
748                                 break;
749                         }
750                         r = reap_events_aio(s, events, r);
751                         s->reaps += r;
752                         to_wait -= r;
753                 }
754         } while (!s->finish);
755
756         free(iocbsptr);
757         free(iocbs);
758         free(events);
759         finish = 1;
760         return NULL;
761 }
762 #endif
763
764 static void *submitter_uring_fn(void *data)
765 {
766         struct submitter *s = data;
767         struct io_sq_ring *ring = &s->sq_ring;
768         int ret, prepped, nr_batch;
769
770         nr_batch = submitter_init(s);
771
772         prepped = 0;
773         do {
774                 int to_wait, to_submit, this_reap, to_prep;
775                 unsigned ring_flags = 0;
776
777                 if (!prepped && s->inflight < depth) {
778                         to_prep = min(depth - s->inflight, batch_submit);
779                         prepped = prep_more_ios_uring(s, to_prep);
780 #ifdef ARCH_HAVE_CPU_CLOCK
781                         if (prepped && stats) {
782                                 s->clock_batch[s->clock_index] = get_cpu_clock();
783                                 s->clock_index = (s->clock_index + 1) & (nr_batch - 1);
784                         }
785 #endif
786                 }
787                 s->inflight += prepped;
788 submit_more:
789                 to_submit = prepped;
790 submit:
791                 if (to_submit && (s->inflight + to_submit <= depth))
792                         to_wait = 0;
793                 else
794                         to_wait = min(s->inflight + to_submit, batch_complete);
795
796                 /*
797                  * Only need to call io_uring_enter if we're not using SQ thread
798                  * poll, or if IORING_SQ_NEED_WAKEUP is set.
799                  */
800                 if (sq_thread_poll)
801                         ring_flags = atomic_load_acquire(ring->flags);
802                 if (!sq_thread_poll || ring_flags & IORING_SQ_NEED_WAKEUP) {
803                         unsigned flags = 0;
804
805                         if (to_wait)
806                                 flags = IORING_ENTER_GETEVENTS;
807                         if (ring_flags & IORING_SQ_NEED_WAKEUP)
808                                 flags |= IORING_ENTER_SQ_WAKEUP;
809                         ret = io_uring_enter(s, to_submit, to_wait, flags);
810                         s->calls++;
811                 } else {
812                         /* for SQPOLL, we submitted it all effectively */
813                         ret = to_submit;
814                 }
815
816                 /*
817                  * For non SQ thread poll, we already got the events we needed
818                  * through the io_uring_enter() above. For SQ thread poll, we
819                  * need to loop here until we find enough events.
820                  */
821                 this_reap = 0;
822                 do {
823                         int r;
824
825                         r = reap_events_uring(s);
826                         if (r == -1) {
827                                 s->finish = 1;
828                                 break;
829                         } else if (r > 0)
830                                 this_reap += r;
831                 } while (sq_thread_poll && this_reap < to_wait);
832                 s->reaps += this_reap;
833
834                 if (ret >= 0) {
835                         if (!ret) {
836                                 to_submit = 0;
837                                 if (s->inflight)
838                                         goto submit;
839                                 continue;
840                         } else if (ret < to_submit) {
841                                 int diff = to_submit - ret;
842
843                                 s->done += ret;
844                                 prepped -= diff;
845                                 goto submit_more;
846                         }
847                         s->done += ret;
848                         prepped = 0;
849                         continue;
850                 } else if (ret < 0) {
851                         if (errno == EAGAIN) {
852                                 if (s->finish)
853                                         break;
854                                 if (this_reap)
855                                         goto submit;
856                                 to_submit = 0;
857                                 goto submit;
858                         }
859                         printf("io_submit: %s\n", strerror(errno));
860                         break;
861                 }
862         } while (!s->finish);
863
864         finish = 1;
865         return NULL;
866 }
867
868 static struct submitter *get_submitter(int offset)
869 {
870         void *ret;
871
872         ret = submitter;
873         if (offset)
874                 ret += offset * (sizeof(*submitter) + depth * sizeof(struct iovec));
875         return ret;
876 }
877
878 static void do_finish(const char *reason)
879 {
880         int j;
881         printf("Exiting on %s\n", reason);
882         for (j = 0; j < nthreads; j++) {
883                 struct submitter *s = get_submitter(j);
884                 s->finish = 1;
885         }
886         finish = 1;
887 }
888
889 static void sig_int(int sig)
890 {
891         do_finish("signal");
892 }
893
894 static void arm_sig_int(void)
895 {
896         struct sigaction act;
897
898         memset(&act, 0, sizeof(act));
899         act.sa_handler = sig_int;
900         act.sa_flags = SA_RESTART;
901         sigaction(SIGINT, &act, NULL);
902
903         /* Windows uses SIGBREAK as a quit signal from other applications */
904 #ifdef WIN32
905         sigaction(SIGBREAK, &act, NULL);
906 #endif
907 }
908
909 static int setup_aio(struct submitter *s)
910 {
911 #ifdef CONFIG_LIBAIO
912         if (polled) {
913                 fprintf(stderr, "aio does not support polled IO\n");
914                 polled = 0;
915         }
916         if (sq_thread_poll) {
917                 fprintf(stderr, "aio does not support SQPOLL IO\n");
918                 sq_thread_poll = 0;
919         }
920         if (do_nop) {
921                 fprintf(stderr, "aio does not support polled IO\n");
922                 do_nop = 0;
923         }
924         if (fixedbufs || register_files) {
925                 fprintf(stderr, "aio does not support registered files or buffers\n");
926                 fixedbufs = register_files = 0;
927         }
928
929         return io_queue_init(depth, &s->aio_ctx);
930 #else
931         fprintf(stderr, "Legacy AIO not available on this system/build\n");
932         errno = EINVAL;
933         return -1;
934 #endif
935 }
936
937 static int setup_ring(struct submitter *s)
938 {
939         struct io_sq_ring *sring = &s->sq_ring;
940         struct io_cq_ring *cring = &s->cq_ring;
941         struct io_uring_params p;
942         int ret, fd;
943         void *ptr;
944
945         memset(&p, 0, sizeof(p));
946
947         if (polled && !do_nop)
948                 p.flags |= IORING_SETUP_IOPOLL;
949         if (sq_thread_poll) {
950                 p.flags |= IORING_SETUP_SQPOLL;
951                 if (sq_thread_cpu != -1) {
952                         p.flags |= IORING_SETUP_SQ_AFF;
953                         p.sq_thread_cpu = sq_thread_cpu;
954                 }
955         }
956
957         fd = io_uring_setup(depth, &p);
958         if (fd < 0) {
959                 perror("io_uring_setup");
960                 return 1;
961         }
962         s->ring_fd = fd;
963
964         io_uring_probe(fd);
965
966         if (fixedbufs) {
967                 struct rlimit rlim;
968
969                 rlim.rlim_cur = RLIM_INFINITY;
970                 rlim.rlim_max = RLIM_INFINITY;
971                 /* ignore potential error, not needed on newer kernels */
972                 setrlimit(RLIMIT_MEMLOCK, &rlim);
973
974                 ret = io_uring_register_buffers(s);
975                 if (ret < 0) {
976                         perror("io_uring_register_buffers");
977                         return 1;
978                 }
979
980                 if (dma_map) {
981                         ret = io_uring_map_buffers(s);
982                         if (ret < 0) {
983                                 perror("io_uring_map_buffers");
984                                 return 1;
985                         }
986                 }
987         }
988
989         if (register_files) {
990                 ret = io_uring_register_files(s);
991                 if (ret < 0) {
992                         perror("io_uring_register_files");
993                         return 1;
994                 }
995         }
996
997         ptr = mmap(0, p.sq_off.array + p.sq_entries * sizeof(__u32),
998                         PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd,
999                         IORING_OFF_SQ_RING);
1000         sring->head = ptr + p.sq_off.head;
1001         sring->tail = ptr + p.sq_off.tail;
1002         sring->ring_mask = ptr + p.sq_off.ring_mask;
1003         sring->ring_entries = ptr + p.sq_off.ring_entries;
1004         sring->flags = ptr + p.sq_off.flags;
1005         sring->array = ptr + p.sq_off.array;
1006         sq_ring_mask = *sring->ring_mask;
1007
1008         s->sqes = mmap(0, p.sq_entries * sizeof(struct io_uring_sqe),
1009                         PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd,
1010                         IORING_OFF_SQES);
1011
1012         ptr = mmap(0, p.cq_off.cqes + p.cq_entries * sizeof(struct io_uring_cqe),
1013                         PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd,
1014                         IORING_OFF_CQ_RING);
1015         cring->head = ptr + p.cq_off.head;
1016         cring->tail = ptr + p.cq_off.tail;
1017         cring->ring_mask = ptr + p.cq_off.ring_mask;
1018         cring->ring_entries = ptr + p.cq_off.ring_entries;
1019         cring->cqes = ptr + p.cq_off.cqes;
1020         cq_ring_mask = *cring->ring_mask;
1021         return 0;
1022 }
1023
1024 static void file_depths(char *buf)
1025 {
1026         bool prev = false;
1027         char *p;
1028         int i, j;
1029
1030         buf[0] = '\0';
1031         p = buf;
1032         for (j = 0; j < nthreads; j++) {
1033                 struct submitter *s = get_submitter(j);
1034
1035                 for (i = 0; i < s->nr_files; i++) {
1036                         struct file *f = &s->files[i];
1037
1038                         if (prev)
1039                                 p += sprintf(p, " %d", f->pending_ios);
1040                         else
1041                                 p += sprintf(p, "%d", f->pending_ios);
1042                         prev = true;
1043                 }
1044         }
1045 }
1046
1047 static void usage(char *argv, int status)
1048 {
1049         char runtime_str[16];
1050         snprintf(runtime_str, sizeof(runtime_str), "%d", runtime);
1051         printf("%s [options] -- [filenames]\n"
1052                 " -d <int>  : IO Depth, default %d\n"
1053                 " -s <int>  : Batch submit, default %d\n"
1054                 " -c <int>  : Batch complete, default %d\n"
1055                 " -b <int>  : Block size, default %d\n"
1056                 " -p <bool> : Polled IO, default %d\n"
1057                 " -B <bool> : Fixed buffers, default %d\n"
1058                 " -R <bool> : DMA map fixed buffers, default %d\n"
1059                 " -F <bool> : Register files, default %d\n"
1060                 " -n <int>  : Number of threads, default %d\n"
1061                 " -O <bool> : Use O_DIRECT, default %d\n"
1062                 " -N <bool> : Perform just no-op requests, default %d\n"
1063                 " -t <bool> : Track IO latencies, default %d\n"
1064                 " -T <int>  : TSC rate in HZ\n"
1065                 " -a <bool> : Use legacy aio, default %d\n"
1066                 " -r <int>  : Runtime in seconds, default %s\n",
1067                 argv, DEPTH, BATCH_SUBMIT, BATCH_COMPLETE, BS, polled,
1068                 fixedbufs, dma_map, register_files, nthreads, !buffered, do_nop,
1069                 stats, aio, runtime == 0 ? "unlimited" : runtime_str);
1070         exit(status);
1071 }
1072
1073 static void read_tsc_rate(void)
1074 {
1075         char buffer[32];
1076         int fd, ret;
1077
1078         if (tsc_rate)
1079                 return;
1080
1081         fd = open(TSC_RATE_FILE, O_RDONLY);
1082         if (fd < 0)
1083                 return;
1084
1085         ret = read(fd, buffer, sizeof(buffer));
1086         if (ret < 0) {
1087                 close(fd);
1088                 return;
1089         }
1090
1091         tsc_rate = strtoul(buffer, NULL, 10);
1092         printf("Using TSC rate %luHz\n", tsc_rate);
1093         close(fd);
1094 }
1095
1096 static void write_tsc_rate(void)
1097 {
1098         char buffer[32];
1099         struct stat sb;
1100         int fd, ret;
1101
1102         if (!stat(TSC_RATE_FILE, &sb))
1103                 return;
1104
1105         fd = open(TSC_RATE_FILE, O_WRONLY | O_CREAT, 0644);
1106         if (fd < 0)
1107                 return;
1108
1109         memset(buffer, 0, sizeof(buffer));
1110         sprintf(buffer, "%lu", tsc_rate);
1111         ret = write(fd, buffer, strlen(buffer));
1112         if (ret < 0)
1113                 perror("write");
1114         close(fd);
1115 }
1116
1117 int main(int argc, char *argv[])
1118 {
1119         struct submitter *s;
1120         unsigned long done, calls, reap;
1121         int err, i, j, flags, fd, opt, threads_per_f, threads_rem = 0, nfiles;
1122         struct file f;
1123         char *fdepths;
1124         void *ret;
1125
1126         if (!do_nop && argc < 2)
1127                 usage(argv[0], 1);
1128
1129         while ((opt = getopt(argc, argv, "d:s:c:b:p:B:F:n:N:O:t:T:a:r:D:h?")) != -1) {
1130                 switch (opt) {
1131                 case 'a':
1132                         aio = !!atoi(optarg);
1133                         break;
1134                 case 'd':
1135                         depth = atoi(optarg);
1136                         break;
1137                 case 's':
1138                         batch_submit = atoi(optarg);
1139                         if (!batch_submit)
1140                                 batch_submit = 1;
1141                         break;
1142                 case 'c':
1143                         batch_complete = atoi(optarg);
1144                         if (!batch_complete)
1145                                 batch_complete = 1;
1146                         break;
1147                 case 'b':
1148                         bs = atoi(optarg);
1149                         break;
1150                 case 'p':
1151                         polled = !!atoi(optarg);
1152                         break;
1153                 case 'B':
1154                         fixedbufs = !!atoi(optarg);
1155                         break;
1156                 case 'F':
1157                         register_files = !!atoi(optarg);
1158                         break;
1159                 case 'n':
1160                         nthreads = atoi(optarg);
1161                         if (!nthreads) {
1162                                 printf("Threads must be non-zero\n");
1163                                 usage(argv[0], 1);
1164                         }
1165                         break;
1166                 case 'N':
1167                         do_nop = !!atoi(optarg);
1168                         break;
1169                 case 'O':
1170                         buffered = !atoi(optarg);
1171                         break;
1172                 case 't':
1173 #ifndef ARCH_HAVE_CPU_CLOCK
1174                         fprintf(stderr, "Stats not supported on this CPU\n");
1175                         return 1;
1176 #endif
1177                         stats = !!atoi(optarg);
1178                         break;
1179                 case 'T':
1180 #ifndef ARCH_HAVE_CPU_CLOCK
1181                         fprintf(stderr, "Stats not supported on this CPU\n");
1182                         return 1;
1183 #endif
1184                         tsc_rate = strtoul(optarg, NULL, 10);
1185                         write_tsc_rate();
1186                         break;
1187                 case 'r':
1188                         runtime = atoi(optarg);
1189                         break;
1190                 case 'D':
1191                         dma_map = !!atoi(optarg);
1192                         break;
1193                 case 'h':
1194                 case '?':
1195                 default:
1196                         usage(argv[0], 0);
1197                         break;
1198                 }
1199         }
1200
1201         if (stats)
1202                 read_tsc_rate();
1203
1204         if (batch_complete > depth)
1205                 batch_complete = depth;
1206         if (batch_submit > depth)
1207                 batch_submit = depth;
1208         if (!fixedbufs && dma_map)
1209                 dma_map = 0;
1210
1211         submitter = calloc(nthreads, sizeof(*submitter) +
1212                                 depth * sizeof(struct iovec));
1213         for (j = 0; j < nthreads; j++) {
1214                 s = get_submitter(j);
1215                 s->index = j;
1216                 s->done = s->calls = s->reaps = 0;
1217         }
1218
1219         flags = O_RDONLY | O_NOATIME;
1220         if (!buffered)
1221                 flags |= O_DIRECT;
1222
1223         j = 0;
1224         i = optind;
1225         nfiles = argc - i;
1226         if (!do_nop) {
1227                 if (!nfiles) {
1228                         printf("No files specified\n");
1229                         usage(argv[0], 1);
1230                 }
1231                 threads_per_f = nthreads / nfiles;
1232                 /* make sure each thread gets assigned files */
1233                 if (threads_per_f == 0) {
1234                         threads_per_f = 1;
1235                 } else {
1236                         threads_rem = nthreads - threads_per_f * nfiles;
1237                 }
1238         }
1239         while (!do_nop && i < argc) {
1240                 int k, limit;
1241
1242                 memset(&f, 0, sizeof(f));
1243
1244                 fd = open(argv[i], flags);
1245                 if (fd < 0) {
1246                         perror("open");
1247                         return 1;
1248                 }
1249                 f.real_fd = fd;
1250                 if (get_file_size(&f)) {
1251                         printf("failed getting size of device/file\n");
1252                         return 1;
1253                 }
1254                 if (f.max_blocks <= 1) {
1255                         printf("Zero file/device size?\n");
1256                         return 1;
1257                 }
1258                 f.max_blocks--;
1259
1260                 limit = threads_per_f;
1261                 limit += threads_rem > 0 ? 1 : 0;
1262                 for (k = 0; k < limit; k++) {
1263                         s = get_submitter((j + k) % nthreads);
1264
1265                         if (s->nr_files == MAX_FDS) {
1266                                 printf("Max number of files (%d) reached\n", MAX_FDS);
1267                                 break;
1268                         }
1269
1270                         memcpy(&s->files[s->nr_files], &f, sizeof(f));
1271
1272                         printf("Added file %s (submitter %d)\n", argv[i], s->index);
1273                         s->nr_files++;
1274                 }
1275                 threads_rem--;
1276                 i++;
1277                 j += limit;
1278         }
1279
1280         arm_sig_int();
1281
1282         for (j = 0; j < nthreads; j++) {
1283                 s = get_submitter(j);
1284                 for (i = 0; i < depth; i++) {
1285                         void *buf;
1286
1287                         if (posix_memalign(&buf, bs, bs)) {
1288                                 printf("failed alloc\n");
1289                                 return 1;
1290                         }
1291                         s->iovecs[i].iov_base = buf;
1292                         s->iovecs[i].iov_len = bs;
1293                 }
1294         }
1295
1296         for (j = 0; j < nthreads; j++) {
1297                 s = get_submitter(j);
1298
1299                 if (!aio)
1300                         err = setup_ring(s);
1301                 else
1302                         err = setup_aio(s);
1303                 if (err) {
1304                         printf("ring setup failed: %s, %d\n", strerror(errno), err);
1305                         return 1;
1306                 }
1307         }
1308         s = get_submitter(0);
1309         printf("polled=%d, fixedbufs=%d/%d, register_files=%d, buffered=%d, QD=%d\n", polled, fixedbufs, dma_map, register_files, buffered, depth);
1310         if (!aio)
1311                 printf("Engine=io_uring, sq_ring=%d, cq_ring=%d\n", *s->sq_ring.ring_entries, *s->cq_ring.ring_entries);
1312         else
1313                 printf("Engine=aio\n");
1314
1315         for (j = 0; j < nthreads; j++) {
1316                 s = get_submitter(j);
1317                 if (!aio)
1318                         pthread_create(&s->thread, NULL, submitter_uring_fn, s);
1319 #ifdef CONFIG_LIBAIO
1320                 else
1321                         pthread_create(&s->thread, NULL, submitter_aio_fn, s);
1322 #endif
1323         }
1324
1325         fdepths = malloc(8 * s->nr_files * nthreads);
1326         reap = calls = done = 0;
1327         do {
1328                 unsigned long this_done = 0;
1329                 unsigned long this_reap = 0;
1330                 unsigned long this_call = 0;
1331                 unsigned long rpc = 0, ipc = 0;
1332                 unsigned long iops, bw;
1333
1334                 sleep(1);
1335                 if (runtime && !--runtime)
1336                         do_finish("timeout");
1337
1338                 /* don't print partial run, if interrupted by signal */
1339                 if (finish)
1340                         break;
1341
1342                 /* one second in to the run, enable stats */
1343                 if (stats)
1344                         stats_running = 1;
1345
1346                 for (j = 0; j < nthreads; j++) {
1347                         this_done += s->done;
1348                         this_call += s->calls;
1349                         this_reap += s->reaps;
1350                 }
1351                 if (this_call - calls) {
1352                         rpc = (this_done - done) / (this_call - calls);
1353                         ipc = (this_reap - reap) / (this_call - calls);
1354                 } else
1355                         rpc = ipc = -1;
1356                 file_depths(fdepths);
1357                 iops = this_done - done;
1358                 if (bs > 1048576)
1359                         bw = iops * (bs / 1048576);
1360                 else
1361                         bw = iops / (1048576 / bs);
1362                 if (iops > 100000)
1363                         printf("IOPS=%luK, ", iops / 1000);
1364                 else
1365                         printf("IOPS=%luK, ", iops);
1366                 if (!do_nop)
1367                         printf("BW=%luMiB/s, ", bw);
1368                 printf("IOS/call=%ld/%ld, inflight=(%s)\n", rpc, ipc, fdepths);
1369                 done = this_done;
1370                 calls = this_call;
1371                 reap = this_reap;
1372         } while (!finish);
1373
1374         for (j = 0; j < nthreads; j++) {
1375                 s = get_submitter(j);
1376                 pthread_join(s->thread, &ret);
1377                 close(s->ring_fd);
1378
1379                 if (stats) {
1380                         unsigned long nr;
1381
1382                         printf("%d: Latency percentiles:\n", s->tid);
1383                         for (i = 0, nr = 0; i < PLAT_NR; i++)
1384                                 nr += s->plat[i];
1385                         show_clat_percentiles(s->plat, nr, 4);
1386                         free(s->clock_batch);
1387                         free(s->plat);
1388                 }
1389         }
1390
1391         free(fdepths);
1392         free(submitter);
1393         return 0;
1394 }