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