Line data Source code
1 : /*
2 : MIT License
3 :
4 : Copyright (c) 2026 - A bunch of nerds
5 :
6 : Permission is hereby granted, free of charge, to any person obtaining a copy
7 : of this software and associated documentation files (the "Software"), to deal
8 : in the Software without restriction, including without limitation the rights
9 : to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 : copies of the Software, and to permit persons to whom the Software is
11 : furnished to do so, subject to the following conditions:
12 :
13 : The above copyright notice and this permission notice shall be included in all
14 : copies or substantial portions of the Software.
15 :
16 : THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 : IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 : FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 : AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 : LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 : OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 : SOFTWARE.
23 : */
24 :
25 : // Internal only. The readiness interface behind the event loop and cselect():
26 : // epoll(7) on Linux and kqueue(2) on the BSDs and macOS. The interface is
27 : // epoll's. On Linux every name below is the epoll name, so the code compiles to
28 : // plain epoll; elsewhere the same names emulate epoll on top of kqueue:
29 : //
30 : // A mask with IN, RDHUP, ERR or HUP registers the read filter, OUT the write
31 : // filter, and a mask with neither deletes both (like an epoll DEL). OUT without
32 : // IN or RDHUP arms the write filter alone, so the EOF of the receive direction
33 : // isn't reported. Without IN a socket's read filter has a low-water mark that
34 : // no read reaches, so it reports only EOF and errors, with EV_CLEAR; a pipe,
35 : // FIFO or terminal ignores that mark and is watched by the filter of the end it
36 : // was opened for. ONESHOT becomes EV_DISPATCH (never on an EV_CLEAR filter). A
37 : // MOD that flips IN must carry CCOL_POLL_READ_MODE_CHANGE, because kqueue keeps
38 : // the trigger flags a filter got at creation.
39 : //
40 : // ccol_poll_wait() makes no system call on an fd, since another thread can
41 : // close it as soon as the wait returns. It marks a read filter EOF instead, and
42 : // the caller calls ccol_poll_refine() where it can prove the fd is still open
43 : // (the event loop does it under the stripe lock that removal takes). Only a
44 : // refined event carries the bits epoll would give for that fd and mask, and it
45 : // can refine to no bit at all, which the caller ignores. An ADD of a regular
46 : // file or a directory fails with EPERM as in epoll. A ccol_poll_fdinfo (may be
47 : // NULL) caches what the fd is and how its write filter was created, so a MOD
48 : // asks the kernel nothing; keep it under the same lock as every call for the
49 : // fd.
50 : //
51 : // When the event loop needs something new from the kernel, add it here in epoll
52 : // terms and emulate it on kqueue, so the loop keeps one set of semantics.
53 :
54 : #ifndef CCOL_INTERNAL_CPOLL_H
55 : #define CCOL_INTERNAL_CPOLL_H
56 :
57 : #include <errno.h>
58 : #include <stdint.h>
59 :
60 : #if defined(__linux__)
61 :
62 : #include <sys/epoll.h>
63 :
64 : typedef struct epoll_event ccol_poll_event;
65 :
66 : // epoll needs to know nothing about an fd; see the kqueue version below.
67 : typedef uint8_t ccol_poll_fdinfo;
68 :
69 : // Interest and report bits, control operations and the calls themselves are
70 : // the epoll ones, so the Linux build is plain epoll. ccol_poll_create(),
71 : // ccol_poll_ctl() and ccol_poll_wait() evaluate to what the epoll call gives;
72 : // ccol_poll_ctl() ignores info. CCOL_POLL_READ_MODE_CHANGE is 0 since epoll
73 : // rebuilds nothing.
74 : #define CCOL_POLL_IN EPOLLIN
75 : #define CCOL_POLL_OUT EPOLLOUT
76 : #define CCOL_POLL_RDHUP EPOLLRDHUP
77 : #define CCOL_POLL_ERR EPOLLERR
78 : #define CCOL_POLL_HUP EPOLLHUP
79 : #define CCOL_POLL_ONESHOT EPOLLONESHOT
80 : #define CCOL_POLL_READ_MODE_CHANGE 0u
81 :
82 : #define CCOL_POLL_CTL_ADD EPOLL_CTL_ADD
83 : #define CCOL_POLL_CTL_MOD EPOLL_CTL_MOD
84 : #define CCOL_POLL_CTL_DEL EPOLL_CTL_DEL
85 :
86 : #define ccol_poll_create() epoll_create1(EPOLL_CLOEXEC)
87 : #define ccol_poll_ctl(pfd, op, fd, ev, info) \
88 : ((void)(info), epoll_ctl((pfd), (op), (fd), (ev)))
89 : #define ccol_poll_wait(pfd, evs, max, timeout_ms) \
90 : epoll_wait((pfd), (evs), (max), (timeout_ms))
91 :
92 : // Does nothing with epoll, whose events already carry the right bits; it
93 : // exists so the callers need no #ifdef.
94 396325 : static inline void ccol_poll_refine(ccol_poll_event *ev, int fd, uint32_t mask,
95 : ccol_poll_fdinfo *info) {
96 396325 : (void)ev;
97 396325 : (void)fd;
98 396325 : (void)mask;
99 396325 : (void)info;
100 396325 : }
101 :
102 : #elif defined(__FreeBSD__) || defined(__APPLE__) || defined(__OpenBSD__)
103 :
104 : #include <fcntl.h>
105 : #include <limits.h>
106 : #include <poll.h>
107 : #include <stdbool.h>
108 : #include <stddef.h>
109 : #include <sys/event.h>
110 : #include <sys/socket.h>
111 : #include <sys/stat.h>
112 : #if defined(__APPLE__)
113 : #include <libproc.h>
114 : #include <sys/proc_info.h>
115 : #endif
116 : #include <sys/time.h>
117 : #include <sys/types.h>
118 : #include <time.h>
119 : #include <unistd.h>
120 :
121 : // An event's 64-bit tag rides in the pointer-sized udata of its kevent.
122 : _Static_assert(sizeof(void *) >= sizeof(uint64_t),
123 : "the kqueue backend needs 64-bit pointers");
124 :
125 : // The epoll-shaped event, overlaid on a struct kevent so the wait writes into
126 : // the caller's array and allocates nothing.
127 : typedef union ccol_poll_event {
128 : struct {
129 : uint32_t events;
130 : union {
131 : void *ptr;
132 : uint64_t u64;
133 : } data;
134 : };
135 : struct kevent ccol__kev;
136 : } ccol_poll_event;
137 :
138 : // The epoll bit values.
139 : #define CCOL_POLL_IN 0x001u
140 : #define CCOL_POLL_OUT 0x004u
141 : #define CCOL_POLL_ERR 0x008u
142 : #define CCOL_POLL_HUP 0x010u
143 : #define CCOL_POLL_RDHUP 0x2000u
144 : #define CCOL_POLL_ONESHOT (1u << 30)
145 : // Flag for a MOD whose CCOL_POLL_IN differs from the previous mask: The read
146 : // filter is deleted and created again, since kqueue keeps its trigger flags.
147 : #define CCOL_POLL_READ_MODE_CHANGE (1u << 29)
148 :
149 : // Marks that ccol_poll_wait() leaves for ccol_poll_refine(): A read filter
150 : // EOF, an error it reported, data still queued, and a report from a socket's
151 : // error-only read filter (which, without EOF, is a pending socket error).
152 : #define CCOL__POLL_EOF (1u << 28)
153 : #define CCOL__POLL_EOF_ERR (1u << 27)
154 : #define CCOL__POLL_EOF_DATA (1u << 26)
155 : #define CCOL__POLL_ERR_ONLY_FILTER (1u << 25)
156 :
157 : // The udata bit that marks the error-only read filter. Every caller tag has it
158 : // clear: An event loop entry is a user-space address and cselect() uses bit 63
159 : // with a descriptor or a small index.
160 : #define CCOL__POLL_UDATA_ERR_ONLY ((uint64_t)1 << 62)
161 :
162 : // The control operations.
163 : #define CCOL_POLL_CTL_ADD 1
164 : #define CCOL_POLL_CTL_DEL 2
165 : #define CCOL_POLL_CTL_MOD 3
166 :
167 : // A low-water mark no read reaches, for a read filter of errors and EOF only.
168 : #define CCOL__POLL_LOWAT_NEVER INT_MAX
169 :
170 : // ThreadSanitizer intercepts epoll but not kevent(), so a TSan build states
171 : // the ordering itself: A release on the kqueue before each change and an
172 : // acquire after each wait that returns events. Without it every object reached
173 : // through an event's udata looks like a race. Only that build compiles this.
174 : #if defined(__has_feature)
175 : #if __has_feature(thread_sanitizer)
176 : #define CCOL__POLL_TSAN 1
177 : #endif
178 : #endif
179 : #if defined(__SANITIZE_THREAD__)
180 : #define CCOL__POLL_TSAN 1
181 : #endif
182 : #ifdef CCOL__POLL_TSAN
183 : void __tsan_acquire(void *addr);
184 : void __tsan_release(void *addr);
185 :
186 : // Gives the address that stands for kq in ThreadSanitizer's model, one of 256
187 : // static bytes picked by the descriptor, for the release and acquire macros.
188 : static inline void *ccol__poll_tsan_sync(int kq) {
189 : static char sync[256];
190 : return &sync[(unsigned)kq & 255u];
191 : }
192 : #define CCOL__POLL_TSAN_RELEASE(kq) __tsan_release(ccol__poll_tsan_sync(kq))
193 : #define CCOL__POLL_TSAN_ACQUIRE(kq) __tsan_acquire(ccol__poll_tsan_sync(kq))
194 : #else
195 : #define CCOL__POLL_TSAN_RELEASE(kq) ((void)0)
196 : #define CCOL__POLL_TSAN_ACQUIRE(kq) ((void)0)
197 : #endif
198 :
199 : // Creates a kqueue, closed on exec, for the event loop and cselect(). Gives
200 : // its fd or -1.
201 : static inline int ccol_poll_create(void) {
202 : int kq = kqueue();
203 : if (kq >= 0) (void)fcntl(kq, F_SETFD, FD_CLOEXEC);
204 : return kq;
205 : }
206 :
207 : // Says whether the socket fd listens, since a listener's read filter ignores
208 : // the low-water mark and the error-only filter must not arm it. FreeBSD and
209 : // OpenBSD answer SO_ACCEPTCONN; macOS refuses it and gives the flag through
210 : // proc_pidfdinfo(). A failed query answers false, so the error-only filter is
211 : // armed as for any other socket.
212 : static inline bool ccol__poll_is_listener(int fd) {
213 : #if defined(__APPLE__)
214 : struct socket_fdinfo si;
215 : if (proc_pidfdinfo(getpid(), fd, PROC_PIDFDSOCKETINFO, &si, sizeof(si)) ==
216 : (int)sizeof(si))
217 : return (si.psi.soi_options & SO_ACCEPTCONN) != 0;
218 : #else
219 : int listening = 0;
220 : socklen_t ll = sizeof(listening);
221 : if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &listening, &ll) == 0)
222 : return listening != 0;
223 : #endif
224 : return false;
225 : }
226 :
227 : // What ccol_poll_ctl() knows about an fd. Zero means nothing yet.
228 : typedef uint16_t ccol_poll_fdinfo;
229 :
230 : // The bits of ccol_poll_fdinfo: KNOWN says the kind bits (SOCK, RD for opened
231 : // for reading, ANON_PIPE for a FIFO with no device and inode) are filled;
232 : // LISTEN_KNOWN says LISTENER is; WFILT says a write filter is in place and
233 : // WCLEAR that it carries EV_CLEAR.
234 : #define CCOL__POLL_FI_KNOWN 0x001u
235 : #define CCOL__POLL_FI_SOCK 0x002u
236 : #define CCOL__POLL_FI_RD 0x004u
237 : #define CCOL__POLL_FI_ANON_PIPE 0x010u
238 : #define CCOL__POLL_FI_LISTEN_KNOWN 0x020u
239 : #define CCOL__POLL_FI_LISTENER 0x040u
240 : #define CCOL__POLL_FI_WFILT 0x080u
241 : #define CCOL__POLL_FI_WCLEAR 0x100u
242 :
243 : // Asks the fd what it is (socket, read end, anonymous pipe) and fills *fi, so
244 : // a MOD or a refine needn't ask again. A regular file or a directory fails with
245 : // EPERM, as epoll_ctl() does. Gives 0 or -1 with errno set.
246 : static inline int ccol__poll_fdinfo_fill(int fd, ccol_poll_fdinfo *fi) {
247 : struct stat st;
248 : if (fstat(fd, &st) != 0) return -1;
249 : if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode)) {
250 : errno = EPERM;
251 : return -1;
252 : }
253 : ccol_poll_fdinfo f = CCOL__POLL_FI_KNOWN;
254 : if (S_ISSOCK(st.st_mode)) {
255 : f |= CCOL__POLL_FI_SOCK | CCOL__POLL_FI_RD;
256 : } else {
257 : int fl = fcntl(fd, F_GETFL);
258 : if (fl < 0) return -1;
259 : if ((fl & O_ACCMODE) != O_WRONLY) f |= CCOL__POLL_FI_RD;
260 : if (S_ISFIFO(st.st_mode) && st.st_dev == 0 && st.st_ino == 0)
261 : f |= CCOL__POLL_FI_ANON_PIPE;
262 : }
263 : *fi = f;
264 : return 0;
265 : }
266 :
267 : // Says whether the socket listens, from the cache when *fi knows and asking
268 : // the fd (and caching the answer) otherwise.
269 : static inline bool ccol__poll_fdinfo_listener(int fd, ccol_poll_fdinfo *fi) {
270 : if (!(*fi & CCOL__POLL_FI_LISTEN_KNOWN)) {
271 : *fi |= CCOL__POLL_FI_LISTEN_KNOWN;
272 : if (ccol__poll_is_listener(fd)) *fi |= CCOL__POLL_FI_LISTENER;
273 : }
274 : return (*fi & CCOL__POLL_FI_LISTENER) != 0;
275 : }
276 :
277 : // epoll_ctl() on kqueue. DEL deletes both filters and succeeds when either
278 : // existed. Otherwise both filter changes go in one kevent() call with
279 : // EV_RECEIPT, and a delete of a missing filter (ENOENT) isn't an error. For an
280 : // error-only mask: A socket that also wants OUT uses the write filter alone; a
281 : // listener arms no read filter (it would report every pending connection); any
282 : // other socket gets the low-water mark with EV_CLEAR; a write end uses its
283 : // write filter and a read end its read filter, both with EV_CLEAR. An OpenBSD
284 : // anonymous pipe always uses the read filter, since OpenBSD doesn't wake a
285 : // write filter armed before the reader closes. An EV_CLEAR filter is never
286 : // one-shot: An event that refines to nothing would leave it disabled for good.
287 : // A write filter that switches EV_CLEAR on or off is recreated. Updates the
288 : // write filter bits of *info.
289 : static inline int ccol_poll_ctl(int kq, int op, int fd,
290 : const ccol_poll_event *ev,
291 : ccol_poll_fdinfo *info) {
292 : struct kevent ch[2];
293 : if (op == CCOL_POLL_CTL_DEL) {
294 : EV_SET(&ch[0], (uintptr_t)fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
295 : EV_SET(&ch[1], (uintptr_t)fd, EVFILT_WRITE, EV_DELETE, 0, 0, NULL);
296 : bool any = false;
297 : for (int i = 0; i < 2; i++) {
298 : if (kevent(kq, &ch[i], 1, NULL, 0, NULL) == 0) any = true;
299 : }
300 : if (info)
301 : *info &= (ccol_poll_fdinfo) ~(CCOL__POLL_FI_WFILT | CCOL__POLL_FI_WCLEAR);
302 : if (any) return 0;
303 : errno = ENOENT;
304 : return -1;
305 : }
306 :
307 : ccol_poll_fdinfo local = 0;
308 : ccol_poll_fdinfo *fi = info ? info : &local;
309 : if (op == CCOL_POLL_CTL_ADD)
310 : *fi &= (ccol_poll_fdinfo) ~(CCOL__POLL_FI_WFILT | CCOL__POLL_FI_WCLEAR);
311 : uint32_t m = ev->events;
312 : unsigned short dispatch = (m & CCOL_POLL_ONESHOT) ? EV_DISPATCH : 0;
313 : void *udata = (void *)(uintptr_t)ev->data.u64;
314 : bool want_read =
315 : (m & (CCOL_POLL_IN | CCOL_POLL_RDHUP | CCOL_POLL_ERR | CCOL_POLL_HUP)) !=
316 : 0;
317 : bool want_write = (m & CCOL_POLL_OUT) != 0;
318 : unsigned int rfflags = 0;
319 : int64_t rdata = 0;
320 : unsigned short rclear = 0;
321 : unsigned short wclear = 0;
322 : uint64_t rmark = 0;
323 : bool error_only_read = want_read && !(m & CCOL_POLL_IN);
324 : if ((op == CCOL_POLL_CTL_ADD || error_only_read) &&
325 : !(*fi & CCOL__POLL_FI_KNOWN) && ccol__poll_fdinfo_fill(fd, fi) != 0)
326 : return -1;
327 : bool is_sock = (*fi & CCOL__POLL_FI_SOCK) != 0;
328 : if (error_only_read) {
329 : if (is_sock && want_write && !(m & CCOL_POLL_RDHUP)) {
330 : want_read = false;
331 : } else if (is_sock && ccol__poll_fdinfo_listener(fd, fi)) {
332 : want_read = false;
333 : } else if (is_sock) {
334 : rfflags = NOTE_LOWAT;
335 : rdata = CCOL__POLL_LOWAT_NEVER;
336 : rclear = EV_CLEAR;
337 : rmark = CCOL__POLL_UDATA_ERR_ONLY;
338 : #if defined(__OpenBSD__)
339 : } else if (*fi & CCOL__POLL_FI_ANON_PIPE) {
340 : rclear = EV_CLEAR;
341 : #endif
342 : } else if (want_write) {
343 : want_read = false;
344 : } else if (!(*fi & CCOL__POLL_FI_RD)) {
345 : want_read = false;
346 : want_write = true;
347 : wclear = EV_CLEAR;
348 : } else {
349 : rclear = EV_CLEAR;
350 : }
351 : }
352 :
353 : if (op == CCOL_POLL_CTL_MOD && (m & CCOL_POLL_READ_MODE_CHANGE)) {
354 : EV_SET(&ch[0], (uintptr_t)fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
355 : CCOL__POLL_TSAN_RELEASE(kq);
356 : (void)kevent(kq, &ch[0], 1, NULL, 0, NULL);
357 : }
358 : if (want_write && (*fi & CCOL__POLL_FI_WFILT) &&
359 : ((*fi & CCOL__POLL_FI_WCLEAR) != 0) != (wclear != 0)) {
360 : EV_SET(&ch[1], (uintptr_t)fd, EVFILT_WRITE, EV_DELETE, 0, 0, NULL);
361 : CCOL__POLL_TSAN_RELEASE(kq);
362 : (void)kevent(kq, &ch[1], 1, NULL, 0, NULL);
363 : }
364 : unsigned short receipt = EV_RECEIPT;
365 : if (want_read) {
366 : EV_SET(&ch[0], (uintptr_t)fd, EVFILT_READ,
367 : EV_ADD | EV_ENABLE | (rclear ? 0 : dispatch) | rclear | receipt,
368 : rfflags, rdata,
369 : (void *)(uintptr_t)((uint64_t)(uintptr_t)udata | rmark));
370 : } else {
371 : EV_SET(&ch[0], (uintptr_t)fd, EVFILT_READ, EV_DELETE | receipt, 0, 0, NULL);
372 : }
373 : if (want_write) {
374 : EV_SET(&ch[1], (uintptr_t)fd, EVFILT_WRITE,
375 : EV_ADD | EV_ENABLE | (wclear ? 0 : dispatch) | wclear | receipt, 0,
376 : 0, udata);
377 : } else {
378 : EV_SET(&ch[1], (uintptr_t)fd, EVFILT_WRITE, EV_DELETE | receipt, 0, 0,
379 : NULL);
380 : }
381 : struct kevent res[2];
382 : struct timespec zero = {0, 0};
383 : CCOL__POLL_TSAN_RELEASE(kq);
384 : int n = kevent(kq, ch, 2, res, 2, &zero);
385 : if (n < 0) return -1;
386 : int fail = 0;
387 : bool write_added = want_write;
388 : for (int i = 0; i < n; i++) {
389 : if (!(res[i].flags & EV_ERROR) || res[i].data == 0) continue;
390 : bool was_delete = (res[i].filter == EVFILT_READ) ? !want_read : !want_write;
391 : if (was_delete && res[i].data == ENOENT) continue;
392 : if (res[i].filter == EVFILT_WRITE) write_added = false;
393 : fail = (int)res[i].data;
394 : }
395 : *fi &= (ccol_poll_fdinfo) ~(CCOL__POLL_FI_WFILT | CCOL__POLL_FI_WCLEAR);
396 : if (write_added)
397 : *fi |= (ccol_poll_fdinfo)(CCOL__POLL_FI_WFILT |
398 : (wclear ? CCOL__POLL_FI_WCLEAR : 0));
399 : if (fail != 0) {
400 : errno = fail;
401 : return -1;
402 : }
403 : return 0;
404 : }
405 :
406 : // epoll_wait() on kqueue. kevent() writes straight into evs and each record
407 : // is translated in place: A read report gives IN (or EOF marks), a write report
408 : // gives OUT, with ERR or HUP at its EOF. No call is made on any fd.
409 : static inline int ccol_poll_wait(int kq, ccol_poll_event *evs, int max,
410 : int timeout_ms) {
411 : struct timespec ts, *tsp = NULL;
412 : if (timeout_ms >= 0) {
413 : ts.tv_sec = timeout_ms / 1000;
414 : ts.tv_nsec = (long)(timeout_ms % 1000) * 1000000L;
415 : tsp = &ts;
416 : }
417 : _Static_assert(sizeof(ccol_poll_event) == sizeof(struct kevent),
418 : "ccol_poll_event must have the stride of struct kevent");
419 : int n = kevent(kq, NULL, 0, (struct kevent *)evs, max, tsp);
420 : if (n > 0) CCOL__POLL_TSAN_ACQUIRE(kq);
421 : for (int i = 0; i < n; i++) {
422 : struct kevent k = evs[i].ccol__kev;
423 : uint32_t bits = 0;
424 : if (k.filter == EVFILT_READ) {
425 : if ((uint64_t)(uintptr_t)k.udata & CCOL__POLL_UDATA_ERR_ONLY)
426 : bits |= CCOL__POLL_ERR_ONLY_FILTER;
427 : if (!(k.flags & EV_EOF)) {
428 : bits |= CCOL_POLL_IN;
429 : } else {
430 : bits |= CCOL__POLL_EOF;
431 : if (k.fflags != 0) bits |= CCOL__POLL_EOF_ERR;
432 : if (k.data > 0) bits |= CCOL__POLL_EOF_DATA;
433 : }
434 : } else if (k.filter == EVFILT_WRITE) {
435 : bits |= CCOL_POLL_OUT;
436 : if (k.flags & EV_EOF)
437 : bits |= (k.fflags != 0) ? CCOL_POLL_ERR : CCOL_POLL_HUP;
438 : }
439 : evs[i].events = bits;
440 : evs[i].data.u64 = (uint64_t)(uintptr_t)k.udata & ~CCOL__POLL_UDATA_ERR_ONLY;
441 : }
442 : return n;
443 : }
444 :
445 : // Turns the marks of a read filter report into the bits epoll would give, and
446 : // keeps only mask, ERR and HUP. The caller must prove fd is still open and
447 : // still belongs to the registration. A socket EOF gives IN|RDHUP, plus ERR for
448 : // an error and HUP when poll(POLLOUT) reports POLLHUP (both directions down);
449 : // macOS poll reports POLLHUP only for the filters asked for, hence POLLOUT. A
450 : // pipe EOF gives HUP, with IN while data is queued. A report from the
451 : // error-only filter is dropped for a listener (and the listener is cached in
452 : // *info) and on macOS for a full buffer, which its clamped low-water mark
453 : // reports; one proc_pidfdinfo() call tells those apart without clearing the
454 : // pending error. What remains of it becomes ERR.
455 : static inline void ccol_poll_refine(ccol_poll_event *ev, int fd, uint32_t mask,
456 : ccol_poll_fdinfo *info) {
457 : uint32_t m = ev->events;
458 : uint32_t keep = mask | CCOL_POLL_ERR | CCOL_POLL_HUP;
459 : bool err_only_filter = (m & CCOL__POLL_ERR_ONLY_FILTER) != 0;
460 : m &= ~CCOL__POLL_ERR_ONLY_FILTER;
461 : if (!(m & CCOL__POLL_EOF)) {
462 : #if defined(__APPLE__)
463 : if (err_only_filter && (m & CCOL_POLL_IN)) {
464 : struct socket_fdinfo si;
465 : if (info && (*info & CCOL__POLL_FI_LISTENER)) {
466 : m &= ~CCOL_POLL_IN;
467 : } else if (proc_pidfdinfo(getpid(), fd, PROC_PIDFDSOCKETINFO, &si,
468 : sizeof(si)) == (int)sizeof(si)) {
469 : if (si.psi.soi_options & SO_ACCEPTCONN) {
470 : if (info)
471 : *info |= CCOL__POLL_FI_LISTEN_KNOWN | CCOL__POLL_FI_LISTENER;
472 : m &= ~CCOL_POLL_IN;
473 : } else if (si.psi.soi_error == 0) {
474 : m &= ~CCOL_POLL_IN;
475 : }
476 : } else {
477 : int nread = 0, rcvbuf = 0, type = 0;
478 : socklen_t nl = sizeof(nread), rl = sizeof(rcvbuf), tl = sizeof(type);
479 : if (getsockopt(fd, SOL_SOCKET, SO_NREAD, &nread, &nl) == 0 &&
480 : getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &rl) == 0 &&
481 : getsockopt(fd, SOL_SOCKET, SO_TYPE, &type, &tl) == 0 &&
482 : (type == SOCK_STREAM ? nread >= rcvbuf : nread > 0))
483 : m &= ~CCOL_POLL_IN;
484 : }
485 : }
486 : #else
487 : if (err_only_filter && (m & CCOL_POLL_IN)) {
488 : bool listener;
489 : if (info && (*info & CCOL__POLL_FI_LISTENER)) {
490 : listener = true;
491 : } else {
492 : listener = ccol__poll_is_listener(fd);
493 : if (listener && info)
494 : *info |= CCOL__POLL_FI_LISTEN_KNOWN | CCOL__POLL_FI_LISTENER;
495 : }
496 : if (listener) m &= ~CCOL_POLL_IN;
497 : }
498 : #endif
499 : if (err_only_filter && (m & CCOL_POLL_IN))
500 : m = (m & ~CCOL_POLL_IN) | CCOL_POLL_ERR;
501 : ev->events = m & keep;
502 : return;
503 : }
504 : uint32_t bits =
505 : m & ~(CCOL__POLL_EOF | CCOL__POLL_EOF_ERR | CCOL__POLL_EOF_DATA);
506 : bool is_sock;
507 : if (info && (*info & CCOL__POLL_FI_KNOWN)) {
508 : is_sock = (*info & CCOL__POLL_FI_SOCK) != 0;
509 : } else {
510 : struct stat est;
511 : is_sock = fstat(fd, &est) == 0 && S_ISSOCK(est.st_mode);
512 : }
513 : if (is_sock) {
514 : bits |= CCOL_POLL_IN | CCOL_POLL_RDHUP;
515 : if (m & CCOL__POLL_EOF_ERR) bits |= CCOL_POLL_ERR;
516 : struct pollfd pfd = {.fd = fd, .events = POLLOUT};
517 : if (poll(&pfd, 1, 0) > 0 && (pfd.revents & POLLHUP)) bits |= CCOL_POLL_HUP;
518 : } else {
519 : bits |= CCOL_POLL_HUP;
520 : if (m & CCOL__POLL_EOF_DATA) bits |= CCOL_POLL_IN;
521 : }
522 : ev->events = bits & keep;
523 : }
524 :
525 : #else
526 : #error "c_collections needs epoll(7) or kqueue(2)"
527 : #endif
528 :
529 : // A wake descriptor is one fd that a poller watches for readability;
530 : // ccol_wakefd_notify() makes it readable and ccol_wakefd_drain() makes it
531 : // quiet. It's an eventfd on Linux and FreeBSD. macOS and OpenBSD have none, so
532 : // there it's a kqueue of its own with one EVFILT_USER event that carries
533 : // EV_CLEAR. CCOL__EMULATE_DARWIN_WAKEFD selects that form on FreeBSD too, for
534 : // the tests. ccol_wakefd_create() gives it closed on exec and non-blocking, or
535 : // -1 with errno set; close(2) releases it.
536 : #if (defined(__APPLE__) || defined(__OpenBSD__)) && \
537 : !defined(CCOL__EMULATE_DARWIN_WAKEFD)
538 : #define CCOL__EMULATE_DARWIN_WAKEFD 1
539 : #endif
540 :
541 : #if defined(CCOL__EMULATE_DARWIN_WAKEFD)
542 : #include <sys/event.h>
543 : #include <unistd.h>
544 :
545 : // Creates the wake descriptor (a kqueue with its user event) that the loop and
546 : // the queue bridges wait on. Gives its fd or -1 with errno set.
547 : static inline int ccol_wakefd_create(void) {
548 : int kq = kqueue();
549 : if (kq < 0) return -1;
550 : struct kevent ev;
551 : EV_SET(&ev, 1, EVFILT_USER, EV_ADD | EV_CLEAR, 0, 0, NULL);
552 : if (fcntl(kq, F_SETFD, FD_CLOEXEC) != 0 ||
553 : kevent(kq, &ev, 1, NULL, 0, NULL) != 0) {
554 : int saved = errno;
555 : close(kq);
556 : errno = saved;
557 : return -1;
558 : }
559 : return kq;
560 : }
561 :
562 : // Makes the wake descriptor readable by triggering the user event.
563 : static inline void ccol_wakefd_notify(int fd) {
564 : struct kevent ev;
565 : EV_SET(&ev, 1, EVFILT_USER, 0, NOTE_TRIGGER, 0, NULL);
566 : while (kevent(fd, &ev, 1, NULL, 0, NULL) < 0 && errno == EINTR) {
567 : }
568 : }
569 :
570 : // Makes the wake descriptor quiet by collecting the event without waiting,
571 : // which clears it.
572 : static inline void ccol_wakefd_drain(int fd) {
573 : struct kevent ev;
574 : struct timespec zero = {0, 0};
575 : while (kevent(fd, NULL, 0, &ev, 1, &zero) < 0 && errno == EINTR) {
576 : }
577 : }
578 : #else
579 : #include <sys/eventfd.h>
580 : #include <unistd.h>
581 :
582 : // Creates the wake descriptor (an eventfd) that the loop and the queue bridges
583 : // wait on. Gives its fd or -1 with errno set.
584 81175 : static inline int ccol_wakefd_create(void) {
585 81175 : return eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
586 : }
587 :
588 : // Makes the wake descriptor readable by writing 1. EAGAIN means the counter
589 : // is at its ceiling, which our small counts never reach, and every call site is
590 : // best effort, so only EINTR is retried.
591 68101 : static inline void ccol_wakefd_notify(int fd) {
592 68101 : uint64_t one = 1;
593 136201 : while (write(fd, &one, sizeof(one)) < 0 && errno == EINTR) {
594 68101 : }
595 68100 : }
596 :
597 : // Makes the wake descriptor quiet by reading the counter. EAGAIN just says
598 : // nothing is pending.
599 25524 : static inline void ccol_wakefd_drain(int fd) {
600 25524 : uint64_t val;
601 51035 : while (read(fd, &val, sizeof(val)) < 0 && errno == EINTR) {
602 25524 : }
603 25511 : }
604 : #endif
605 :
606 : #endif
|