nish 0.40.1 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1592 @@
1
+ /* Nish runtime, the io_uring half of the network layer (WP63 S1): a set of
2
+ * io_uring rings that holds TCP connections in the rings' registered file
3
+ * tables instead of the process's descriptor table, so one process can hold
4
+ * more connections than RLIMIT_NOFILE allows descriptors. The design and its
5
+ * measurements are docs/wp63-iouring-net.md; the prototype it was measured on
6
+ * is bench/fd-limit/uring-server.c. Nothing in `nish:net` calls this file yet
7
+ * (S2 adds the surface), and section GC means a program pays nothing for it.
8
+ *
9
+ * A translation unit of its own for the reason runtime-net.c is one: it
10
+ * carries its own measured `.text*` ceiling in tests/runtime-budgets.js, and
11
+ * scripts/build.sh pairs it with runtime.c like the other halves.
12
+ *
13
+ * **Four kernel behaviours shape it** (the note's §2, each measured):
14
+ *
15
+ * 1. A ring's file table is capped at RLIMIT_NOFILE slots
16
+ * (io_uring/rsrc.c, io_sqe_files_register answers -EMFILE past it), so a
17
+ * set holds C connections in ceil(C / limit) rings, made as they fill.
18
+ * 2. An accept that finds the table full has already taken the connection
19
+ * off the listener, and the kernel drops it (io_accept: the fixed install
20
+ * fails and puts the file). A multishot accept keeps accepting while the
21
+ * queue is non-empty, so it cannot be bounded. Accepts here are
22
+ * single-shot into IORING_FILE_INDEX_ALLOC, and a ring never has more in
23
+ * flight than it has free slots.
24
+ * 3. Accepts on one listener are exclusive waiters, woken one per arriving
25
+ * connection, so an accept that is only waiting never learns of the ones
26
+ * already queued. Exactly one ring accepts at a time, and moving the job
27
+ * to another ring is a fresh submission there, which is tried at once and
28
+ * drains the backlog.
29
+ * 4. A DEFER_TASKRUN ring runs at most 20 queued completions per
30
+ * io_uring_enter (IO_LOCAL_TW_DEFAULT_MAX), and queuing more work does
31
+ * not signal its eventfd while the rest wait; only the completions the
32
+ * enter posts do. TASKRUN_FLAG says work is left in IORING_SQ_TASKRUN.
33
+ * `ur_service` enters again while that flag is up, so one wait takes
34
+ * all of a ring's queued work rather than 20 per wakeup, and while
35
+ * IORING_SQ_CQ_OVERFLOW says the kernel holds completions the CQ had no
36
+ * room for (FEAT_NODROP keeps them rather than dropping them).
37
+ *
38
+ * **Every ring** is SINGLE_ISSUER | DEFER_TASKRUN | TASKRUN_FLAG |
39
+ * SUBMIT_ALL, with COOP_TASKRUN added where a kernel refuses TASKRUN_FLAG
40
+ * without it; a sparse file table; a provided-buffer ring that every
41
+ * connection's multishot recv draws from; and one eventfd, which the set's
42
+ * one epoll descriptor watches. A DEFER_TASKRUN ring's work runs only when
43
+ * this thread enters the ring, so a set belongs to the thread that opened it
44
+ * (the kernel refuses another thread's submissions under SINGLE_ISSUER). The
45
+ * kernel signals the eventfd when it queues work on an empty list, but on 7.0
46
+ * (and 6.18) that signal can be lost for good (NURING-8: a deferred signal
47
+ * sets a bit nothing clears), and polling the ring's own descriptor is no
48
+ * better, so no sleep on the set is longer than UR_SLEEP_MAX_MS: the timer is
49
+ * the wake the kernel guarantees, and a wait that wakes by it services every
50
+ * flagged ring. A caller that sleeps on `nish_uring_fd` sleeps no longer than
51
+ * `nish_uring_sleep_ms` answers.
52
+ *
53
+ * **A connection is a (ring, slot) pair.** Its recv is multishot; a recv the
54
+ * kernel ends with -ENOBUFS (every buffer lent out) is parked and re-armed on
55
+ * the next `nish_uring_wait`, after the buffers lent by the last one are back,
56
+ * never closed. A send copies its bytes, and a slot keeps one send in flight
57
+ * so that a short send's remainder, which is re-queued, goes out before the
58
+ * bytes queued behind it. A close cancels the slot's armed recv (closing a
59
+ * fixed slot does not, and the recv would keep the socket alive) and then
60
+ * closes the slot. Every completion carries the slot's generation, which the
61
+ * close moves on, so a completion that arrives after the close, or after the
62
+ * slot was reused, is recognised as stale and only gives back its buffer.
63
+ *
64
+ * **Nothing here exits or panics.** A call answers `>= 0` or a negative errno,
65
+ * Linux's number, the shape runtime-net.c uses. `nish_uring_probe` answers
66
+ * whether this kernel and this process may use the design at all: a kernel
67
+ * without io_uring (-ENOSYS), a sandbox or `io_uring_disabled` that refuses
68
+ * it (-EPERM), a kernel too old for the flags (-EINVAL), or one missing a
69
+ * feature or an opcode (-EOPNOTSUPP) all answer negative, and the caller
70
+ * keeps epoll. The calls are raw `syscall()`s against the kernel's ABI, which
71
+ * this file declares itself, so it builds against any libc's headers and
72
+ * needs no liburing.
73
+ *
74
+ * On any other platform, and on WASI, a set is unavailable: Darwin's stub
75
+ * answers -38 (Linux's ENOSYS) from every call, and a WASI build is empty.
76
+ */
77
+ #if defined(__wasi__) || defined(__wasm__)
78
+ /* ISO C wants at least one declaration in a translation unit. */
79
+ typedef int nish_uring_unused;
80
+ #else
81
+ #if defined(__linux__)
82
+ /* glibc declares `syscall` only with this feature macro. */
83
+ #define _GNU_SOURCE
84
+ #endif
85
+ #include <errno.h>
86
+ #include <stddef.h>
87
+ #include <stdint.h>
88
+ #include <stdlib.h>
89
+ #include <string.h>
90
+
91
+ /* What a set reports to the loop that waits on it. `data` is the set's own
92
+ * buffer and stays valid until the next `nish_uring_wait` on the same set. */
93
+ enum {
94
+ NISH_URING_ACCEPTED = 1, /* a new connection in (ring, slot) */
95
+ NISH_URING_DATA = 2, /* `res` bytes at `data` from (ring, slot) */
96
+ NISH_URING_HUP = 3, /* the peer closed (`res` 0) or failed (`res` < 0) */
97
+ NISH_URING_SEND_FAILED = 4, /* a send on (ring, slot) failed with `res` */
98
+ NISH_URING_ACCEPT_FAILED = 5, /* the listener failed with `res`; accepting stopped */
99
+ NISH_URING_ACCEPT_PAUSED = 6 /* an accept found memory short (`res`); accepting resumes after a back-off */
100
+ };
101
+
102
+ struct nish_uring_event {
103
+ int32_t kind;
104
+ int32_t ring;
105
+ int32_t slot;
106
+ int32_t res;
107
+ const uint8_t *data;
108
+ };
109
+
110
+ /* Sizes a set is opened with; a field of 0 takes its default. */
111
+ struct nish_uring_opts {
112
+ int32_t slots; /* file-table slots per ring; default RLIMIT_NOFILE's soft limit */
113
+ int32_t rings_max; /* rings a set may grow to; default 64 */
114
+ int32_t sq_entries; /* default 1024 */
115
+ int32_t cq_entries; /* default 8192, at least sq_entries */
116
+ int32_t buf_count; /* provided buffers per ring, a power of two; default 1024 */
117
+ int32_t buf_size; /* bytes per buffer; default 2048 */
118
+ };
119
+
120
+ /* Counters the tests read. `max_accepting_rings` is the most rings that ever
121
+ * had an accept in flight at once, which behaviour 3 says must stay 1, and
122
+ * `bound_violations` counts accepts the kernel refused for a full table, which
123
+ * behaviour 2 says must stay 0. */
124
+ struct nish_uring_stats {
125
+ int64_t rings;
126
+ int64_t live;
127
+ int64_t accepting;
128
+ int64_t slots;
129
+ int64_t taskrun_reentries;
130
+ int64_t overflow_drains;
131
+ int64_t nobufs_rearms;
132
+ int64_t send_requeues;
133
+ int64_t accept_errors;
134
+ int64_t accept_pauses;
135
+ int64_t bound_violations;
136
+ int64_t max_accepting_rings;
137
+ };
138
+
139
+ struct nish_uring_set;
140
+
141
+ int32_t nish_uring_probe(void);
142
+ int32_t nish_uring_premake(int32_t n, int32_t slots, int32_t *fds);
143
+ int32_t nish_uring_pooled(void);
144
+ int32_t nish_uring_open(struct nish_uring_set **out, int32_t listener, const struct nish_uring_opts *opts);
145
+ int32_t nish_uring_fd(const struct nish_uring_set *s);
146
+ int32_t nish_uring_sleep_ms(const struct nish_uring_set *s, int32_t timeout_ms);
147
+ int32_t nish_uring_wait(struct nish_uring_set *s, int32_t timeout_ms, struct nish_uring_event *ev, int32_t cap);
148
+ int32_t nish_uring_send(struct nish_uring_set *s, int32_t ring, int32_t slot, const uint8_t *p, int32_t n);
149
+ int32_t nish_uring_close(struct nish_uring_set *s, int32_t ring, int32_t slot);
150
+ int64_t nish_uring_queued(const struct nish_uring_set *s, int32_t ring, int32_t slot);
151
+ int32_t nish_uring_full(const struct nish_uring_set *s);
152
+ int32_t nish_uring_hold(struct nish_uring_set *s, int32_t ring, int32_t slot, int32_t on);
153
+ void nish_uring_stats(const struct nish_uring_set *s, struct nish_uring_stats *st);
154
+ void nish_uring_destroy(struct nish_uring_set *s);
155
+
156
+ #if defined(__linux__)
157
+ #include <fcntl.h>
158
+ #include <sys/epoll.h>
159
+ #include <sys/eventfd.h>
160
+ #include <sys/mman.h>
161
+ #include <sys/resource.h>
162
+ #include <sys/socket.h>
163
+ #include <sys/syscall.h>
164
+ #include <time.h>
165
+ #include <unistd.h>
166
+
167
+ /* The kernel's io_uring ABI (include/uapi/linux/io_uring.h), declared here so
168
+ * the file needs no particular kernel headers: an older sysroot that lacks
169
+ * DEFER_TASKRUN still builds, and the probe finds out at run time. The
170
+ * syscall numbers are the same on every architecture but alpha and mips. */
171
+ #ifndef __NR_io_uring_setup
172
+ #define __NR_io_uring_setup 425
173
+ #endif
174
+ #ifndef __NR_io_uring_enter
175
+ #define __NR_io_uring_enter 426
176
+ #endif
177
+ #ifndef __NR_io_uring_register
178
+ #define __NR_io_uring_register 427
179
+ #endif
180
+
181
+ #define UR_SETUP_CQSIZE (1u << 3)
182
+ #define UR_SETUP_R_DISABLED (1u << 6)
183
+ #define UR_SETUP_SUBMIT_ALL (1u << 7)
184
+ #define UR_SETUP_COOP_TASKRUN (1u << 8)
185
+ #define UR_SETUP_TASKRUN_FLAG (1u << 9)
186
+ #define UR_SETUP_SINGLE_ISSUER (1u << 12)
187
+ #define UR_SETUP_DEFER_TASKRUN (1u << 13)
188
+ #define UR_FEAT_SINGLE_MMAP (1u << 0)
189
+ #define UR_FEAT_NODROP (1u << 1)
190
+ #define UR_OFF_SQ_RING 0ull
191
+ #define UR_OFF_SQES 0x10000000ull
192
+ #define UR_SQ_CQ_OVERFLOW (1u << 1)
193
+ #define UR_SQ_TASKRUN (1u << 2)
194
+ #define UR_ENTER_GETEVENTS (1u << 0)
195
+ #define UR_SQE_FIXED_FILE (1u << 0)
196
+ #define UR_SQE_BUFFER_SELECT (1u << 5)
197
+ #define UR_SQE_CQE_SKIP_SUCCESS (1u << 6)
198
+ #define UR_CQE_F_BUFFER (1u << 0)
199
+ #define UR_CQE_F_MORE (1u << 1)
200
+ #define UR_CQE_BUFFER_SHIFT 16
201
+ #define UR_OP_NOP 0
202
+ #define UR_OP_ACCEPT 13
203
+ #define UR_OP_ASYNC_CANCEL 14
204
+ #define UR_OP_CLOSE 19
205
+ #define UR_OP_SEND 26
206
+ #define UR_OP_RECV 27
207
+ #define UR_RECV_MULTISHOT (1u << 1)
208
+ #define UR_CANCEL_ALL (1u << 0)
209
+ #define UR_CANCEL_FD (1u << 1)
210
+ #define UR_CANCEL_FD_FIXED (1u << 3)
211
+ #define UR_REGISTER_EVENTFD 4
212
+ #define UR_REGISTER_PROBE 8
213
+ #define UR_REGISTER_FILES2 13
214
+ #define UR_REGISTER_RESTRICTIONS 11
215
+ #define UR_REGISTER_ENABLE_RINGS 12
216
+ #define UR_REGISTER_PBUF_RING 22
217
+ #define UR_RESTRICTION_SQE_OP 1
218
+ #define UR_RESTRICTION_SQE_FLAGS_ALLOWED 2
219
+ #define UR_RSRC_REGISTER_SPARSE (1u << 0)
220
+ #define UR_FILE_INDEX_ALLOC (~0u)
221
+ #define UR_OP_SUPPORTED (1u << 0)
222
+ /* The kernel's own cap on a file table (IORING_MAX_FIXED_FILES). */
223
+ #define UR_MAX_SLOTS (1 << 20)
224
+
225
+ struct ur_sqring_offsets {
226
+ uint32_t head, tail, ring_mask, ring_entries, flags, dropped, array, resv1;
227
+ uint64_t user_addr;
228
+ };
229
+ struct ur_cqring_offsets {
230
+ uint32_t head, tail, ring_mask, ring_entries, overflow, cqes, flags, resv1;
231
+ uint64_t user_addr;
232
+ };
233
+ struct ur_params {
234
+ uint32_t sq_entries, cq_entries, flags, sq_thread_cpu, sq_thread_idle, features, wq_fd, resv[3];
235
+ struct ur_sqring_offsets sq_off;
236
+ struct ur_cqring_offsets cq_off;
237
+ };
238
+ /* One submission. The kernel's struct is a nest of unions; these are the
239
+ * names of the members this file sets, at the kernel's offsets. */
240
+ struct ur_sqe {
241
+ uint8_t opcode;
242
+ uint8_t flags;
243
+ uint16_t ioprio;
244
+ int32_t fd;
245
+ uint64_t off;
246
+ uint64_t addr;
247
+ uint32_t len;
248
+ uint32_t op_flags; /* msg_flags, accept_flags, cancel_flags */
249
+ uint64_t user_data;
250
+ uint16_t buf_group;
251
+ uint16_t personality;
252
+ uint32_t file_index;
253
+ uint64_t addr3;
254
+ uint64_t pad;
255
+ };
256
+ struct ur_cqe {
257
+ uint64_t user_data;
258
+ int32_t res;
259
+ uint32_t flags;
260
+ };
261
+ struct ur_rsrc_register {
262
+ uint32_t nr, flags;
263
+ uint64_t resv2, data, tags;
264
+ };
265
+ struct ur_buf {
266
+ uint64_t addr;
267
+ uint32_t len;
268
+ uint16_t bid;
269
+ uint16_t resv; /* in entry 0, the ring's tail */
270
+ };
271
+ struct ur_buf_reg {
272
+ uint64_t ring_addr;
273
+ uint32_t ring_entries;
274
+ uint16_t bgid;
275
+ uint16_t flags;
276
+ uint64_t resv[3];
277
+ };
278
+ struct ur_probe_op {
279
+ uint8_t op, resv;
280
+ uint16_t flags;
281
+ uint32_t resv2;
282
+ };
283
+ struct ur_probe {
284
+ uint8_t last_op, ops_len;
285
+ uint16_t resv;
286
+ uint32_t resv2[3];
287
+ struct ur_probe_op ops[64];
288
+ };
289
+ /* One entry of IORING_REGISTER_RESTRICTIONS: `arg` is the union of
290
+ * register_op, sqe_op and sqe_flags. */
291
+ struct ur_restriction {
292
+ uint16_t opcode;
293
+ uint8_t arg;
294
+ uint8_t resv;
295
+ uint32_t resv2[3];
296
+ };
297
+
298
+ _Static_assert(sizeof(struct ur_params) == 120, "io_uring_params is 120 bytes");
299
+ _Static_assert(sizeof(struct ur_sqe) == 64, "io_uring_sqe is 64 bytes");
300
+ _Static_assert(sizeof(struct ur_cqe) == 16, "io_uring_cqe is 16 bytes");
301
+ _Static_assert(sizeof(struct ur_rsrc_register) == 32, "io_uring_rsrc_register is 32 bytes");
302
+ _Static_assert(sizeof(struct ur_buf) == 16, "io_uring_buf is 16 bytes");
303
+ _Static_assert(sizeof(struct ur_buf_reg) == 40, "io_uring_buf_reg is 40 bytes");
304
+ _Static_assert(sizeof(struct ur_restriction) == 16, "io_uring_restriction is 16 bytes");
305
+
306
+ /* What a completion's user_data says. A send's is its record's address, which
307
+ * malloc aligns to 8, with UR_SEND in the low three bits; every other op's is
308
+ * the op, the slot's generation and the slot, and none of those ops is 3. */
309
+ enum { UR_ACCEPT = 1, UR_RECV = 2, UR_SEND = 3, UR_CLOSE = 4, UR_CANCEL = 5 };
310
+
311
+ /* A slot's state word: open, recv armed, recv parked on -ENOBUFS, recv held
312
+ * by its caller (`nish_uring_hold`), hung up (its recv ended for good, so it
313
+ * is never armed again until the slot is accepted anew), and the generation
314
+ * in the 24 bits above. */
315
+ #define ST_OPEN 1u
316
+ #define ST_ARMED 2u
317
+ #define ST_PARKED 4u
318
+ #define ST_HELD 8u
319
+ #define ST_HUP 16u
320
+ #define ST_GEN(st) ((st) >> 8)
321
+ #define GEN_MASK 0xffffffu
322
+
323
+ #define BGID 1
324
+ #define ACCEPT_DEPTH 32
325
+ /* The back-off after an accept that found memory short: 10 ms, doubling to
326
+ * 640 ms while accepts keep failing. Connections wait in the listener's
327
+ * backlog meanwhile, as they do at a full set. */
328
+ #define ACCEPT_BACKOFF_MIN_MS 10
329
+ #define ACCEPT_BACKOFF_MAX_MS 640
330
+ #define EVENTS_MAX 256
331
+
332
+ /* One send's bytes, owned by the set until the kernel has taken all of them.
333
+ * `next` queues it behind the slot's earlier sends; `prev_all`/`next_all`
334
+ * keep every record on one list so `nish_uring_destroy` can free those the
335
+ * kernel still held. */
336
+ struct ur_send {
337
+ struct ur_send *next, *prev_all, *next_all;
338
+ uint32_t slot, gen;
339
+ uint32_t off, len;
340
+ int in_flight;
341
+ uint8_t data[];
342
+ };
343
+
344
+ struct ur_ring {
345
+ int fd, efd;
346
+ uint32_t *sq_head, *sq_tail, *sq_mask, *sq_array, *sq_flags;
347
+ uint32_t *cq_head, *cq_tail, *cq_mask;
348
+ struct ur_sqe *sqes;
349
+ struct ur_cqe *cqes;
350
+ void *ring_map;
351
+ size_t ring_len, sqes_len;
352
+ uint32_t sq_entries, sq_local_tail, to_submit;
353
+ struct ur_buf *br;
354
+ uint8_t *bufs;
355
+ size_t br_len, bufs_len;
356
+ uint16_t br_tail;
357
+ long live, accepting;
358
+ uint32_t *st; /* per slot */
359
+ struct ur_send **sq_first; /* per slot: the head of its send queue */
360
+ struct ur_send **sq_last; /* per slot: the tail */
361
+ uint32_t *qbytes; /* per slot: bytes queued and not yet sent */
362
+ uint32_t *parked; /* slots whose recv waits for buffers */
363
+ uint32_t nparked;
364
+ };
365
+
366
+ struct nish_uring_set {
367
+ int listener, ep;
368
+ uint32_t slots, buf_count, buf_size, sq_entries, cq_entries;
369
+ int nrings, rings_max, acceptor;
370
+ int accept_stopped;
371
+ /* Accepting waits until `resume_ms` after an accept found memory short; the
372
+ * wait doubles from ACCEPT_BACKOFF_MIN_MS while it keeps failing and starts
373
+ * again from the minimum once an accept succeeds. */
374
+ int accept_paused;
375
+ int32_t backoff_ms;
376
+ int64_t resume_ms;
377
+ struct ur_ring **rings;
378
+ struct ur_send *all;
379
+ long stalled_sends; /* heads that found the SQ full */
380
+ /* Buffers lent to the caller by the last wait, given back by the next. */
381
+ uint32_t lent_ring[EVENTS_MAX];
382
+ uint16_t lent_bid[EVENTS_MAX];
383
+ int nlent;
384
+ struct nish_uring_stats stats;
385
+ };
386
+
387
+ static int ur_errno(long rc) { return rc < 0 ? -errno : (int)rc; }
388
+
389
+ /* tests/runtime/uring-test.c stands in for setup and register to force the
390
+ * answers a seccomp filter cannot: an -EINVAL that depends on the flags, a
391
+ * missing feature bit or opcode. */
392
+ #ifndef UR_SYS_SETUP
393
+ #define UR_SYS_SETUP(entries, p) syscall(__NR_io_uring_setup, entries, p)
394
+ #endif
395
+ #ifndef UR_SYS_REGISTER
396
+ #define UR_SYS_REGISTER(fd, op, arg, nr) syscall(__NR_io_uring_register, fd, op, arg, nr)
397
+ #endif
398
+ /* What an accept completion answered; uring-test.c turns one into -ENOMEM,
399
+ * which the kernel gives only when memory is short. */
400
+ #ifndef UR_ACCEPT_RES
401
+ #define UR_ACCEPT_RES(res) (res)
402
+ #endif
403
+
404
+ static int ur_setup(uint32_t entries, struct ur_params *p) { return ur_errno(UR_SYS_SETUP(entries, p)); }
405
+
406
+ static int ur_enter(struct ur_ring *r, uint32_t submit, uint32_t wait, uint32_t flags) {
407
+ return ur_errno(syscall(__NR_io_uring_enter, r->fd, submit, wait, flags, NULL, 0));
408
+ }
409
+
410
+ static int ur_register(int fd, unsigned op, void *arg, unsigned nr) {
411
+ return ur_errno(UR_SYS_REGISTER(fd, op, arg, nr));
412
+ }
413
+
414
+ static int ur_setup_try(uint32_t entries, uint32_t cq, struct ur_params *p, uint32_t f) {
415
+ memset(p, 0, sizeof *p);
416
+ p->flags = f;
417
+ p->cq_entries = cq;
418
+ return ur_setup(entries, p);
419
+ }
420
+
421
+ /* Make a ring fd with the set's flags. A kernel that has TASKRUN_FLAG but
422
+ * wants COOP_TASKRUN beside it, or DEFER_TASKRUN's precondition, answers
423
+ * -EINVAL, so the second try adds COOP_TASKRUN. */
424
+ static int ur_setup_flags(uint32_t entries, uint32_t cq, struct ur_params *p) {
425
+ uint32_t f = UR_SETUP_SINGLE_ISSUER | UR_SETUP_DEFER_TASKRUN | UR_SETUP_TASKRUN_FLAG | UR_SETUP_SUBMIT_ALL;
426
+ if (cq) f |= UR_SETUP_CQSIZE;
427
+ int fd = ur_setup_try(entries, cq, p, f);
428
+ if (fd == -EINVAL) {
429
+ f |= UR_SETUP_COOP_TASKRUN;
430
+ fd = ur_setup_try(entries, cq, p, f);
431
+ }
432
+ return fd;
433
+ }
434
+
435
+ /* Whether the ring `fd` has every opcode the layer submits: 1, -EOPNOTSUPP
436
+ * when one is missing or the kernel has no probe, or the register's errno. */
437
+ static int32_t ur_ops_ok(int fd) {
438
+ struct ur_probe pr;
439
+ memset(&pr, 0, sizeof pr);
440
+ int e = ur_register(fd, UR_REGISTER_PROBE, &pr, 64);
441
+ if (e < 0) return e == -EINVAL ? -EOPNOTSUPP : e;
442
+ static const uint8_t ops[] = {UR_OP_ACCEPT, UR_OP_ASYNC_CANCEL, UR_OP_CLOSE, UR_OP_SEND, UR_OP_RECV};
443
+ for (size_t i = 0; i < sizeof ops; i++) {
444
+ uint8_t op = ops[i];
445
+ if (op > pr.last_op || op >= pr.ops_len || !(pr.ops[op].flags & UR_OP_SUPPORTED)) return -EOPNOTSUPP;
446
+ }
447
+ return 1;
448
+ }
449
+
450
+ static int32_t ur_probe_once(void) {
451
+ struct ur_params p;
452
+ int fd = ur_setup_flags(4, 0, &p);
453
+ if (fd < 0) return fd;
454
+ int32_t rc = 1;
455
+ if (!(p.features & UR_FEAT_NODROP) || !(p.features & UR_FEAT_SINGLE_MMAP)) rc = -EOPNOTSUPP;
456
+ if (rc > 0) rc = ur_ops_ok(fd);
457
+ if (rc > 0) {
458
+ struct ur_rsrc_register files;
459
+ memset(&files, 0, sizeof files);
460
+ files.nr = 1;
461
+ files.flags = UR_RSRC_REGISTER_SPARSE;
462
+ int e = ur_register(fd, UR_REGISTER_FILES2, &files, sizeof files);
463
+ if (e < 0) rc = e == -EINVAL ? -EOPNOTSUPP : e;
464
+ }
465
+ if (rc > 0) {
466
+ void *br = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
467
+ if (br == MAP_FAILED) {
468
+ rc = -ENOMEM;
469
+ } else {
470
+ struct ur_buf_reg reg;
471
+ memset(&reg, 0, sizeof reg);
472
+ reg.ring_addr = (uint64_t)(uintptr_t)br;
473
+ reg.ring_entries = 8;
474
+ reg.bgid = BGID;
475
+ int e = ur_register(fd, UR_REGISTER_PBUF_RING, &reg, 1);
476
+ if (e < 0) rc = e == -EINVAL ? -EOPNOTSUPP : e;
477
+ close(fd);
478
+ fd = -1;
479
+ munmap(br, 4096);
480
+ }
481
+ }
482
+ if (fd >= 0) close(fd);
483
+ return rc;
484
+ }
485
+
486
+ /* The rings `--sandbox` made before its filter (WP63 S3), which sets take in
487
+ * place of making their own: under that filter `io_uring_setup` and
488
+ * `io_uring_register` kill the process. `made` is set once, before `main`
489
+ * and before any thread, by `nish_uring_premake`; `rc` is the number of rings
490
+ * made or the errno of the step that failed, and `next` the next ring a set
491
+ * takes. `keeper` is one more restricted ring, made after them, which takes
492
+ * only NOP and has no queue mapped: a ring a set frees is dropped by
493
+ * `dup3`ing the keeper over its number, never by closing it, so every number
494
+ * the filter lets `io_uring_enter` take holds a restricted ring for the
495
+ * process's life (NURING-36). -1 when the pool holds no ring. */
496
+ #define UR_POOL_MAX 64
497
+ /* The default sizes, which a pooled ring is made at. */
498
+ #define UR_SQ_DEFAULT 1024
499
+ #define UR_CQ_DEFAULT 8192
500
+ #define UR_BUF_COUNT_DEFAULT 1024
501
+ #define UR_BUF_SIZE_DEFAULT 2048
502
+ struct ur_sizes {
503
+ uint32_t slots, buf_count, buf_size, sq_entries, cq_entries;
504
+ };
505
+ static struct {
506
+ int made;
507
+ int32_t rc;
508
+ struct ur_sizes z;
509
+ struct ur_ring *rings[UR_POOL_MAX];
510
+ int32_t fds[UR_POOL_MAX];
511
+ int n, next;
512
+ int keeper;
513
+ } ur_pool = {.keeper = -1};
514
+
515
+ /* 1 when this process may use a set, else the negative errno that says why
516
+ * not. A yes or a static refusal is kept for the process: what refuses
517
+ * io_uring (the kernel, a seccomp filter, the sysctl) does not change under
518
+ * a running program in a way it could act on. A refusal for want of a
519
+ * resource (-EMFILE, -ENFILE, -ENOMEM, ...) is not kept, so the next call
520
+ * asks again once descriptors or memory are free. */
521
+ int32_t nish_uring_probe(void) {
522
+ /* A sandboxed process never calls setup: the pool is the answer. */
523
+ if (ur_pool.made) return ur_pool.rc > 0 ? 1 : ur_pool.rc;
524
+ static int32_t cached;
525
+ int32_t c = __atomic_load_n(&cached, __ATOMIC_RELAXED);
526
+ if (c == 0) {
527
+ c = ur_probe_once();
528
+ if (c > 0 || c == -ENOSYS || c == -EPERM || c == -EINVAL || c == -EOPNOTSUPP)
529
+ __atomic_store_n(&cached, c, __ATOMIC_RELAXED);
530
+ }
531
+ return c;
532
+ }
533
+
534
+ /* Hand the queued submissions to the kernel. -EINTR is tried again; anything
535
+ * else (-EAGAIN for memory, -EBUSY on a kernel that refuses submissions while
536
+ * completions overflow) leaves them queued for the next call to retry. */
537
+ static int ur_flush(struct ur_ring *r) {
538
+ while (r->to_submit) {
539
+ int rc = ur_enter(r, r->to_submit, 0, UR_ENTER_GETEVENTS);
540
+ if (rc == -EINTR) continue;
541
+ if (rc < 0) return rc;
542
+ if (rc == 0) return -EAGAIN;
543
+ r->to_submit -= (uint32_t)rc > r->to_submit ? r->to_submit : (uint32_t)rc;
544
+ }
545
+ return 0;
546
+ }
547
+
548
+ /* The next free submission entry, zeroed, or NULL when the SQ stays full
549
+ * after a flush. */
550
+ static struct ur_sqe *ur_sqe(struct ur_ring *r) {
551
+ uint32_t head = __atomic_load_n(r->sq_head, __ATOMIC_ACQUIRE);
552
+ if (r->sq_local_tail - head >= r->sq_entries) {
553
+ (void)ur_flush(r);
554
+ head = __atomic_load_n(r->sq_head, __ATOMIC_ACQUIRE);
555
+ if (r->sq_local_tail - head >= r->sq_entries) return NULL;
556
+ }
557
+ uint32_t i = r->sq_local_tail & *r->sq_mask;
558
+ struct ur_sqe *e = &r->sqes[i];
559
+ memset(e, 0, sizeof *e);
560
+ r->sq_array[i] = i;
561
+ r->sq_local_tail++;
562
+ __atomic_store_n(r->sq_tail, r->sq_local_tail, __ATOMIC_RELEASE);
563
+ r->to_submit++;
564
+ return e;
565
+ }
566
+
567
+ static uint64_t ur_tag(unsigned op, uint32_t st, uint32_t slot) {
568
+ return (uint64_t)op | ((uint64_t)(ST_GEN(st) & GEN_MASK) << 8) | ((uint64_t)slot << 32);
569
+ }
570
+
571
+ static void ur_recycle(struct nish_uring_set *s, struct ur_ring *r, uint32_t bid) {
572
+ struct ur_buf *b = &r->br[r->br_tail & (s->buf_count - 1)];
573
+ b->addr = (uint64_t)(uintptr_t)(r->bufs + (size_t)bid * s->buf_size);
574
+ b->len = s->buf_size;
575
+ b->bid = (uint16_t)bid;
576
+ r->br_tail++;
577
+ __atomic_store_n(&r->br[0].resv, r->br_tail, __ATOMIC_RELEASE);
578
+ }
579
+
580
+ /* Arm a slot's multishot recv, or park it for the next wait when the SQ has
581
+ * no room. A slot that has hung up is not armed: a recv on its socket would
582
+ * answer 0 once the kernel has handed over the reset, and a second hangup
583
+ * would turn the reset into a clean end (NURING-27). */
584
+ static void ur_arm(struct ur_ring *r, uint32_t slot) {
585
+ if (r->st[slot] & ST_HUP) return;
586
+ struct ur_sqe *e = ur_sqe(r);
587
+ if (!e) {
588
+ if (!(r->st[slot] & ST_PARKED)) {
589
+ r->st[slot] |= ST_PARKED;
590
+ r->parked[r->nparked++] = slot;
591
+ }
592
+ return;
593
+ }
594
+ e->opcode = UR_OP_RECV;
595
+ e->fd = (int32_t)slot;
596
+ e->flags = UR_SQE_FIXED_FILE | UR_SQE_BUFFER_SELECT;
597
+ e->ioprio = UR_RECV_MULTISHOT;
598
+ e->buf_group = BGID;
599
+ e->user_data = ur_tag(UR_RECV, r->st[slot], slot);
600
+ r->st[slot] |= ST_ARMED;
601
+ }
602
+
603
+ static void ur_free_ring(struct ur_ring *r) {
604
+ if (r->efd >= 0) close(r->efd);
605
+ /* A pooled ring's number stays a restricted ring's: `dup3` drops the ring
606
+ and puts the keeper there in one step, which the filter allows from the
607
+ keeper alone, where it kills `close` on that number (NURING-36). It is
608
+ tried again on EINTR and EBUSY; on any other failure the ring is left at
609
+ its number, still restricted, and its kernel memory is held. */
610
+ if (r->fd >= 0 && ur_pool.keeper >= 0) {
611
+ while (syscall(SYS_dup3, ur_pool.keeper, r->fd, O_CLOEXEC) < 0 && (errno == EINTR || errno == EBUSY)) {
612
+ }
613
+ } else if (r->fd >= 0)
614
+ close(r->fd);
615
+ if (r->ring_map && r->ring_map != MAP_FAILED) munmap(r->ring_map, r->ring_len);
616
+ if (r->sqes && (void *)r->sqes != MAP_FAILED) munmap(r->sqes, r->sqes_len);
617
+ if (r->br && (void *)r->br != MAP_FAILED) munmap(r->br, r->br_len);
618
+ if (r->bufs && (void *)r->bufs != MAP_FAILED) munmap(r->bufs, r->bufs_len);
619
+ free(r->st);
620
+ free(r->sq_first);
621
+ free(r->sq_last);
622
+ free(r->parked);
623
+ free(r->qbytes);
624
+ free(r);
625
+ }
626
+
627
+ /* Restrict a ring made with R_DISABLED to what the layer submits (WP63 §6.2):
628
+ * the five opcodes and NOP, the three flags the layer sets, and no register
629
+ * opcode at all once it is enabled. */
630
+ static int ur_restrict(int fd) {
631
+ static const uint8_t ops[] = {UR_OP_ACCEPT, UR_OP_RECV, UR_OP_SEND, UR_OP_CLOSE, UR_OP_ASYNC_CANCEL, UR_OP_NOP};
632
+ struct ur_restriction res[sizeof ops + 1];
633
+ memset(res, 0, sizeof res);
634
+ for (size_t i = 0; i < sizeof ops; i++) {
635
+ res[i].opcode = UR_RESTRICTION_SQE_OP;
636
+ res[i].arg = ops[i];
637
+ }
638
+ res[sizeof ops].opcode = UR_RESTRICTION_SQE_FLAGS_ALLOWED;
639
+ res[sizeof ops].arg = UR_SQE_FIXED_FILE | UR_SQE_BUFFER_SELECT | UR_SQE_CQE_SKIP_SUCCESS;
640
+ return ur_register(fd, UR_REGISTER_RESTRICTIONS, res, (unsigned)(sizeof res / sizeof res[0]));
641
+ }
642
+
643
+ /* The pool's keeper: a ring of one entry made disabled, restricted to NOP
644
+ * with no submission flag, and enabled, with nothing mapped or registered.
645
+ * Answers its descriptor or the failing step's negative errno. */
646
+ static int ur_make_keeper(void) {
647
+ struct ur_params p;
648
+ int fd = ur_setup_try(1, 0, &p, UR_SETUP_R_DISABLED);
649
+ if (fd < 0) return fd;
650
+ struct ur_restriction res;
651
+ memset(&res, 0, sizeof res);
652
+ res.opcode = UR_RESTRICTION_SQE_OP;
653
+ res.arg = UR_OP_NOP;
654
+ int rc = ur_register(fd, UR_REGISTER_RESTRICTIONS, &res, 1);
655
+ if (rc >= 0) rc = ur_register(fd, UR_REGISTER_ENABLE_RINGS, NULL, 0);
656
+ if (rc < 0) {
657
+ close(fd);
658
+ return rc;
659
+ }
660
+ return fd;
661
+ }
662
+
663
+ /* A new ring of sizes `z`: the SQ and CQ mapped, a sparse table of
664
+ * `z->slots`, the buffer ring registered, the eventfd registered. A
665
+ * `restricted` ring is made disabled, restricted before anything else is
666
+ * registered, and enabled last; it has no SINGLE_ISSUER, which would tie it to
667
+ * the thread that enabled it, the one that runs `.preinit_array`. Answers 0
668
+ * with the ring in `*out`, or the failing step's negative errno with nothing
669
+ * left behind. */
670
+ static int ur_make_ring(const struct ur_sizes *z, int restricted, struct ur_ring **out) {
671
+ *out = NULL;
672
+ struct ur_ring *r = calloc(1, sizeof *r);
673
+ if (!r) return -ENOMEM;
674
+ r->fd = -1;
675
+ r->efd = -1;
676
+ int rc = 0;
677
+ struct ur_params p;
678
+ /* The ring itself, and the two features the layer cannot do without. */
679
+ if (restricted)
680
+ r->fd = ur_setup_try(z->sq_entries, z->cq_entries, &p,
681
+ UR_SETUP_R_DISABLED | UR_SETUP_COOP_TASKRUN | UR_SETUP_TASKRUN_FLAG | UR_SETUP_SUBMIT_ALL |
682
+ UR_SETUP_CQSIZE);
683
+ else
684
+ r->fd = ur_setup_flags(z->sq_entries, z->cq_entries, &p);
685
+ if (r->fd < 0) {
686
+ rc = r->fd;
687
+ goto fail;
688
+ }
689
+ if (!(p.features & UR_FEAT_SINGLE_MMAP) || !(p.features & UR_FEAT_NODROP)) {
690
+ rc = -EOPNOTSUPP;
691
+ goto fail;
692
+ }
693
+ if (restricted) {
694
+ rc = ur_ops_ok(r->fd);
695
+ if (rc < 0) goto fail;
696
+ rc = ur_restrict(r->fd);
697
+ if (rc < 0) goto fail;
698
+ }
699
+ /* SQ and CQ share one mapping (FEAT_SINGLE_MMAP); the SQEs are another. */
700
+ r->sq_entries = p.sq_entries;
701
+ size_t sq_len = p.sq_off.array + (size_t)p.sq_entries * sizeof(uint32_t);
702
+ size_t cq_len = p.cq_off.cqes + (size_t)p.cq_entries * sizeof(struct ur_cqe);
703
+ r->ring_len = sq_len > cq_len ? sq_len : cq_len;
704
+ r->ring_map = mmap(NULL, r->ring_len, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, r->fd, UR_OFF_SQ_RING);
705
+ if (r->ring_map == MAP_FAILED) {
706
+ rc = -errno;
707
+ goto fail;
708
+ }
709
+ char *m = r->ring_map;
710
+ r->sq_head = (uint32_t *)(void *)(m + p.sq_off.head);
711
+ r->sq_tail = (uint32_t *)(void *)(m + p.sq_off.tail);
712
+ r->sq_mask = (uint32_t *)(void *)(m + p.sq_off.ring_mask);
713
+ r->sq_array = (uint32_t *)(void *)(m + p.sq_off.array);
714
+ r->sq_flags = (uint32_t *)(void *)(m + p.sq_off.flags);
715
+ r->cq_head = (uint32_t *)(void *)(m + p.cq_off.head);
716
+ r->cq_tail = (uint32_t *)(void *)(m + p.cq_off.tail);
717
+ r->cq_mask = (uint32_t *)(void *)(m + p.cq_off.ring_mask);
718
+ r->cqes = (struct ur_cqe *)(void *)(m + p.cq_off.cqes);
719
+ r->sqes_len = (size_t)p.sq_entries * sizeof(struct ur_sqe);
720
+ r->sqes = mmap(NULL, r->sqes_len, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, r->fd, UR_OFF_SQES);
721
+ if ((void *)r->sqes == MAP_FAILED) {
722
+ rc = -errno;
723
+ goto fail;
724
+ }
725
+ r->sq_local_tail = *r->sq_tail;
726
+
727
+ /* The sparse file table: one entry per slot, filled by FILE_INDEX_ALLOC. */
728
+ struct ur_rsrc_register files;
729
+ memset(&files, 0, sizeof files);
730
+ files.nr = z->slots;
731
+ files.flags = UR_RSRC_REGISTER_SPARSE;
732
+ rc = ur_register(r->fd, UR_REGISTER_FILES2, &files, sizeof files);
733
+ if (rc < 0) goto fail;
734
+
735
+ /* The provided-buffer ring every multishot recv draws from; the set fills it. */
736
+ r->br_len = (size_t)z->buf_count * sizeof(struct ur_buf);
737
+ r->bufs_len = (size_t)z->buf_count * z->buf_size;
738
+ r->br = mmap(NULL, r->br_len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
739
+ r->bufs = mmap(NULL, r->bufs_len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
740
+ if ((void *)r->br == MAP_FAILED || (void *)r->bufs == MAP_FAILED) {
741
+ rc = -ENOMEM;
742
+ goto fail;
743
+ }
744
+ struct ur_buf_reg reg;
745
+ memset(&reg, 0, sizeof reg);
746
+ reg.ring_addr = (uint64_t)(uintptr_t)r->br;
747
+ reg.ring_entries = z->buf_count;
748
+ reg.bgid = BGID;
749
+ rc = ur_register(r->fd, UR_REGISTER_PBUF_RING, &reg, 1);
750
+ if (rc < 0) goto fail;
751
+
752
+ /* Per-slot state: generation and flags, send queues, parked recvs. */
753
+ r->st = calloc(z->slots, sizeof *r->st);
754
+ r->sq_first = calloc(z->slots, sizeof *r->sq_first);
755
+ r->sq_last = calloc(z->slots, sizeof *r->sq_last);
756
+ r->parked = calloc(z->slots, sizeof *r->parked);
757
+ r->qbytes = calloc(z->slots, sizeof *r->qbytes);
758
+ if (!r->st || !r->sq_first || !r->sq_last || !r->parked || !r->qbytes) {
759
+ rc = -ENOMEM;
760
+ goto fail;
761
+ }
762
+
763
+ /* The eventfd the kernel signals for this ring. */
764
+ r->efd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
765
+ if (r->efd < 0) {
766
+ rc = -errno;
767
+ goto fail;
768
+ }
769
+ rc = ur_register(r->fd, UR_REGISTER_EVENTFD, &r->efd, 1);
770
+ if (rc < 0) goto fail;
771
+ if (restricted) {
772
+ rc = ur_register(r->fd, UR_REGISTER_ENABLE_RINGS, NULL, 0);
773
+ if (rc < 0) goto fail;
774
+ }
775
+ *out = r;
776
+ return 0;
777
+ fail:
778
+ ur_free_ring(r);
779
+ return rc < 0 ? rc : -EINVAL;
780
+ }
781
+
782
+ /* A new ring in the set: made, or taken from the pool when `--sandbox` made
783
+ * one (-ENOSPC when the pool is spent), then its buffer ring filled and its
784
+ * eventfd in the set's epoll with the ring's index as its data. Answers the
785
+ * ring's index or a negative errno, and leaves nothing behind on failure. */
786
+ static int ur_add_ring(struct nish_uring_set *s) {
787
+ if (s->nrings >= s->rings_max) return -ENOSPC;
788
+ struct ur_ring *r;
789
+ if (ur_pool.made) {
790
+ /* A full set asks again on every top-up, so a spent pool answers without
791
+ counting: `next` stays within the threads past `n` and never wraps to
792
+ a negative index (NURING-34). */
793
+ if (__atomic_load_n(&ur_pool.next, __ATOMIC_RELAXED) >= ur_pool.n) return -ENOSPC;
794
+ int i = __atomic_fetch_add(&ur_pool.next, 1, __ATOMIC_RELAXED);
795
+ if (i >= ur_pool.n) return -ENOSPC;
796
+ r = ur_pool.rings[i];
797
+ ur_pool.rings[i] = NULL;
798
+ } else {
799
+ struct ur_sizes z = {s->slots, s->buf_count, s->buf_size, s->sq_entries, s->cq_entries};
800
+ int rc = ur_make_ring(&z, 0, &r);
801
+ if (rc < 0) return rc;
802
+ }
803
+ for (uint32_t i = 0; i < s->buf_count; i++) ur_recycle(s, r, i);
804
+ struct epoll_event ev;
805
+ memset(&ev, 0, sizeof ev);
806
+ ev.events = EPOLLIN;
807
+ ev.data.u32 = (uint32_t)s->nrings;
808
+ if (epoll_ctl(s->ep, EPOLL_CTL_ADD, r->efd, &ev) != 0) {
809
+ int rc = -errno;
810
+ ur_free_ring(r);
811
+ return rc;
812
+ }
813
+ s->rings[s->nrings] = r;
814
+ s->stats.rings = ++s->nrings;
815
+ s->stats.slots = (int64_t)s->nrings * s->slots;
816
+ return s->nrings - 1;
817
+ }
818
+
819
+ /* Make `n` restricted rings of `slots` slots, at the sizes a set opens with
820
+ * by default, for the sets this process opens later (WP63 S3). `--sandbox`
821
+ * calls it once, before its seccomp filter and before any thread; with `n`
822
+ * of 0 it only records that this process may not make a ring (-EPERM). A
823
+ * kernel below the probe's floor makes none, and a ring that fails any step
824
+ * closes every ring made; either way the pool answers that step's errno from
825
+ * then on: the process falls back to descriptors for good.
826
+ * Answers the number of rings made or that errno, and writes each ring's
827
+ * descriptor to `fds`, which holds 65: the only descriptors the filter lets
828
+ * `io_uring_enter` take, then the keeper's after them, which the filter
829
+ * keeps every one of those numbers on (NURING-36). */
830
+ int32_t nish_uring_premake(int32_t n, int32_t slots, int32_t *fds) {
831
+ if (ur_pool.made) return ur_pool.rc;
832
+ ur_pool.made = 1;
833
+ if (n <= 0) return ur_pool.rc = -EPERM;
834
+ /* A restricted ring drops SINGLE_ISSUER and DEFER_TASKRUN, so it alone
835
+ would take a 5.19 or 6.0 kernel; the probe holds the pool to the floor
836
+ an unsandboxed set has, 6.1 (NURING-33). */
837
+ int32_t probed = ur_probe_once();
838
+ if (probed < 0) return ur_pool.rc = probed;
839
+ if (n > UR_POOL_MAX) n = UR_POOL_MAX;
840
+ if (slots < 1) slots = 1;
841
+ if (slots > UR_MAX_SLOTS) slots = UR_MAX_SLOTS;
842
+ ur_pool.z = (struct ur_sizes){(uint32_t)slots, UR_BUF_COUNT_DEFAULT, UR_BUF_SIZE_DEFAULT, UR_SQ_DEFAULT, UR_CQ_DEFAULT};
843
+ for (int i = 0; i < n; i++) {
844
+ int rc = ur_make_ring(&ur_pool.z, 1, &ur_pool.rings[i]);
845
+ if (rc < 0) {
846
+ for (int j = 0; j < i; j++) ur_free_ring(ur_pool.rings[j]);
847
+ memset(ur_pool.rings, 0, sizeof ur_pool.rings);
848
+ return ur_pool.rc = rc;
849
+ }
850
+ }
851
+ int keeper = ur_make_keeper();
852
+ if (keeper < 0) {
853
+ for (int j = 0; j < n; j++) ur_free_ring(ur_pool.rings[j]);
854
+ memset(ur_pool.rings, 0, sizeof ur_pool.rings);
855
+ return ur_pool.rc = keeper;
856
+ }
857
+ for (int i = 0; i < n; i++) fds[i] = ur_pool.fds[i] = ur_pool.rings[i]->fd;
858
+ fds[n] = ur_pool.keeper = keeper;
859
+ ur_pool.n = n;
860
+ return ur_pool.rc = n;
861
+ }
862
+
863
+ /* The slots of each ring `--sandbox` made, 0 when it made none, or -1 when
864
+ * it ran and made none: a set must open with the pool's sizes. */
865
+ int32_t nish_uring_pooled(void) {
866
+ if (!ur_pool.made) return 0;
867
+ return ur_pool.rc > 0 ? (int32_t)ur_pool.z.slots : -1;
868
+ }
869
+
870
+ #ifdef NISH_URING_TEST_HOOKS
871
+ /* Test-only: tests/run.js's sandbox section builds the runtime with
872
+ * -DNISH_URING_TEST_HOOKS to ask the kernel what a premade ring takes, and
873
+ * scripts/build.sh never passes it. Submits one entry of opcode `op` with
874
+ * submission flags `flags`, on descriptor `fd`, to premade ring `i` before a
875
+ * listener has taken it, and answers its completion's res: -EACCES is the
876
+ * ring's restriction. -ENOENT when no such ring was made or it was taken. */
877
+ int32_t nish_uring_test_submit_fd(int32_t i, int32_t op, int32_t flags, int32_t fd);
878
+ int32_t nish_uring_test_submit_fd(int32_t i, int32_t op, int32_t flags, int32_t fd) {
879
+ if (!ur_pool.made || ur_pool.rc <= 0 || i < 0 || i >= ur_pool.n || ur_pool.rings[i] == NULL) return -ENOENT;
880
+ struct ur_ring *r = ur_pool.rings[i];
881
+ struct ur_sqe *e = ur_sqe(r);
882
+ if (e == NULL) return -EBUSY;
883
+ e->opcode = (uint8_t)op;
884
+ e->flags = (uint8_t)flags;
885
+ e->fd = fd;
886
+ e->user_data = 1;
887
+ int rc;
888
+ do rc = ur_enter(r, r->to_submit, 1, UR_ENTER_GETEVENTS);
889
+ while (rc == -EINTR);
890
+ if (rc < 0) return rc;
891
+ r->to_submit = 0;
892
+ uint32_t head = *r->cq_head;
893
+ if (head == __atomic_load_n(r->cq_tail, __ATOMIC_ACQUIRE)) return -EAGAIN;
894
+ int32_t res = r->cqes[head & *r->cq_mask].res;
895
+ __atomic_store_n(r->cq_head, head + 1, __ATOMIC_RELEASE);
896
+ return res;
897
+ }
898
+ /* As `nish_uring_test_submit_fd`, on no file. */
899
+ int32_t nish_uring_test_submit(int32_t i, int32_t op, int32_t flags);
900
+ int32_t nish_uring_test_submit(int32_t i, int32_t op, int32_t flags) { return nish_uring_test_submit_fd(i, op, flags, -1); }
901
+ /* The number premade ring `i` was made at, whether or not a set has taken
902
+ * it since, or the keeper's for `i` equal to the ring count; -ENOENT for
903
+ * any other `i`. */
904
+ int32_t nish_uring_test_fd(int32_t i);
905
+ int32_t nish_uring_test_fd(int32_t i) {
906
+ if (!ur_pool.made || ur_pool.rc <= 0 || i < 0 || i > ur_pool.n) return -ENOENT;
907
+ return i == ur_pool.n ? ur_pool.keeper : ur_pool.fds[i];
908
+ }
909
+ #endif
910
+
911
+ static int64_t ur_now_ms(void) {
912
+ struct timespec t;
913
+ clock_gettime(CLOCK_MONOTONIC, &t);
914
+ return (int64_t)t.tv_sec * 1000 + t.tv_nsec / 1000000;
915
+ }
916
+
917
+ /* Keep min(ACCEPT_DEPTH, free slots) accepts in flight on the accepting ring,
918
+ * and only there (behaviours 2 and 3). A full acceptor with nothing in flight
919
+ * hands the job to the next ring with a free slot, making one when none has
920
+ * and the set may grow; with `rings_max` reached and every ring full,
921
+ * connections wait in the listener's backlog until a close frees a slot. */
922
+ static void ur_top_up(struct nish_uring_set *s) {
923
+ if (s->accept_stopped || s->nrings == 0) return;
924
+ if (s->accept_paused) {
925
+ if (ur_now_ms() < s->resume_ms) return;
926
+ s->accept_paused = 0;
927
+ }
928
+ struct ur_ring *r = s->rings[s->acceptor];
929
+ if (r->live + r->accepting >= (long)s->slots && r->accepting == 0) {
930
+ int moved = 0;
931
+ for (int i = 1; i <= s->nrings; i++) {
932
+ int j = (s->acceptor + i) % s->nrings;
933
+ if (s->rings[j]->live < (long)s->slots) {
934
+ s->acceptor = j;
935
+ moved = 1;
936
+ break;
937
+ }
938
+ }
939
+ if (!moved) {
940
+ int j = ur_add_ring(s);
941
+ if (j < 0) return;
942
+ s->acceptor = j;
943
+ }
944
+ r = s->rings[s->acceptor];
945
+ }
946
+ while (r->accepting < ACCEPT_DEPTH && r->live + r->accepting < (long)s->slots) {
947
+ struct ur_sqe *e = ur_sqe(r);
948
+ if (!e) break;
949
+ e->opcode = UR_OP_ACCEPT;
950
+ e->fd = s->listener;
951
+ e->file_index = UR_FILE_INDEX_ALLOC;
952
+ e->user_data = UR_ACCEPT;
953
+ r->accepting++;
954
+ }
955
+ long accepting = 0, rings = 0;
956
+ for (int i = 0; i < s->nrings; i++) {
957
+ accepting += s->rings[i]->accepting;
958
+ rings += s->rings[i]->accepting > 0;
959
+ }
960
+ s->stats.accepting = accepting;
961
+ if (rings > s->stats.max_accepting_rings) s->stats.max_accepting_rings = rings;
962
+ }
963
+
964
+ /* Submit the slot's first queued send, from where the kernel left off. */
965
+ static void ur_send_head(struct ur_ring *r, uint32_t slot, struct nish_uring_set *s) {
966
+ struct ur_send *q = r->sq_first[slot];
967
+ if (!q || q->in_flight) return;
968
+ struct ur_sqe *e = ur_sqe(r);
969
+ if (!e) {
970
+ s->stalled_sends++;
971
+ return;
972
+ }
973
+ e->opcode = UR_OP_SEND;
974
+ e->fd = (int32_t)slot;
975
+ e->flags = UR_SQE_FIXED_FILE;
976
+ e->addr = (uint64_t)(uintptr_t)(q->data + q->off);
977
+ e->len = q->len - q->off;
978
+ e->op_flags = MSG_NOSIGNAL;
979
+ e->user_data = (uint64_t)(uintptr_t)q | UR_SEND;
980
+ q->in_flight = 1;
981
+ }
982
+
983
+ static void ur_unlink_all(struct nish_uring_set *s, struct ur_send *q) {
984
+ if (q->prev_all) q->prev_all->next_all = q->next_all;
985
+ else s->all = q->next_all;
986
+ if (q->next_all) q->next_all->prev_all = q->prev_all;
987
+ free(q);
988
+ }
989
+
990
+ /* Drop a slot's queued sends. The one the kernel holds, if any, is left on
991
+ * the all-records list; its completion finds the generation moved on and
992
+ * frees it. */
993
+ static void ur_drop_sends(struct nish_uring_set *s, struct ur_ring *r, uint32_t slot) {
994
+ struct ur_send *q = r->sq_first[slot];
995
+ r->sq_first[slot] = r->sq_last[slot] = NULL;
996
+ r->qbytes[slot] = 0;
997
+ while (q) {
998
+ struct ur_send *next = q->next;
999
+ q->next = NULL;
1000
+ if (!q->in_flight) ur_unlink_all(s, q);
1001
+ q = next;
1002
+ }
1003
+ }
1004
+
1005
+ /* An accept that failed for this one peer; the next is submitted at once. */
1006
+ static int ur_transient_accept(int res) {
1007
+ return res == -EAGAIN || res == -EINTR || res == -ECONNABORTED || res == -EPROTO;
1008
+ }
1009
+
1010
+ /* An accept that found the kernel short of memory for a socket (NURING-28).
1011
+ * It clears as memory frees, so accepting pauses and resumes; submitting
1012
+ * again at once would spin on the same answer while the shortage lasts. */
1013
+ static int ur_pressure_accept(int res) { return res == -ENOMEM || res == -ENOBUFS; }
1014
+
1015
+ static void ur_event(struct nish_uring_event *ev, int kind, int ring, uint32_t slot, int res, const uint8_t *data) {
1016
+ ev->kind = kind;
1017
+ ev->ring = ring;
1018
+ ev->slot = (int32_t)slot;
1019
+ ev->res = res;
1020
+ ev->data = data;
1021
+ }
1022
+
1023
+ /* One completion. Answers 1 when it wrote an event. */
1024
+ static int ur_complete(struct nish_uring_set *s, int ri, const struct ur_cqe *c, struct nish_uring_event *ev) {
1025
+ struct ur_ring *r = s->rings[ri];
1026
+ uint64_t ud = c->user_data;
1027
+ int res = c->res;
1028
+ if ((ud & 7) == UR_SEND) {
1029
+ struct ur_send *q = (struct ur_send *)(uintptr_t)(ud & ~(uint64_t)7);
1030
+ q->in_flight = 0;
1031
+ uint32_t slot = q->slot;
1032
+ if ((r->st[slot] & ST_OPEN) == 0 || ST_GEN(r->st[slot]) != q->gen || r->sq_first[slot] != q) {
1033
+ ur_unlink_all(s, q);
1034
+ return 0;
1035
+ }
1036
+ if (res > 0) r->qbytes[slot] -= (uint32_t)res < r->qbytes[slot] ? (uint32_t)res : r->qbytes[slot];
1037
+ if (res > 0 && q->off + (uint32_t)res < q->len) {
1038
+ q->off += (uint32_t)res;
1039
+ s->stats.send_requeues++;
1040
+ } else if (res == -EINTR || res == -EAGAIN || res == -ENOBUFS) {
1041
+ s->stats.send_requeues++;
1042
+ } else if (res < 0) {
1043
+ /* q is the head and no longer in flight, so this frees it with the rest. */
1044
+ ur_drop_sends(s, r, slot);
1045
+ ur_event(ev, NISH_URING_SEND_FAILED, ri, slot, res, NULL);
1046
+ return 1;
1047
+ } else {
1048
+ r->sq_first[slot] = q->next;
1049
+ if (!q->next) r->sq_last[slot] = NULL;
1050
+ ur_unlink_all(s, q);
1051
+ }
1052
+ ur_send_head(r, slot, s);
1053
+ return 0;
1054
+ }
1055
+ unsigned op = (unsigned)(ud & 0xff);
1056
+ uint32_t gen = (uint32_t)(ud >> 8) & GEN_MASK;
1057
+ uint32_t slot = (uint32_t)(ud >> 32);
1058
+ if (op == UR_ACCEPT) {
1059
+ r->accepting--;
1060
+ res = UR_ACCEPT_RES(res);
1061
+ int wrote = 0;
1062
+ if (res >= 0 && (uint32_t)res < s->slots) {
1063
+ uint32_t at = (uint32_t)res;
1064
+ s->backoff_ms = 0;
1065
+ r->st[at] = (r->st[at] & ~(ST_ARMED | ST_PARKED | ST_HELD | ST_HUP)) | ST_OPEN;
1066
+ r->live++;
1067
+ s->stats.live++;
1068
+ ur_arm(r, at);
1069
+ ur_event(ev, NISH_URING_ACCEPTED, ri, at, 0, NULL);
1070
+ wrote = 1;
1071
+ } else if (res >= 0) {
1072
+ /* A slot past the table the set registered; the kernel never answers
1073
+ * one, so it is counted rather than trusted. */
1074
+ s->stats.bound_violations++;
1075
+ } else if (ur_pressure_accept(res)) {
1076
+ /* Accepts already in flight may fail the same way; one pause covers them. */
1077
+ if (!s->accept_paused) {
1078
+ s->accept_paused = 1;
1079
+ s->backoff_ms = s->backoff_ms ? s->backoff_ms * 2 : ACCEPT_BACKOFF_MIN_MS;
1080
+ if (s->backoff_ms > ACCEPT_BACKOFF_MAX_MS) s->backoff_ms = ACCEPT_BACKOFF_MAX_MS;
1081
+ s->resume_ms = ur_now_ms() + s->backoff_ms;
1082
+ s->stats.accept_pauses++;
1083
+ ur_event(ev, NISH_URING_ACCEPT_PAUSED, ri, 0, res, NULL);
1084
+ wrote = 1;
1085
+ }
1086
+ } else if (!ur_transient_accept(res)) {
1087
+ s->stats.accept_errors++;
1088
+ if (res == -ENFILE) s->stats.bound_violations++;
1089
+ if (!s->accept_stopped) {
1090
+ s->accept_stopped = 1;
1091
+ ur_event(ev, NISH_URING_ACCEPT_FAILED, ri, 0, res, NULL);
1092
+ wrote = 1;
1093
+ }
1094
+ }
1095
+ ur_top_up(s);
1096
+ return wrote;
1097
+ }
1098
+ if (op != UR_RECV) return 0; /* a close or cancel; nothing to report */
1099
+ int stale = slot >= s->slots || (r->st[slot] & ST_OPEN) == 0 || (ST_GEN(r->st[slot]) & GEN_MASK) != gen;
1100
+ int more = (c->flags & UR_CQE_F_MORE) != 0;
1101
+ uint32_t bid = c->flags >> UR_CQE_BUFFER_SHIFT;
1102
+ int has_buf = (c->flags & UR_CQE_F_BUFFER) != 0 && bid < s->buf_count;
1103
+ if (stale) {
1104
+ if (has_buf) ur_recycle(s, r, bid);
1105
+ return 0;
1106
+ }
1107
+ if (!more) r->st[slot] &= ~ST_ARMED;
1108
+ if (res > 0 && has_buf) {
1109
+ s->lent_ring[s->nlent] = (uint32_t)ri;
1110
+ s->lent_bid[s->nlent] = (uint16_t)bid;
1111
+ s->nlent++;
1112
+ if (!more && !(r->st[slot] & ST_HELD)) ur_arm(r, slot);
1113
+ ur_event(ev, NISH_URING_DATA, ri, slot, res, r->bufs + (size_t)bid * s->buf_size);
1114
+ return 1;
1115
+ }
1116
+ if (has_buf) ur_recycle(s, r, bid);
1117
+ /* Only a hold cancels a live slot's recv (a close moves the generation on
1118
+ * first). The recv stays down while the slot is held, and one let go before
1119
+ * the cancel landed is armed again; a held recv out of buffers stays down. */
1120
+ if (!more && res == -ECANCELED) {
1121
+ if (!(r->st[slot] & ST_HELD)) ur_arm(r, slot);
1122
+ return 0;
1123
+ }
1124
+ if (!more && res == -ENOBUFS && (r->st[slot] & ST_HELD)) return 0;
1125
+ if (res == -ENOBUFS) {
1126
+ s->stats.nobufs_rearms++;
1127
+ if (!more && !(r->st[slot] & ST_PARKED)) {
1128
+ r->st[slot] |= ST_PARKED;
1129
+ r->parked[r->nparked++] = slot;
1130
+ }
1131
+ return 0;
1132
+ }
1133
+ if (more) return 0;
1134
+ r->st[slot] |= ST_HUP;
1135
+ ur_event(ev, NISH_URING_HUP, ri, slot, res, NULL);
1136
+ return 1;
1137
+ }
1138
+
1139
+ /* Take completions until the CQ is empty or `cap` events are written; what
1140
+ * does not fit stays in the CQ for the next wait. */
1141
+ static int ur_reap(struct nish_uring_set *s, int ri, struct nish_uring_event *ev, int cap) {
1142
+ struct ur_ring *r = s->rings[ri];
1143
+ int n = 0;
1144
+ uint32_t head = *r->cq_head;
1145
+ for (;;) {
1146
+ uint32_t tail = __atomic_load_n(r->cq_tail, __ATOMIC_ACQUIRE);
1147
+ if (head == tail || n >= cap) break;
1148
+ struct ur_cqe c = r->cqes[head & *r->cq_mask];
1149
+ head++;
1150
+ /* Give the entry back before handling it, so a completion's handler that
1151
+ * flushes (an accept topping up) frees room in the CQ for what it makes. */
1152
+ __atomic_store_n(r->cq_head, head, __ATOMIC_RELEASE);
1153
+ n += ur_complete(s, ri, &c, ev + n);
1154
+ }
1155
+ return n;
1156
+ }
1157
+
1158
+ /* Reap, submit, and enter again while the kernel says it holds more for this
1159
+ * ring (behaviour 4): IORING_SQ_TASKRUN for completions DEFER_TASKRUN has not
1160
+ * run, IORING_SQ_CQ_OVERFLOW for ones the CQ had no room for. A flush that
1161
+ * answers -EBUSY (a kernel that refuses submissions while completions
1162
+ * overflow) is retried at once with no backoff: the reap before it has
1163
+ * freed CQ room, so the next pass moves the overflow along. The guard only
1164
+ * bounds a kernel that keeps a flag up without progress; the next wait
1165
+ * starts again from here. */
1166
+ static int ur_service(struct nish_uring_set *s, int ri, struct nish_uring_event *ev, int cap) {
1167
+ struct ur_ring *r = s->rings[ri];
1168
+ int n = 0;
1169
+ for (int guard = 0; guard < 1 << 16; guard++) {
1170
+ n += ur_reap(s, ri, ev + n, cap - n);
1171
+ int rc = ur_flush(r);
1172
+ if (n >= cap) break;
1173
+ uint32_t flags = __atomic_load_n(r->sq_flags, __ATOMIC_ACQUIRE);
1174
+ if (flags & (UR_SQ_TASKRUN | UR_SQ_CQ_OVERFLOW)) {
1175
+ if (flags & UR_SQ_TASKRUN) s->stats.taskrun_reentries++;
1176
+ if (flags & UR_SQ_CQ_OVERFLOW) s->stats.overflow_drains++;
1177
+ rc = ur_enter(r, 0, 0, UR_ENTER_GETEVENTS);
1178
+ if (rc < 0 && rc != -EINTR && rc != -EBUSY && rc != -EAGAIN) break;
1179
+ continue;
1180
+ }
1181
+ if (rc == -EBUSY) continue;
1182
+ if (*r->cq_head == __atomic_load_n(r->cq_tail, __ATOMIC_ACQUIRE)) break;
1183
+ }
1184
+ return n;
1185
+ }
1186
+
1187
+ int32_t nish_uring_open(struct nish_uring_set **out, int32_t listener, const struct nish_uring_opts *o) {
1188
+ *out = NULL;
1189
+ int32_t ok = nish_uring_probe();
1190
+ if (ok < 0) return ok;
1191
+ struct nish_uring_opts d;
1192
+ memset(&d, 0, sizeof d);
1193
+ if (o) d = *o;
1194
+ if (listener < 0 || d.slots < 0 || d.rings_max < 0 || d.sq_entries < 0 || d.cq_entries < 0 || d.buf_count < 0 ||
1195
+ d.buf_size < 0)
1196
+ return -EINVAL;
1197
+ if (d.slots == 0) {
1198
+ struct rlimit rl;
1199
+ if (getrlimit(RLIMIT_NOFILE, &rl) != 0) return -errno;
1200
+ d.slots = rl.rlim_cur == RLIM_INFINITY || rl.rlim_cur > UR_MAX_SLOTS ? UR_MAX_SLOTS : (int32_t)rl.rlim_cur;
1201
+ }
1202
+ if (d.slots > UR_MAX_SLOTS) return -EINVAL;
1203
+ if (d.rings_max == 0) d.rings_max = 64;
1204
+ if (d.sq_entries == 0) d.sq_entries = UR_SQ_DEFAULT;
1205
+ if (d.cq_entries == 0) d.cq_entries = UR_CQ_DEFAULT;
1206
+ if (d.cq_entries < d.sq_entries) d.cq_entries = d.sq_entries;
1207
+ if (d.buf_count == 0) d.buf_count = UR_BUF_COUNT_DEFAULT;
1208
+ if (d.buf_size == 0) d.buf_size = UR_BUF_SIZE_DEFAULT;
1209
+ if (d.rings_max > 4096 || d.buf_count > 32768 || (d.buf_count & (d.buf_count - 1)) != 0 || d.buf_size > (1 << 20))
1210
+ return -EINVAL;
1211
+ /* A pooled ring was made at its own sizes, before the program could ask. */
1212
+ if (ur_pool.made) {
1213
+ d.slots = (int32_t)ur_pool.z.slots;
1214
+ d.sq_entries = (int32_t)ur_pool.z.sq_entries;
1215
+ d.cq_entries = (int32_t)ur_pool.z.cq_entries;
1216
+ d.buf_count = (int32_t)ur_pool.z.buf_count;
1217
+ d.buf_size = (int32_t)ur_pool.z.buf_size;
1218
+ }
1219
+ struct nish_uring_set *s = calloc(1, sizeof *s);
1220
+ if (!s) return -ENOMEM;
1221
+ s->listener = listener;
1222
+ s->slots = (uint32_t)d.slots;
1223
+ s->rings_max = d.rings_max;
1224
+ s->sq_entries = (uint32_t)d.sq_entries;
1225
+ s->cq_entries = (uint32_t)d.cq_entries;
1226
+ s->buf_count = (uint32_t)d.buf_count;
1227
+ s->buf_size = (uint32_t)d.buf_size;
1228
+ s->rings = calloc((size_t)d.rings_max, sizeof *s->rings);
1229
+ s->ep = epoll_create1(EPOLL_CLOEXEC);
1230
+ if (!s->rings || s->ep < 0) {
1231
+ int rc = s->ep < 0 ? -errno : -ENOMEM;
1232
+ if (s->ep >= 0) close(s->ep);
1233
+ free(s->rings);
1234
+ free(s);
1235
+ return rc;
1236
+ }
1237
+ int rc = ur_add_ring(s);
1238
+ if (rc < 0) {
1239
+ close(s->ep);
1240
+ free(s->rings);
1241
+ free(s);
1242
+ return rc;
1243
+ }
1244
+ ur_top_up(s);
1245
+ (void)ur_flush(s->rings[0]);
1246
+ *out = s;
1247
+ return 0;
1248
+ }
1249
+
1250
+ /* The epoll descriptor a caller's own loop may wait on beside other sources.
1251
+ * It is readable when a ring's eventfd was signalled since that ring was last
1252
+ * serviced. It is not readable for events a wait left behind because `cap`
1253
+ * was full, so a caller that got `cap` events calls wait again (with a
1254
+ * timeout of 0) before it sleeps on this descriptor. Sends and closes are
1255
+ * only queued: the next wait hands them to the kernel, so a caller calls
1256
+ * wait after them, too, before it sleeps here. A wait returns with nothing
1257
+ * left queued unless the kernel refused the submission (-EBUSY while
1258
+ * completions overflow, -EAGAIN or -ENOMEM for memory): then the ring has
1259
+ * completions to reap or the refusal is transient, and the next wait
1260
+ * submits them again.
1261
+ *
1262
+ * Readable is not the whole answer: the kernel can hold a ring's work with
1263
+ * IORING_SQ_TASKRUN up and its eventfd never signalled (NURING-8). A caller
1264
+ * that sleeps on this descriptor, alone or beside other sources, asks
1265
+ * `nish_uring_sleep_ms` right before it sleeps and sleeps no longer than it
1266
+ * answers, then calls wait (with a timeout of 0) whether or not the
1267
+ * descriptor became readable. */
1268
+ int32_t nish_uring_fd(const struct nish_uring_set *s) { return s->ep; }
1269
+
1270
+ /* Whether the kernel holds work for one of the ring's completions to post:
1271
+ * deferred task work (IORING_SQ_TASKRUN) or completions the CQ had no room
1272
+ * for (IORING_SQ_CQ_OVERFLOW). Its eventfd may say nothing of either. */
1273
+ static int ur_flagged(const struct ur_ring *r) {
1274
+ return (__atomic_load_n(r->sq_flags, __ATOMIC_ACQUIRE) & (UR_SQ_TASKRUN | UR_SQ_CQ_OVERFLOW)) != 0;
1275
+ }
1276
+
1277
+ /* The longest sleep on a set: the kernel's eventfd signal can be lost
1278
+ * (NURING-8), so the timer is what wakes a sleeper to service a ring the
1279
+ * kernel flagged. 10 ms bounds a lost wake's delay; idle, it costs a set 100
1280
+ * wakes a second. */
1281
+ #define UR_SLEEP_MAX_MS 10
1282
+
1283
+ /* How long a caller may sleep on `nish_uring_fd` before it calls wait, given
1284
+ * the longest it wants (`timeout_ms`, -1 for ever). Answers 0 while a wait has
1285
+ * work it can do now: a ring the kernel flagged, completions not yet reaped,
1286
+ * buffers the last wait lent, or recvs parked or sends stalled on a full SQ
1287
+ * that every ring has room for again. Otherwise answers `timeout_ms` cut to
1288
+ * UR_SLEEP_MAX_MS. Submissions the kernel refused, and what waits on them, are
1289
+ * retried after that bound, not at once, so a refusal that persists does not
1290
+ * spin the caller. */
1291
+ int32_t nish_uring_sleep_ms(const struct nish_uring_set *s, int32_t timeout_ms) {
1292
+ int room = 1, parked = 0;
1293
+ for (int ri = 0; ri < s->nrings; ri++) {
1294
+ const struct ur_ring *r = s->rings[ri];
1295
+ if (ur_flagged(r) || *r->cq_head != __atomic_load_n(r->cq_tail, __ATOMIC_ACQUIRE)) return 0;
1296
+ if (r->to_submit) room = 0;
1297
+ if (r->nparked) parked = 1;
1298
+ }
1299
+ if (s->nlent || (room && (parked || s->stalled_sends))) return 0;
1300
+ int32_t bound = UR_SLEEP_MAX_MS;
1301
+ if (s->accept_paused) {
1302
+ int64_t left = s->resume_ms - ur_now_ms();
1303
+ if (left <= 0) return 0;
1304
+ if (left < bound) bound = (int32_t)left;
1305
+ }
1306
+ return timeout_ms < 0 || timeout_ms > bound ? bound : timeout_ms;
1307
+ }
1308
+
1309
+ /* What the last wait left to do: give back the buffers it lent, re-arm the
1310
+ * recvs it parked, and submit the sends that found the SQ full. */
1311
+ static void ur_catch_up(struct nish_uring_set *s) {
1312
+ if (s->accept_paused) ur_top_up(s); /* accepting resumes once the back-off ends */
1313
+ for (int i = 0; i < s->nlent; i++) ur_recycle(s, s->rings[s->lent_ring[i]], s->lent_bid[i]);
1314
+ s->nlent = 0;
1315
+ for (int ri = 0; ri < s->nrings; ri++) {
1316
+ struct ur_ring *r = s->rings[ri];
1317
+ uint32_t n = r->nparked;
1318
+ r->nparked = 0;
1319
+ for (uint32_t i = 0; i < n; i++) {
1320
+ uint32_t slot = r->parked[i];
1321
+ r->st[slot] &= ~ST_PARKED;
1322
+ if ((r->st[slot] & (ST_OPEN | ST_ARMED | ST_HELD)) == ST_OPEN) ur_arm(r, slot);
1323
+ }
1324
+ }
1325
+ /* Scanning every slot of every ring costs rings * slots, but only after a
1326
+ * send found the SQ full, which a queue of `sq_entries` (1,024 by default)
1327
+ * makes rare; keeping a list of the stalled slots would cost every send. */
1328
+ if (s->stalled_sends) {
1329
+ s->stalled_sends = 0;
1330
+ for (int ri = 0; ri < s->nrings; ri++)
1331
+ for (uint32_t slot = 0; slot < s->slots; slot++)
1332
+ if (s->rings[ri]->sq_first[slot]) ur_send_head(s->rings[ri], slot, s);
1333
+ }
1334
+ }
1335
+
1336
+ /* Hand every ring's queued submissions to the kernel before a wait returns
1337
+ * or sleeps. Servicing a ring submits its own, but an accept or a close there
1338
+ * can move the accepting job to a ring the wait already passed or will not
1339
+ * reach (`cap` full, or not ready), and that ring's new accepts would sit in
1340
+ * user space while the caller sleeps on `nish_uring_fd`. A refused flush
1341
+ * leaves them queued for the next wait, as ur_flush says. */
1342
+ static void ur_submit_queued(struct nish_uring_set *s) {
1343
+ for (int ri = 0; ri < s->nrings; ri++)
1344
+ if (s->rings[ri]->to_submit) (void)ur_flush(s->rings[ri]);
1345
+ }
1346
+
1347
+ /* Wait for events and write at most `cap` of them, at most 256. Answers the
1348
+ * count or a negative errno. A DATA event's bytes are the set's buffer until
1349
+ * the next wait. A `timeout_ms` of -1 waits until there are events (or answers
1350
+ * 0 when a signal interrupts it); 0 does not sleep. Any other timeout is a
1351
+ * most, not a least: the wait sleeps no longer than `nish_uring_sleep_ms`
1352
+ * answers (NURING-8), so it can answer 0 early, while work is pending or
1353
+ * after UR_SLEEP_MAX_MS, and a caller that wants the whole timeout waits again
1354
+ * for what is left of it. */
1355
+ int32_t nish_uring_wait(struct nish_uring_set *s, int32_t timeout_ms, struct nish_uring_event *ev, int32_t cap) {
1356
+ if (cap <= 0) return -EINVAL;
1357
+ if (cap > EVENTS_MAX) cap = EVENTS_MAX;
1358
+ again:
1359
+ ur_catch_up(s);
1360
+ int n = 0;
1361
+ for (int ri = 0; ri < s->nrings && n < cap; ri++) n += ur_service(s, ri, ev + n, cap - n);
1362
+ ur_submit_queued(s);
1363
+ if (n > 0) return n;
1364
+ /* No eventfd is trusted to end the sleep (NURING-8): the bound does, and the
1365
+ * flagged rings are serviced below whether an eventfd was read or not. */
1366
+ struct epoll_event ready[64];
1367
+ int k = epoll_wait(s->ep, ready, 64, nish_uring_sleep_ms(s, timeout_ms));
1368
+ if (k < 0) return errno == EINTR ? 0 : -errno;
1369
+ for (int i = 0; i < k && n < cap; i++) {
1370
+ uint32_t ri = ready[i].data.u32;
1371
+ if (ri >= (uint32_t)s->nrings) continue;
1372
+ struct ur_ring *r = s->rings[ri];
1373
+ uint64_t v;
1374
+ (void)!read(r->efd, &v, sizeof v);
1375
+ (void)ur_enter(r, 0, 0, UR_ENTER_GETEVENTS);
1376
+ n += ur_service(s, (int)ri, ev + n, cap - n);
1377
+ }
1378
+ for (int ri = 0; ri < s->nrings && n < cap; ri++)
1379
+ if (ur_flagged(s->rings[ri])) n += ur_service(s, ri, ev + n, cap - n);
1380
+ ur_submit_queued(s);
1381
+ if (n == 0 && timeout_ms < 0) goto again;
1382
+ return n;
1383
+ }
1384
+
1385
+ static struct ur_ring *ur_open_slot(struct nish_uring_set *s, int32_t ring, int32_t slot) {
1386
+ if (ring < 0 || ring >= s->nrings || slot < 0 || (uint32_t)slot >= s->slots) return NULL;
1387
+ struct ur_ring *r = s->rings[ring];
1388
+ return (r->st[slot] & ST_OPEN) ? r : NULL;
1389
+ }
1390
+
1391
+ /* Queue `n` bytes for (ring, slot). They are copied, so the caller's buffer
1392
+ * is free on return; a failure comes back later as a SEND_FAILED event. */
1393
+ int32_t nish_uring_send(struct nish_uring_set *s, int32_t ring, int32_t slot, const uint8_t *p, int32_t n) {
1394
+ struct ur_ring *r = ur_open_slot(s, ring, slot);
1395
+ if (!r) return -EBADF;
1396
+ if (n < 0) return -EINVAL;
1397
+ if (n == 0) return 0;
1398
+ struct ur_send *q = malloc(sizeof *q + (size_t)n);
1399
+ if (!q) return -ENOMEM;
1400
+ memcpy(q->data, p, (size_t)n);
1401
+ q->next = NULL;
1402
+ q->prev_all = NULL;
1403
+ q->next_all = s->all;
1404
+ if (s->all) s->all->prev_all = q;
1405
+ s->all = q;
1406
+ q->slot = (uint32_t)slot;
1407
+ q->gen = ST_GEN(r->st[slot]);
1408
+ q->off = 0;
1409
+ q->len = (uint32_t)n;
1410
+ q->in_flight = 0;
1411
+ r->qbytes[slot] += (uint32_t)n;
1412
+ if (r->sq_last[slot]) {
1413
+ r->sq_last[slot]->next = q;
1414
+ } else {
1415
+ r->sq_first[slot] = q;
1416
+ }
1417
+ r->sq_last[slot] = q;
1418
+ ur_send_head(r, (uint32_t)slot, s);
1419
+ return n;
1420
+ }
1421
+
1422
+ /* Cancel the slot's recv, close the slot, and move its generation on, so
1423
+ * every completion still on its way for it is stale. The freed slot goes to
1424
+ * the accepting job. -EAGAIN when the SQ has no room for both entries, with
1425
+ * nothing changed. */
1426
+ int32_t nish_uring_close(struct nish_uring_set *s, int32_t ring, int32_t slot) {
1427
+ struct ur_ring *r = ur_open_slot(s, ring, slot);
1428
+ if (!r) return -EBADF;
1429
+ uint32_t head = __atomic_load_n(r->sq_head, __ATOMIC_ACQUIRE);
1430
+ if (r->sq_local_tail - head + 2 > r->sq_entries) {
1431
+ (void)ur_flush(r);
1432
+ head = __atomic_load_n(r->sq_head, __ATOMIC_ACQUIRE);
1433
+ if (r->sq_local_tail - head + 2 > r->sq_entries) return -EAGAIN;
1434
+ }
1435
+ uint32_t st = r->st[slot];
1436
+ struct ur_sqe *e = ur_sqe(r);
1437
+ e->opcode = UR_OP_ASYNC_CANCEL;
1438
+ e->fd = slot;
1439
+ e->op_flags = UR_CANCEL_FD | UR_CANCEL_FD_FIXED | UR_CANCEL_ALL;
1440
+ e->flags = UR_SQE_CQE_SKIP_SUCCESS;
1441
+ e->user_data = ur_tag(UR_CANCEL, st, (uint32_t)slot);
1442
+ e = ur_sqe(r);
1443
+ e->opcode = UR_OP_CLOSE;
1444
+ e->file_index = (uint32_t)slot + 1;
1445
+ e->flags = UR_SQE_CQE_SKIP_SUCCESS;
1446
+ e->user_data = ur_tag(UR_CLOSE, st, (uint32_t)slot);
1447
+ ur_drop_sends(s, r, (uint32_t)slot);
1448
+ r->st[slot] = ((ST_GEN(st) + 1) & GEN_MASK) << 8;
1449
+ r->live--;
1450
+ s->stats.live--;
1451
+ ur_top_up(s);
1452
+ return 0;
1453
+ }
1454
+
1455
+ /* The bytes queued for (ring, slot) that the kernel has not yet sent, or -1
1456
+ * for a slot that is not open. runtime-net.c bounds a connection's send area
1457
+ * with it (NURING-2): a successful send makes no event, so the caller asks. */
1458
+ int64_t nish_uring_queued(const struct nish_uring_set *s, int32_t ring, int32_t slot) {
1459
+ if (ring < 0 || ring >= s->nrings || slot < 0 || (uint32_t)slot >= s->slots) return -1;
1460
+ const struct ur_ring *r = s->rings[ring];
1461
+ return (r->st[slot] & ST_OPEN) ? (int64_t)r->qbytes[slot] : -1;
1462
+ }
1463
+
1464
+ /* 1 when no accept is in flight and none can be: every ring's table is full
1465
+ * and the set has `rings_max` rings or could not make another. A connection
1466
+ * then waits in the listener's backlog, and tcpAccept answers -23
1467
+ * (NURING-6). A close frees a slot and starts accepting again. */
1468
+ int32_t nish_uring_full(const struct nish_uring_set *s) {
1469
+ if (s->accept_stopped || s->accept_paused) return 0;
1470
+ for (int i = 0; i < s->nrings; i++) {
1471
+ const struct ur_ring *r = s->rings[i];
1472
+ if (r->accepting > 0 || r->live < (long)s->slots) return 0;
1473
+ }
1474
+ return 1;
1475
+ }
1476
+
1477
+ /* Hold (`on` 1) or let go (`on` 0) a slot's receive. A hold cancels the
1478
+ * slot's multishot recv by its tag, not by its descriptor, so the slot's sends
1479
+ * in flight go on, and keeps it from being armed again; the bytes the kernel
1480
+ * received before the cancel takes effect are still reported. runtime-net.c
1481
+ * holds a slot whose receive queue reaches its bound, so a peer the program
1482
+ * does not read cannot grow it (NURING-9). Letting go arms the recv again.
1483
+ * -EBADF for a slot that is not open; -EAGAIN, nothing changed, when the SQ
1484
+ * has no room for the cancel. */
1485
+ int32_t nish_uring_hold(struct nish_uring_set *s, int32_t ring, int32_t slot, int32_t on) {
1486
+ struct ur_ring *r = ur_open_slot(s, ring, slot);
1487
+ if (!r) return -EBADF;
1488
+ uint32_t st = r->st[slot];
1489
+ if (!on) {
1490
+ r->st[slot] = st & ~ST_HELD;
1491
+ if ((st & (ST_ARMED | ST_PARKED)) == 0) ur_arm(r, (uint32_t)slot);
1492
+ return 0;
1493
+ }
1494
+ if (st & ST_HELD) return 0;
1495
+ if (st & ST_ARMED) {
1496
+ struct ur_sqe *e = ur_sqe(r);
1497
+ if (!e) return -EAGAIN;
1498
+ e->opcode = UR_OP_ASYNC_CANCEL;
1499
+ e->addr = ur_tag(UR_RECV, st, (uint32_t)slot);
1500
+ e->flags = UR_SQE_CQE_SKIP_SUCCESS;
1501
+ e->user_data = ur_tag(UR_CANCEL, st, (uint32_t)slot);
1502
+ }
1503
+ r->st[slot] = st | ST_HELD;
1504
+ return 0;
1505
+ }
1506
+
1507
+ void nish_uring_stats(const struct nish_uring_set *s, struct nish_uring_stats *st) { *st = s->stats; }
1508
+
1509
+ /* Close every ring, which ends whatever the kernel still held, and free the
1510
+ * sends it held them for. The caller's listener stays open: it is theirs. */
1511
+ void nish_uring_destroy(struct nish_uring_set *s) {
1512
+ if (!s) return;
1513
+ for (int i = 0; i < s->nrings; i++) ur_free_ring(s->rings[i]);
1514
+ while (s->all) {
1515
+ struct ur_send *q = s->all;
1516
+ s->all = q->next_all;
1517
+ free(q);
1518
+ }
1519
+ close(s->ep);
1520
+ free(s->rings);
1521
+ free(s);
1522
+ }
1523
+
1524
+ #else /* not Linux: no io_uring, so a set is never available */
1525
+
1526
+ int32_t nish_uring_probe(void) { return -38; }
1527
+ int32_t nish_uring_premake(int32_t n, int32_t slots, int32_t *fds) {
1528
+ (void)n;
1529
+ (void)slots;
1530
+ (void)fds;
1531
+ return -38;
1532
+ }
1533
+ int32_t nish_uring_pooled(void) { return 0; }
1534
+ int32_t nish_uring_open(struct nish_uring_set **out, int32_t listener, const struct nish_uring_opts *opts) {
1535
+ (void)listener;
1536
+ (void)opts;
1537
+ *out = NULL;
1538
+ return -38;
1539
+ }
1540
+ int32_t nish_uring_fd(const struct nish_uring_set *s) {
1541
+ (void)s;
1542
+ return -38;
1543
+ }
1544
+ int32_t nish_uring_sleep_ms(const struct nish_uring_set *s, int32_t timeout_ms) {
1545
+ (void)s;
1546
+ return timeout_ms;
1547
+ }
1548
+ int32_t nish_uring_wait(struct nish_uring_set *s, int32_t timeout_ms, struct nish_uring_event *ev, int32_t cap) {
1549
+ (void)s;
1550
+ (void)timeout_ms;
1551
+ (void)ev;
1552
+ (void)cap;
1553
+ return -38;
1554
+ }
1555
+ int32_t nish_uring_send(struct nish_uring_set *s, int32_t ring, int32_t slot, const uint8_t *p, int32_t n) {
1556
+ (void)s;
1557
+ (void)ring;
1558
+ (void)slot;
1559
+ (void)p;
1560
+ (void)n;
1561
+ return -38;
1562
+ }
1563
+ int32_t nish_uring_close(struct nish_uring_set *s, int32_t ring, int32_t slot) {
1564
+ (void)s;
1565
+ (void)ring;
1566
+ (void)slot;
1567
+ return -38;
1568
+ }
1569
+ int64_t nish_uring_queued(const struct nish_uring_set *s, int32_t ring, int32_t slot) {
1570
+ (void)s;
1571
+ (void)ring;
1572
+ (void)slot;
1573
+ return -1;
1574
+ }
1575
+ int32_t nish_uring_full(const struct nish_uring_set *s) {
1576
+ (void)s;
1577
+ return 0;
1578
+ }
1579
+ int32_t nish_uring_hold(struct nish_uring_set *s, int32_t ring, int32_t slot, int32_t on) {
1580
+ (void)s;
1581
+ (void)ring;
1582
+ (void)slot;
1583
+ (void)on;
1584
+ return -38;
1585
+ }
1586
+ void nish_uring_stats(const struct nish_uring_set *s, struct nish_uring_stats *st) {
1587
+ (void)s;
1588
+ memset(st, 0, sizeof *st);
1589
+ }
1590
+ void nish_uring_destroy(struct nish_uring_set *s) { (void)s; }
1591
+ #endif
1592
+ #endif