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