ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/libev/ev_iouring.c
Revision: 1.11
Committed: Fri Dec 27 21:56:29 2019 UTC (4 years, 4 months ago) by root
Content type: text/plain
Branch: MAIN
Changes since 1.10: +7 -2 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 /*
2 * libev linux io_uring fd activity backend
3 *
4 * Copyright (c) 2019 Marc Alexander Lehmann <libev@schmorp.de>
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without modifica-
8 * tion, are permitted provided that the following conditions are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright notice,
11 * this list of conditions and the following disclaimer.
12 *
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
18 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
19 * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
20 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
21 * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
23 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
24 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
25 * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
26 * OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Alternatively, the contents of this file may be used under the terms of
29 * the GNU General Public License ("GPL") version 2 or any later version,
30 * in which case the provisions of the GPL are applicable instead of
31 * the above. If you wish to allow the use of your version of this file
32 * only under the terms of the GPL and not to allow others to use your
33 * version of this file under the BSD license, indicate your decision
34 * by deleting the provisions above and replace them with the notice
35 * and other provisions required by the GPL. If you do not delete the
36 * provisions above, a recipient may use your version of this file under
37 * either the BSD or the GPL.
38 */
39
40 /*
41 * general notes about linux io_uring:
42 *
43 * a) it's the best interface I have seen so far. on linux.
44 * b) best is not necessarily very good.
45 * c) it's better than the aio mess, doesn't suffer from the fork problems
46 * of linux aio or epoll and so on and so on. and you could do event stuff
47 * without any syscalls. what's not to like?
48 * d) ok, it's vastly more complex, but that's ok, really.
49 * e) why 3 mmaps instead of one? one would be more space-efficient,
50 * and I can't see what benefit three would have (other than being
51 * somehow resizable/relocatable, but that's apparently not possible).
52 * (FIXME: newer kernels can use 2 mmaps only, need to look into this).
53 * f) hmm, it's practiclaly undebuggable (gdb can't access the memory, and
54 * the bizarre way structure offsets are communicated makes it hard to
55 * just print the ring buffer heads, even *iff* the memory were visible
56 * in gdb. but then, that's also ok, really.
57 * g) well, you cannot specify a timeout when waiting for events. no,
58 * seriously, the interface doesn't support a timeout. never seen _that_
59 * before. sure, you can use a timerfd, but that's another syscall
60 * you could have avoided. overall, this bizarre omission smells
61 * like a ยต-optimisation by the io_uring author for his personal
62 * applications, to the detriment of everybody else who just wants
63 * an event loop. but, umm, ok, if that's all, it could be worse.
64 * (FIXME: jens mentioned timeout commands, need to investigate)
65 * h) there is a hardcoded limit of 4096 outstanding events. okay,
66 * at least there is no arbitrary low system-wide limit...
67 * (FIXME: apparently, this was increased to 32768 in later kernels(
68 * i) unlike linux aio, you *can* register more then the limit
69 * of fd events, and the kernel will "gracefully" signal an
70 * overflow, after which you could destroy and recreate the kernel
71 * state, a bit bigger, or fall back to e.g. poll. thats not
72 * totally insane, but kind of questions the point a high
73 * performance I/O framework when it doesn't really work
74 * under stress.
75 * (FIXME: iouring should no longer drop events, need to investigate)
76 * j) but, oh my! is has exactly the same bugs as the linux aio backend,
77 * where some undocumented poll combinations just fail.
78 * so we need epoll AGAIN as a fallback. AGAIN! epoll!! and of course,
79 * this is completely undocumented, have I mantioned this already?
80 * k) overall, the *API* itself is, I dare to say, not a total trainwreck.
81 * the big isuess with it are the bugs requiring epoll, which might
82 * or might not get fixed (do I hold my breath?).
83 */
84
85 /* TODO: use internal TIMEOUT */
86 /* TODO: take advantage of single mmap, NODROP etc. */
87 /* TODO: resize cq/sq size independently */
88
89 #include <sys/timerfd.h>
90 #include <sys/mman.h>
91 #include <poll.h>
92
93 #define IOURING_INIT_ENTRIES 32
94
95 /*****************************************************************************/
96 /* syscall wrapdadoop - this section has the raw api/abi definitions */
97
98 #include <linux/fs.h>
99 #include <linux/types.h>
100
101 /* mostly directly taken from the kernel or documentation */
102
103 struct io_uring_sqe
104 {
105 __u8 opcode;
106 __u8 flags;
107 __u16 ioprio;
108 __s32 fd;
109 union {
110 __u64 off;
111 __u64 addr2;
112 };
113 __u64 addr;
114 __u32 len;
115 union {
116 __kernel_rwf_t rw_flags;
117 __u32 fsync_flags;
118 __u16 poll_events;
119 __u32 sync_range_flags;
120 __u32 msg_flags;
121 __u32 timeout_flags;
122 __u32 accept_flags;
123 __u32 cancel_flags;
124 __u32 open_flags;
125 __u32 statx_flags;
126 };
127 __u64 user_data;
128 union {
129 __u16 buf_index;
130 __u64 __pad2[3];
131 };
132 };
133
134 struct io_uring_cqe
135 {
136 __u64 user_data;
137 __s32 res;
138 __u32 flags;
139 };
140
141 struct io_sqring_offsets
142 {
143 __u32 head;
144 __u32 tail;
145 __u32 ring_mask;
146 __u32 ring_entries;
147 __u32 flags;
148 __u32 dropped;
149 __u32 array;
150 __u32 resv1;
151 __u64 resv2;
152 };
153
154 struct io_cqring_offsets
155 {
156 __u32 head;
157 __u32 tail;
158 __u32 ring_mask;
159 __u32 ring_entries;
160 __u32 overflow;
161 __u32 cqes;
162 __u64 resv[2];
163 };
164
165 struct io_uring_params
166 {
167 __u32 sq_entries;
168 __u32 cq_entries;
169 __u32 flags;
170 __u32 sq_thread_cpu;
171 __u32 sq_thread_idle;
172 __u32 features;
173 __u32 resv[4];
174 struct io_sqring_offsets sq_off;
175 struct io_cqring_offsets cq_off;
176 };
177
178 #define IORING_OP_POLL_ADD 6
179 #define IORING_OP_POLL_REMOVE 7
180
181 #define IORING_ENTER_GETEVENTS 0x01
182
183 #define IORING_OFF_SQ_RING 0x00000000ULL
184 #define IORING_OFF_CQ_RING 0x08000000ULL
185 #define IORING_OFF_SQES 0x10000000ULL
186
187 #define IORING_FEAT_SINGLE_MMAP 0x1
188 #define IORING_FEAT_NODROP 0x2
189 #define IORING_FEAT_SUBMIT_STABLE 0x4
190
191 inline_size
192 int
193 evsys_io_uring_setup (unsigned entries, struct io_uring_params *params)
194 {
195 return ev_syscall2 (SYS_io_uring_setup, entries, params);
196 }
197
198 inline_size
199 int
200 evsys_io_uring_enter (int fd, unsigned to_submit, unsigned min_complete, unsigned flags, const sigset_t *sig, size_t sigsz)
201 {
202 return ev_syscall6 (SYS_io_uring_enter, fd, to_submit, min_complete, flags, sig, sigsz);
203 }
204
205 /*****************************************************************************/
206 /* actual backed implementation */
207
208 /* we hope that volatile will make the compiler access this variables only once */
209 #define EV_SQ_VAR(name) *(volatile unsigned *)((char *)iouring_sq_ring + iouring_sq_ ## name)
210 #define EV_CQ_VAR(name) *(volatile unsigned *)((char *)iouring_cq_ring + iouring_cq_ ## name)
211
212 /* the index array */
213 #define EV_SQ_ARRAY ((unsigned *)((char *)iouring_sq_ring + iouring_sq_array))
214
215 /* the submit/completion queue entries */
216 #define EV_SQES ((struct io_uring_sqe *) iouring_sqes)
217 #define EV_CQES ((struct io_uring_cqe *)((char *)iouring_cq_ring + iouring_cq_cqes))
218
219 static
220 struct io_uring_sqe *
221 iouring_sqe_get (EV_P)
222 {
223 unsigned tail = EV_SQ_VAR (tail);
224
225 if (tail + 1 - EV_SQ_VAR (head) > EV_SQ_VAR (ring_entries))
226 {
227 /* queue full, flush */
228 evsys_io_uring_enter (iouring_fd, iouring_to_submit, 0, 0, 0, 0);
229 iouring_to_submit = 0;
230 }
231
232 assert (("libev: io_uring queue full after flush", tail + 1 - EV_SQ_VAR (head) <= EV_SQ_VAR (ring_entries)));
233
234 return EV_SQES + (tail & EV_SQ_VAR (ring_mask));
235 }
236
237 inline_size
238 struct io_uring_sqe *
239 iouring_sqe_submit (EV_P_ struct io_uring_sqe *sqe)
240 {
241 unsigned idx = sqe - EV_SQES;
242
243 EV_SQ_ARRAY [idx] = idx;
244 ECB_MEMORY_FENCE_RELEASE;
245 ++EV_SQ_VAR (tail);
246 /*ECB_MEMORY_FENCE_RELEASE; /* for the time being we assume this is not needed */
247 ++iouring_to_submit;
248 }
249
250 /*****************************************************************************/
251
252 /* when the timerfd expires we simply note the fact,
253 * as the purpose of the timerfd is to wake us up, nothing else.
254 * the next iteration should re-set it.
255 */
256 static void
257 iouring_tfd_cb (EV_P_ struct ev_io *w, int revents)
258 {
259 iouring_tfd_to = EV_TSTAMP_HUGE;
260 }
261
262 /* called for full and partial cleanup */
263 ecb_cold
264 static int
265 iouring_internal_destroy (EV_P)
266 {
267 close (iouring_tfd);
268 close (iouring_fd);
269
270 if (iouring_sq_ring != MAP_FAILED) munmap (iouring_sq_ring, iouring_sq_ring_size);
271 if (iouring_cq_ring != MAP_FAILED) munmap (iouring_cq_ring, iouring_cq_ring_size);
272 if (iouring_sqes != MAP_FAILED) munmap (iouring_sqes , iouring_sqes_size );
273
274 if (ev_is_active (&iouring_tfd_w))
275 {
276 ev_ref (EV_A);
277 ev_io_stop (EV_A_ &iouring_tfd_w);
278 }
279 }
280
281 ecb_cold
282 static int
283 iouring_internal_init (EV_P)
284 {
285 struct io_uring_params params = { 0 };
286
287 iouring_to_submit = 0;
288
289 iouring_tfd = -1;
290 iouring_sq_ring = MAP_FAILED;
291 iouring_cq_ring = MAP_FAILED;
292 iouring_sqes = MAP_FAILED;
293
294 for (;;)
295 {
296 iouring_fd = evsys_io_uring_setup (iouring_entries, &params);
297
298 if (iouring_fd >= 0)
299 break; /* yippie */
300
301 if (errno != EINVAL)
302 return -1; /* we failed */
303
304 #if TODO
305 if ((~params.features) & (IORING_FEAT_NODROP | IORING_FEATURE_SINGLE_MMAP))
306 return -1; /* we require the above features */
307 #endif
308
309 /* EINVAL: lots of possible reasons, but maybe
310 * it is because we hit the unqueryable hardcoded size limit
311 */
312
313 /* we hit the limit already, give up */
314 if (iouring_max_entries)
315 return -1;
316
317 /* first time we hit EINVAL? assume we hit the limit, so go back and retry */
318 iouring_entries >>= 1;
319 iouring_max_entries = iouring_entries;
320 }
321
322 iouring_sq_ring_size = params.sq_off.array + params.sq_entries * sizeof (unsigned);
323 iouring_cq_ring_size = params.cq_off.cqes + params.cq_entries * sizeof (struct io_uring_cqe);
324 iouring_sqes_size = params.sq_entries * sizeof (struct io_uring_sqe);
325
326 iouring_sq_ring = mmap (0, iouring_sq_ring_size, PROT_READ | PROT_WRITE,
327 MAP_SHARED | MAP_POPULATE, iouring_fd, IORING_OFF_SQ_RING);
328 iouring_cq_ring = mmap (0, iouring_cq_ring_size, PROT_READ | PROT_WRITE,
329 MAP_SHARED | MAP_POPULATE, iouring_fd, IORING_OFF_CQ_RING);
330 iouring_sqes = mmap (0, iouring_sqes_size, PROT_READ | PROT_WRITE,
331 MAP_SHARED | MAP_POPULATE, iouring_fd, IORING_OFF_SQES);
332
333 if (iouring_sq_ring == MAP_FAILED || iouring_cq_ring == MAP_FAILED || iouring_sqes == MAP_FAILED)
334 return -1;
335
336 iouring_sq_head = params.sq_off.head;
337 iouring_sq_tail = params.sq_off.tail;
338 iouring_sq_ring_mask = params.sq_off.ring_mask;
339 iouring_sq_ring_entries = params.sq_off.ring_entries;
340 iouring_sq_flags = params.sq_off.flags;
341 iouring_sq_dropped = params.sq_off.dropped;
342 iouring_sq_array = params.sq_off.array;
343
344 iouring_cq_head = params.cq_off.head;
345 iouring_cq_tail = params.cq_off.tail;
346 iouring_cq_ring_mask = params.cq_off.ring_mask;
347 iouring_cq_ring_entries = params.cq_off.ring_entries;
348 iouring_cq_overflow = params.cq_off.overflow;
349 iouring_cq_cqes = params.cq_off.cqes;
350
351 iouring_tfd = timerfd_create (CLOCK_MONOTONIC, TFD_CLOEXEC);
352
353 if (iouring_tfd < 0)
354 return iouring_tfd;
355
356 iouring_tfd_to = EV_TSTAMP_HUGE;
357
358 return 0;
359 }
360
361 ecb_cold
362 static void
363 iouring_fork (EV_P)
364 {
365 iouring_internal_destroy (EV_A);
366
367 while (iouring_internal_init (EV_A) < 0)
368 ev_syserr ("(libev) io_uring_setup");
369
370 fd_rearm_all (EV_A);
371
372 ev_io_stop (EV_A_ &iouring_tfd_w);
373 ev_io_set (EV_A_ &iouring_tfd_w, iouring_tfd, EV_READ);
374 ev_io_start (EV_A_ &iouring_tfd_w);
375 }
376
377 /*****************************************************************************/
378
379 static void
380 iouring_modify (EV_P_ int fd, int oev, int nev)
381 {
382 if (oev)
383 {
384 /* we assume the sqe's are all "properly" initialised */
385 struct io_uring_sqe *sqe = iouring_sqe_get (EV_A);
386 sqe->opcode = IORING_OP_POLL_REMOVE;
387 sqe->fd = fd;
388 sqe->user_data = -1;
389 iouring_sqe_submit (EV_A_ sqe);
390
391 /* increment generation counter to avoid handling old events */
392 ++anfds [fd].egen;
393 }
394
395 if (nev)
396 {
397 struct io_uring_sqe *sqe = iouring_sqe_get (EV_A);
398 sqe->opcode = IORING_OP_POLL_ADD;
399 sqe->fd = fd;
400 sqe->user_data = (uint32_t)fd | ((__u64)(uint32_t)anfds [fd].egen << 32);
401 sqe->poll_events =
402 (nev & EV_READ ? POLLIN : 0)
403 | (nev & EV_WRITE ? POLLOUT : 0);
404 iouring_sqe_submit (EV_A_ sqe);
405 }
406 }
407
408 inline_size
409 void
410 iouring_tfd_update (EV_P_ ev_tstamp timeout)
411 {
412 ev_tstamp tfd_to = mn_now + timeout;
413
414 /* we assume there will be many iterations per timer change, so
415 * we only re-set the timerfd when we have to because its expiry
416 * is too late.
417 */
418 if (ecb_expect_false (tfd_to < iouring_tfd_to))
419 {
420 struct itimerspec its;
421
422 iouring_tfd_to = tfd_to;
423 EV_TS_SET (its.it_interval, 0.);
424 EV_TS_SET (its.it_value, tfd_to);
425
426 if (timerfd_settime (iouring_tfd, TFD_TIMER_ABSTIME, &its, 0) < 0)
427 assert (("libev: iouring timerfd_settime failed", 0));
428 }
429 }
430
431 inline_size
432 void
433 iouring_process_cqe (EV_P_ struct io_uring_cqe *cqe)
434 {
435 int fd = cqe->user_data & 0xffffffffU;
436 uint32_t gen = cqe->user_data >> 32;
437 int res = cqe->res;
438
439 /* ignore fd removal events, if there are any. TODO: verify */
440 /* TODO: yes, this triggers */
441 if (cqe->user_data == (__u64)-1)
442 return;
443
444 assert (("libev: io_uring fd must be in-bounds", fd >= 0 && fd < anfdmax));
445
446 /* documentation lies, of course. the result value is NOT like
447 * normal syscalls, but like linux raw syscalls, i.e. negative
448 * error numbers. fortunate, as otherwise there would be no way
449 * to get error codes at all. still, why not document this?
450 */
451
452 /* ignore event if generation doesn't match */
453 /* this should actually be very rare */
454 if (ecb_expect_false (gen != (uint32_t)anfds [fd].egen))
455 return;
456
457 if (ecb_expect_false (res < 0))
458 {
459 /*TODO: EINVAL handling (was something failed with this fd)*/
460 /*TODO: EBUSY happens when?*/
461
462 if (res == -EBADF)
463 {
464 assert (("libev: event loop rejected bad fd", res != -EBADF));
465 fd_kill (EV_A_ fd);
466 }
467 else
468 {
469 errno = -res;
470 ev_syserr ("(libev) IORING_OP_POLL_ADD");
471 }
472
473 return;
474 }
475
476 /* feed events, we do not expect or handle POLLNVAL */
477 fd_event (
478 EV_A_
479 fd,
480 (res & (POLLOUT | POLLERR | POLLHUP) ? EV_WRITE : 0)
481 | (res & (POLLIN | POLLERR | POLLHUP) ? EV_READ : 0)
482 );
483
484 /* io_uring is oneshot, so we need to re-arm the fd next iteration */
485 /* this also means we usually have to do at least one syscall per iteration */
486 anfds [fd].events = 0;
487 fd_change (EV_A_ fd, EV_ANFD_REIFY);
488 }
489
490 /* called when the event queue overflows */
491 ecb_cold
492 static void
493 iouring_overflow (EV_P)
494 {
495 /* we have two options, resize the queue (by tearing down
496 * everything and recreating it, or living with it
497 * and polling.
498 * we implement this by resizing the queue, and, if that fails,
499 * we just recreate the state on every failure, which
500 * kind of is a very inefficient poll.
501 * one danger is, due to the bios toward lower fds,
502 * we will only really get events for those, so
503 * maybe we need a poll() fallback, after all.
504 */
505 /*EV_CQ_VAR (overflow) = 0;*/ /* need to do this if we keep the state and poll manually */
506
507 fd_rearm_all (EV_A);
508
509 /* we double the size until we hit the hard-to-probe maximum */
510 if (!iouring_max_entries)
511 {
512 iouring_entries <<= 1;
513 iouring_fork (EV_A);
514 }
515 else
516 {
517 /* we hit the kernel limit, we should fall back to something else.
518 * we can either poll() a few times and hope for the best,
519 * poll always, or switch to epoll.
520 * TODO: is this necessary with newer kernels?
521 */
522
523 iouring_internal_destroy (EV_A);
524
525 /* this should make it so that on return, we don't call any uring functions */
526 iouring_to_submit = 0;
527
528 for (;;)
529 {
530 backend = epoll_init (EV_A_ 0);
531
532 if (backend)
533 break;
534
535 ev_syserr ("(libev) iouring switch to epoll");
536 }
537 }
538 }
539
540 /* handle any events in the completion queue, return true if there were any */
541 static int
542 iouring_handle_cq (EV_P)
543 {
544 unsigned head, tail, mask;
545
546 head = EV_CQ_VAR (head);
547 ECB_MEMORY_FENCE_ACQUIRE;
548 tail = EV_CQ_VAR (tail);
549
550 if (head == tail)
551 return 0;
552
553 /* it can only overflow if we have events, yes, yes? */
554 if (ecb_expect_false (EV_CQ_VAR (overflow)))
555 {
556 iouring_overflow (EV_A);
557 return 1;
558 }
559
560 mask = EV_CQ_VAR (ring_mask);
561
562 do
563 iouring_process_cqe (EV_A_ &EV_CQES [head++ & mask]);
564 while (head != tail);
565
566 EV_CQ_VAR (head) = head;
567 ECB_MEMORY_FENCE_RELEASE;
568
569 return 1;
570 }
571
572 static void
573 iouring_poll (EV_P_ ev_tstamp timeout)
574 {
575 /* if we have events, no need for extra syscalls, but we might have to queue events */
576 if (iouring_handle_cq (EV_A))
577 timeout = EV_TS_CONST (0.);
578 else
579 /* no events, so maybe wait for some */
580 iouring_tfd_update (EV_A_ timeout);
581
582 /* only enter the kernel if we have something to submit, or we need to wait */
583 if (timeout || iouring_to_submit)
584 {
585 int res;
586
587 EV_RELEASE_CB;
588
589 res = evsys_io_uring_enter (iouring_fd, iouring_to_submit, 1,
590 timeout > EV_TS_CONST (0.) ? IORING_ENTER_GETEVENTS : 0, 0, 0);
591 iouring_to_submit = 0;
592
593 EV_ACQUIRE_CB;
594
595 if (ecb_expect_false (res < 0))
596 if (errno == EINTR)
597 /* ignore */;
598 else
599 ev_syserr ("(libev) iouring setup");
600 else
601 iouring_handle_cq (EV_A);
602 }
603 }
604
605 inline_size
606 int
607 iouring_init (EV_P_ int flags)
608 {
609 iouring_entries = IOURING_INIT_ENTRIES;
610 iouring_max_entries = 0;
611
612 if (iouring_internal_init (EV_A) < 0)
613 {
614 iouring_internal_destroy (EV_A);
615 return 0;
616 }
617
618 ev_io_init (&iouring_tfd_w, iouring_tfd_cb, iouring_tfd, EV_READ);
619 ev_set_priority (&iouring_tfd_w, EV_MINPRI);
620 ev_io_start (EV_A_ &iouring_tfd_w);
621 ev_unref (EV_A); /* watcher should not keep loop alive */
622
623 backend_modify = iouring_modify;
624 backend_poll = iouring_poll;
625
626 return EVBACKEND_IOURING;
627 }
628
629 inline_size
630 void
631 iouring_destroy (EV_P)
632 {
633 iouring_internal_destroy (EV_A);
634 }
635