Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

ev_iouring.c 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. /*
  2. * libev linux io_uring fd activity backend
  3. *
  4. * Copyright (c) 2019-2020 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. * general notes about linux io_uring:
  41. *
  42. * a) it's the best interface I have seen so far. on linux.
  43. * b) best is not necessarily very good.
  44. * c) it's better than the aio mess, doesn't suffer from the fork problems
  45. * of linux aio or epoll and so on and so on. and you could do event stuff
  46. * without any syscalls. what's not to like?
  47. * d) ok, it's vastly more complex, but that's ok, really.
  48. * e) why two mmaps instead of one? one would be more space-efficient,
  49. * and I can't see what benefit two would have (other than being
  50. * somehow resizable/relocatable, but that's apparently not possible).
  51. * f) hmm, it's practically undebuggable (gdb can't access the memory, and
  52. * the bizarre way structure offsets are communicated makes it hard to
  53. * just print the ring buffer heads, even *iff* the memory were visible
  54. * in gdb. but then, that's also ok, really.
  55. * g) well, you cannot specify a timeout when waiting for events. no,
  56. * seriously, the interface doesn't support a timeout. never seen _that_
  57. * before. sure, you can use a timerfd, but that's another syscall
  58. * you could have avoided. overall, this bizarre omission smells
  59. * like a µ-optimisation by the io_uring author for his personal
  60. * applications, to the detriment of everybody else who just wants
  61. * an event loop. but, umm, ok, if that's all, it could be worse.
  62. * (from what I gather from the author Jens Axboe, it simply didn't
  63. * occur to him, and he made good on it by adding an unlimited nuber
  64. * of timeouts later :).
  65. * h) initially there was a hardcoded limit of 4096 outstanding events.
  66. * later versions not only bump this to 32k, but also can handle
  67. * an unlimited amount of events, so this only affects the batch size.
  68. * i) unlike linux aio, you *can* register more then the limit
  69. * of fd events. while early verisons of io_uring signalled an overflow
  70. * and you ended up getting wet. 5.5+ does not do this anymore.
  71. * j) but, oh my! it had exactly the same bugs as the linux aio backend,
  72. * where some undocumented poll combinations just fail. fortunately,
  73. * after finally reaching the author, he was more than willing to fix
  74. * this probably in 5.6+.
  75. * k) overall, the *API* itself is, I dare to say, not a total trainwreck.
  76. * once the bugs ae fixed (probably in 5.6+), it will be without
  77. * competition.
  78. */
  79. /* TODO: use internal TIMEOUT */
  80. /* TODO: take advantage of single mmap, NODROP etc. */
  81. /* TODO: resize cq/sq size independently */
  82. #include <sys/timerfd.h>
  83. #include <sys/mman.h>
  84. #include <poll.h>
  85. #include <stdint.h>
  86. #define IOURING_INIT_ENTRIES 32
  87. /*****************************************************************************/
  88. /* syscall wrapdadoop - this section has the raw api/abi definitions */
  89. #include <linux/fs.h>
  90. #include <linux/types.h>
  91. /* mostly directly taken from the kernel or documentation */
  92. struct io_uring_sqe
  93. {
  94. __u8 opcode;
  95. __u8 flags;
  96. __u16 ioprio;
  97. __s32 fd;
  98. union {
  99. __u64 off;
  100. __u64 addr2;
  101. };
  102. __u64 addr;
  103. __u32 len;
  104. union {
  105. __kernel_rwf_t rw_flags;
  106. __u32 fsync_flags;
  107. __u16 poll_events;
  108. __u32 sync_range_flags;
  109. __u32 msg_flags;
  110. __u32 timeout_flags;
  111. __u32 accept_flags;
  112. __u32 cancel_flags;
  113. __u32 open_flags;
  114. __u32 statx_flags;
  115. };
  116. __u64 user_data;
  117. union {
  118. __u16 buf_index;
  119. __u64 __pad2[3];
  120. };
  121. };
  122. struct io_uring_cqe
  123. {
  124. __u64 user_data;
  125. __s32 res;
  126. __u32 flags;
  127. };
  128. struct io_sqring_offsets
  129. {
  130. __u32 head;
  131. __u32 tail;
  132. __u32 ring_mask;
  133. __u32 ring_entries;
  134. __u32 flags;
  135. __u32 dropped;
  136. __u32 array;
  137. __u32 resv1;
  138. __u64 resv2;
  139. };
  140. struct io_cqring_offsets
  141. {
  142. __u32 head;
  143. __u32 tail;
  144. __u32 ring_mask;
  145. __u32 ring_entries;
  146. __u32 overflow;
  147. __u32 cqes;
  148. __u64 resv[2];
  149. };
  150. struct io_uring_params
  151. {
  152. __u32 sq_entries;
  153. __u32 cq_entries;
  154. __u32 flags;
  155. __u32 sq_thread_cpu;
  156. __u32 sq_thread_idle;
  157. __u32 features;
  158. __u32 resv[4];
  159. struct io_sqring_offsets sq_off;
  160. struct io_cqring_offsets cq_off;
  161. };
  162. #define IORING_SETUP_CQSIZE 0x00000008
  163. #define IORING_OP_POLL_ADD 6
  164. #define IORING_OP_POLL_REMOVE 7
  165. #define IORING_OP_TIMEOUT 11
  166. #define IORING_OP_TIMEOUT_REMOVE 12
  167. /* relative or absolute, reference clock is CLOCK_MONOTONIC */
  168. struct iouring_kernel_timespec
  169. {
  170. int64_t tv_sec;
  171. long long tv_nsec;
  172. };
  173. #define IORING_TIMEOUT_ABS 0x00000001
  174. #define IORING_ENTER_GETEVENTS 0x01
  175. #define IORING_OFF_SQ_RING 0x00000000ULL
  176. #define IORING_OFF_CQ_RING 0x08000000ULL
  177. #define IORING_OFF_SQES 0x10000000ULL
  178. #define IORING_FEAT_SINGLE_MMAP 0x00000001
  179. #define IORING_FEAT_NODROP 0x00000002
  180. #define IORING_FEAT_SUBMIT_STABLE 0x00000004
  181. inline_size
  182. int
  183. evsys_io_uring_setup (unsigned entries, struct io_uring_params *params)
  184. {
  185. return ev_syscall2 (SYS_io_uring_setup, entries, params);
  186. }
  187. inline_size
  188. int
  189. evsys_io_uring_enter (int fd, unsigned to_submit, unsigned min_complete, unsigned flags, const sigset_t *sig, size_t sigsz)
  190. {
  191. return ev_syscall6 (SYS_io_uring_enter, fd, to_submit, min_complete, flags, sig, sigsz);
  192. }
  193. /*****************************************************************************/
  194. /* actual backed implementation */
  195. /* we hope that volatile will make the compiler access this variables only once */
  196. #define EV_SQ_VAR(name) *(volatile unsigned *)((char *)iouring_sq_ring + iouring_sq_ ## name)
  197. #define EV_CQ_VAR(name) *(volatile unsigned *)((char *)iouring_cq_ring + iouring_cq_ ## name)
  198. /* the index array */
  199. #define EV_SQ_ARRAY ((unsigned *)((char *)iouring_sq_ring + iouring_sq_array))
  200. /* the submit/completion queue entries */
  201. #define EV_SQES ((struct io_uring_sqe *) iouring_sqes)
  202. #define EV_CQES ((struct io_uring_cqe *)((char *)iouring_cq_ring + iouring_cq_cqes))
  203. inline_speed
  204. int
  205. iouring_enter (EV_P_ ev_tstamp timeout)
  206. {
  207. int res;
  208. EV_RELEASE_CB;
  209. res = evsys_io_uring_enter (iouring_fd, iouring_to_submit, 1,
  210. timeout > EV_TS_CONST (0.) ? IORING_ENTER_GETEVENTS : 0, 0, 0);
  211. assert (("libev: io_uring_enter did not consume all sqes", (res < 0 || res == iouring_to_submit)));
  212. iouring_to_submit = 0;
  213. EV_ACQUIRE_CB;
  214. return res;
  215. }
  216. /* TODO: can we move things around so we don't need this forward-reference? */
  217. static void
  218. iouring_poll (EV_P_ ev_tstamp timeout);
  219. static
  220. struct io_uring_sqe *
  221. iouring_sqe_get (EV_P)
  222. {
  223. unsigned tail;
  224. for (;;)
  225. {
  226. tail = EV_SQ_VAR (tail);
  227. if (ecb_expect_true (tail + 1 - EV_SQ_VAR (head) <= EV_SQ_VAR (ring_entries)))
  228. break; /* whats the problem, we have free sqes */
  229. /* queue full, need to flush and possibly handle some events */
  230. #if EV_FEATURE_CODE
  231. /* first we ask the kernel nicely, most often this frees up some sqes */
  232. int res = iouring_enter (EV_A_ EV_TS_CONST (0.));
  233. ECB_MEMORY_FENCE_ACQUIRE; /* better safe than sorry */
  234. if (res >= 0)
  235. continue; /* yes, it worked, try again */
  236. #endif
  237. /* some problem, possibly EBUSY - do the full poll and let it handle any issues */
  238. iouring_poll (EV_A_ EV_TS_CONST (0.));
  239. /* iouring_poll should have done ECB_MEMORY_FENCE_ACQUIRE for us */
  240. }
  241. /*assert (("libev: io_uring queue full after flush", tail + 1 - EV_SQ_VAR (head) <= EV_SQ_VAR (ring_entries)));*/
  242. return EV_SQES + (tail & EV_SQ_VAR (ring_mask));
  243. }
  244. inline_size
  245. struct io_uring_sqe *
  246. iouring_sqe_submit (EV_P_ struct io_uring_sqe *sqe)
  247. {
  248. unsigned idx = sqe - EV_SQES;
  249. EV_SQ_ARRAY [idx] = idx;
  250. ECB_MEMORY_FENCE_RELEASE;
  251. ++EV_SQ_VAR (tail);
  252. /*ECB_MEMORY_FENCE_RELEASE; /* for the time being we assume this is not needed */
  253. ++iouring_to_submit;
  254. }
  255. /*****************************************************************************/
  256. /* when the timerfd expires we simply note the fact,
  257. * as the purpose of the timerfd is to wake us up, nothing else.
  258. * the next iteration should re-set it.
  259. */
  260. static void
  261. iouring_tfd_cb (EV_P_ struct ev_io *w, int revents)
  262. {
  263. iouring_tfd_to = EV_TSTAMP_HUGE;
  264. }
  265. /* called for full and partial cleanup */
  266. ecb_cold
  267. static int
  268. iouring_internal_destroy (EV_P)
  269. {
  270. close (iouring_tfd);
  271. close (iouring_fd);
  272. if (iouring_sq_ring != MAP_FAILED) munmap (iouring_sq_ring, iouring_sq_ring_size);
  273. if (iouring_cq_ring != MAP_FAILED) munmap (iouring_cq_ring, iouring_cq_ring_size);
  274. if (iouring_sqes != MAP_FAILED) munmap (iouring_sqes , iouring_sqes_size );
  275. if (ev_is_active (&iouring_tfd_w))
  276. {
  277. ev_ref (EV_A);
  278. ev_io_stop (EV_A_ &iouring_tfd_w);
  279. }
  280. }
  281. ecb_cold
  282. static int
  283. iouring_internal_init (EV_P)
  284. {
  285. struct io_uring_params params = { 0 };
  286. iouring_to_submit = 0;
  287. iouring_tfd = -1;
  288. iouring_sq_ring = MAP_FAILED;
  289. iouring_cq_ring = MAP_FAILED;
  290. iouring_sqes = MAP_FAILED;
  291. if (!have_monotonic) /* cannot really happen, but what if11 */
  292. return -1;
  293. for (;;)
  294. {
  295. iouring_fd = evsys_io_uring_setup (iouring_entries, &params);
  296. if (iouring_fd >= 0)
  297. break; /* yippie */
  298. if (errno != EINVAL)
  299. return -1; /* we failed */
  300. #if TODO
  301. if ((~params.features) & (IORING_FEAT_NODROP | IORING_FEATURE_SINGLE_MMAP | IORING_FEAT_SUBMIT_STABLE))
  302. return -1; /* we require the above features */
  303. #endif
  304. /* EINVAL: lots of possible reasons, but maybe
  305. * it is because we hit the unqueryable hardcoded size limit
  306. */
  307. /* we hit the limit already, give up */
  308. if (iouring_max_entries)
  309. return -1;
  310. /* first time we hit EINVAL? assume we hit the limit, so go back and retry */
  311. iouring_entries >>= 1;
  312. iouring_max_entries = iouring_entries;
  313. }
  314. iouring_sq_ring_size = params.sq_off.array + params.sq_entries * sizeof (unsigned);
  315. iouring_cq_ring_size = params.cq_off.cqes + params.cq_entries * sizeof (struct io_uring_cqe);
  316. iouring_sqes_size = params.sq_entries * sizeof (struct io_uring_sqe);
  317. iouring_sq_ring = mmap (0, iouring_sq_ring_size, PROT_READ | PROT_WRITE,
  318. MAP_SHARED | MAP_POPULATE, iouring_fd, IORING_OFF_SQ_RING);
  319. iouring_cq_ring = mmap (0, iouring_cq_ring_size, PROT_READ | PROT_WRITE,
  320. MAP_SHARED | MAP_POPULATE, iouring_fd, IORING_OFF_CQ_RING);
  321. iouring_sqes = mmap (0, iouring_sqes_size, PROT_READ | PROT_WRITE,
  322. MAP_SHARED | MAP_POPULATE, iouring_fd, IORING_OFF_SQES);
  323. if (iouring_sq_ring == MAP_FAILED || iouring_cq_ring == MAP_FAILED || iouring_sqes == MAP_FAILED)
  324. return -1;
  325. iouring_sq_head = params.sq_off.head;
  326. iouring_sq_tail = params.sq_off.tail;
  327. iouring_sq_ring_mask = params.sq_off.ring_mask;
  328. iouring_sq_ring_entries = params.sq_off.ring_entries;
  329. iouring_sq_flags = params.sq_off.flags;
  330. iouring_sq_dropped = params.sq_off.dropped;
  331. iouring_sq_array = params.sq_off.array;
  332. iouring_cq_head = params.cq_off.head;
  333. iouring_cq_tail = params.cq_off.tail;
  334. iouring_cq_ring_mask = params.cq_off.ring_mask;
  335. iouring_cq_ring_entries = params.cq_off.ring_entries;
  336. iouring_cq_overflow = params.cq_off.overflow;
  337. iouring_cq_cqes = params.cq_off.cqes;
  338. iouring_tfd = timerfd_create (CLOCK_MONOTONIC, TFD_CLOEXEC);
  339. if (iouring_tfd < 0)
  340. return iouring_tfd;
  341. iouring_tfd_to = EV_TSTAMP_HUGE;
  342. return 0;
  343. }
  344. ecb_cold
  345. static void
  346. iouring_fork (EV_P)
  347. {
  348. iouring_internal_destroy (EV_A);
  349. while (iouring_internal_init (EV_A) < 0)
  350. ev_syserr ("(libev) io_uring_setup");
  351. fd_rearm_all (EV_A);
  352. ev_io_stop (EV_A_ &iouring_tfd_w);
  353. ev_io_set (EV_A_ &iouring_tfd_w, iouring_tfd, EV_READ);
  354. ev_io_start (EV_A_ &iouring_tfd_w);
  355. }
  356. /*****************************************************************************/
  357. static void
  358. iouring_modify (EV_P_ int fd, int oev, int nev)
  359. {
  360. if (oev)
  361. {
  362. /* we assume the sqe's are all "properly" initialised */
  363. struct io_uring_sqe *sqe = iouring_sqe_get (EV_A);
  364. sqe->opcode = IORING_OP_POLL_REMOVE;
  365. sqe->fd = fd;
  366. /* Jens Axboe notified me that user_data is not what is documented, but is
  367. * some kind of unique ID that has to match, otherwise the request cannot
  368. * be removed. Since we don't *really* have that, we pass in the old
  369. * generation counter - if that fails, too bad, it will hopefully be removed
  370. * at close time and then be ignored. */
  371. sqe->addr = (uint32_t)fd | ((__u64)(uint32_t)anfds [fd].egen << 32);
  372. sqe->user_data = (uint64_t)-1;
  373. iouring_sqe_submit (EV_A_ sqe);
  374. /* increment generation counter to avoid handling old events */
  375. ++anfds [fd].egen;
  376. }
  377. if (nev)
  378. {
  379. struct io_uring_sqe *sqe = iouring_sqe_get (EV_A);
  380. sqe->opcode = IORING_OP_POLL_ADD;
  381. sqe->fd = fd;
  382. sqe->addr = 0;
  383. sqe->user_data = (uint32_t)fd | ((__u64)(uint32_t)anfds [fd].egen << 32);
  384. sqe->poll_events =
  385. (nev & EV_READ ? POLLIN : 0)
  386. | (nev & EV_WRITE ? POLLOUT : 0);
  387. iouring_sqe_submit (EV_A_ sqe);
  388. }
  389. }
  390. inline_size
  391. void
  392. iouring_tfd_update (EV_P_ ev_tstamp timeout)
  393. {
  394. ev_tstamp tfd_to = mn_now + timeout;
  395. /* we assume there will be many iterations per timer change, so
  396. * we only re-set the timerfd when we have to because its expiry
  397. * is too late.
  398. */
  399. if (ecb_expect_false (tfd_to < iouring_tfd_to))
  400. {
  401. struct itimerspec its;
  402. iouring_tfd_to = tfd_to;
  403. EV_TS_SET (its.it_interval, 0.);
  404. EV_TS_SET (its.it_value, tfd_to);
  405. if (timerfd_settime (iouring_tfd, TFD_TIMER_ABSTIME, &its, 0) < 0)
  406. assert (("libev: iouring timerfd_settime failed", 0));
  407. }
  408. }
  409. inline_size
  410. void
  411. iouring_process_cqe (EV_P_ struct io_uring_cqe *cqe)
  412. {
  413. int fd = cqe->user_data & 0xffffffffU;
  414. uint32_t gen = cqe->user_data >> 32;
  415. int res = cqe->res;
  416. /* user_data -1 is a remove that we are not atm. interested in */
  417. if (cqe->user_data == (uint64_t)-1)
  418. return;
  419. assert (("libev: io_uring fd must be in-bounds", fd >= 0 && fd < anfdmax));
  420. /* documentation lies, of course. the result value is NOT like
  421. * normal syscalls, but like linux raw syscalls, i.e. negative
  422. * error numbers. fortunate, as otherwise there would be no way
  423. * to get error codes at all. still, why not document this?
  424. */
  425. /* ignore event if generation doesn't match */
  426. /* other than skipping removal events, */
  427. /* this should actually be very rare */
  428. if (ecb_expect_false (gen != (uint32_t)anfds [fd].egen))
  429. return;
  430. if (ecb_expect_false (res < 0))
  431. {
  432. /*TODO: EINVAL handling (was something failed with this fd)*/
  433. if (res == -EBADF)
  434. {
  435. assert (("libev: event loop rejected bad fd", res != -EBADF));
  436. fd_kill (EV_A_ fd);
  437. }
  438. else
  439. {
  440. errno = -res;
  441. ev_syserr ("(libev) IORING_OP_POLL_ADD");
  442. }
  443. return;
  444. }
  445. /* feed events, we do not expect or handle POLLNVAL */
  446. fd_event (
  447. EV_A_
  448. fd,
  449. (res & (POLLOUT | POLLERR | POLLHUP) ? EV_WRITE : 0)
  450. | (res & (POLLIN | POLLERR | POLLHUP) ? EV_READ : 0)
  451. );
  452. /* io_uring is oneshot, so we need to re-arm the fd next iteration */
  453. /* this also means we usually have to do at least one syscall per iteration */
  454. anfds [fd].events = 0;
  455. fd_change (EV_A_ fd, EV_ANFD_REIFY);
  456. }
  457. /* called when the event queue overflows */
  458. ecb_cold
  459. static void
  460. iouring_overflow (EV_P)
  461. {
  462. /* we have two options, resize the queue (by tearing down
  463. * everything and recreating it, or living with it
  464. * and polling.
  465. * we implement this by resizing the queue, and, if that fails,
  466. * we just recreate the state on every failure, which
  467. * kind of is a very inefficient poll.
  468. * one danger is, due to the bios toward lower fds,
  469. * we will only really get events for those, so
  470. * maybe we need a poll() fallback, after all.
  471. */
  472. /*EV_CQ_VAR (overflow) = 0;*/ /* need to do this if we keep the state and poll manually */
  473. fd_rearm_all (EV_A);
  474. /* we double the size until we hit the hard-to-probe maximum */
  475. if (!iouring_max_entries)
  476. {
  477. iouring_entries <<= 1;
  478. iouring_fork (EV_A);
  479. }
  480. else
  481. {
  482. /* we hit the kernel limit, we should fall back to something else.
  483. * we can either poll() a few times and hope for the best,
  484. * poll always, or switch to epoll.
  485. * TODO: is this necessary with newer kernels?
  486. */
  487. iouring_internal_destroy (EV_A);
  488. /* this should make it so that on return, we don't call any uring functions */
  489. iouring_to_submit = 0;
  490. for (;;)
  491. {
  492. backend = epoll_init (EV_A_ 0);
  493. if (backend)
  494. break;
  495. ev_syserr ("(libev) iouring switch to epoll");
  496. }
  497. }
  498. }
  499. /* handle any events in the completion queue, return true if there were any */
  500. static int
  501. iouring_handle_cq (EV_P)
  502. {
  503. unsigned head, tail, mask;
  504. head = EV_CQ_VAR (head);
  505. ECB_MEMORY_FENCE_ACQUIRE;
  506. tail = EV_CQ_VAR (tail);
  507. if (head == tail)
  508. return 0;
  509. /* it can only overflow if we have events, yes, yes? */
  510. if (ecb_expect_false (EV_CQ_VAR (overflow)))
  511. {
  512. iouring_overflow (EV_A);
  513. return 1;
  514. }
  515. mask = EV_CQ_VAR (ring_mask);
  516. do
  517. iouring_process_cqe (EV_A_ &EV_CQES [head++ & mask]);
  518. while (head != tail);
  519. EV_CQ_VAR (head) = head;
  520. ECB_MEMORY_FENCE_RELEASE;
  521. return 1;
  522. }
  523. static void
  524. iouring_poll (EV_P_ ev_tstamp timeout)
  525. {
  526. /* if we have events, no need for extra syscalls, but we might have to queue events */
  527. /* we also clar the timeout if there are outstanding fdchanges */
  528. /* the latter should only happen if both the sq and cq are full, most likely */
  529. /* because we have a lot of event sources that immediately complete */
  530. /* TODO: fdchacngecnt is always 0 because fd_reify does not have two buffers yet */
  531. if (iouring_handle_cq (EV_A) || fdchangecnt)
  532. timeout = EV_TS_CONST (0.);
  533. else
  534. /* no events, so maybe wait for some */
  535. iouring_tfd_update (EV_A_ timeout);
  536. /* only enter the kernel if we have something to submit, or we need to wait */
  537. if (timeout || iouring_to_submit)
  538. {
  539. int res = iouring_enter (EV_A_ timeout);
  540. if (ecb_expect_false (res < 0))
  541. if (errno == EINTR)
  542. /* ignore */;
  543. else if (errno == EBUSY)
  544. /* cq full, cannot submit - should be rare because we flush the cq first, so simply ignore */;
  545. else
  546. ev_syserr ("(libev) iouring setup");
  547. else
  548. iouring_handle_cq (EV_A);
  549. }
  550. }
  551. inline_size
  552. int
  553. iouring_init (EV_P_ int flags)
  554. {
  555. iouring_entries = IOURING_INIT_ENTRIES;
  556. iouring_max_entries = 0;
  557. if (iouring_internal_init (EV_A) < 0)
  558. {
  559. iouring_internal_destroy (EV_A);
  560. return 0;
  561. }
  562. ev_io_init (&iouring_tfd_w, iouring_tfd_cb, iouring_tfd, EV_READ);
  563. ev_set_priority (&iouring_tfd_w, EV_MINPRI);
  564. ev_io_start (EV_A_ &iouring_tfd_w);
  565. ev_unref (EV_A); /* watcher should not keep loop alive */
  566. backend_modify = iouring_modify;
  567. backend_poll = iouring_poll;
  568. return EVBACKEND_IOURING;
  569. }
  570. inline_size
  571. void
  572. iouring_destroy (EV_P)
  573. {
  574. iouring_internal_destroy (EV_A);
  575. }