blob: d08f512ce4b68debaff086929f9d5077cc5d725e [file] [log] [blame]
Christopher Wileye8679812015-07-01 13:36:18 -07001/* $OpenBSD: kqueue.c,v 1.5 2002/07/10 14:41:31 art Exp $ */
2
3/*
4 * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
5 * Copyright 2007-2012 Niels Provos and Nick Mathewson
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29#include "event2/event-config.h"
Narayan Kamathfc74cb42017-09-13 12:53:52 +010030#include "evconfig-private.h"
Christopher Wileye8679812015-07-01 13:36:18 -070031
Narayan Kamathfc74cb42017-09-13 12:53:52 +010032#ifdef EVENT__HAVE_KQUEUE
Christopher Wileye8679812015-07-01 13:36:18 -070033
34#include <sys/types.h>
Narayan Kamathfc74cb42017-09-13 12:53:52 +010035#ifdef EVENT__HAVE_SYS_TIME_H
Christopher Wileye8679812015-07-01 13:36:18 -070036#include <sys/time.h>
37#endif
38#include <sys/queue.h>
39#include <sys/event.h>
Haibo Huangb2279672019-05-31 16:12:39 -070040#include <limits.h>
Christopher Wileye8679812015-07-01 13:36:18 -070041#include <signal.h>
42#include <stdio.h>
43#include <stdlib.h>
44#include <string.h>
45#include <unistd.h>
46#include <errno.h>
Narayan Kamathfc74cb42017-09-13 12:53:52 +010047#ifdef EVENT__HAVE_INTTYPES_H
Christopher Wileye8679812015-07-01 13:36:18 -070048#include <inttypes.h>
49#endif
50
51/* Some platforms apparently define the udata field of struct kevent as
52 * intptr_t, whereas others define it as void*. There doesn't seem to be an
53 * easy way to tell them apart via autoconf, so we need to use OS macros. */
Narayan Kamathfc74cb42017-09-13 12:53:52 +010054#if defined(EVENT__HAVE_INTTYPES_H) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && !defined(__darwin__) && !defined(__APPLE__) && !defined(__CloudABI__)
Christopher Wileye8679812015-07-01 13:36:18 -070055#define PTR_TO_UDATA(x) ((intptr_t)(x))
56#define INT_TO_UDATA(x) ((intptr_t)(x))
57#else
58#define PTR_TO_UDATA(x) (x)
59#define INT_TO_UDATA(x) ((void*)(x))
60#endif
61
62#include "event-internal.h"
63#include "log-internal.h"
64#include "evmap-internal.h"
65#include "event2/thread.h"
Haibo Huangb2279672019-05-31 16:12:39 -070066#include "event2/util.h"
Christopher Wileye8679812015-07-01 13:36:18 -070067#include "evthread-internal.h"
68#include "changelist-internal.h"
69
Narayan Kamathfc74cb42017-09-13 12:53:52 +010070#include "kqueue-internal.h"
71
Christopher Wileye8679812015-07-01 13:36:18 -070072#define NEVENT 64
73
74struct kqop {
75 struct kevent *changes;
76 int changes_size;
77
78 struct kevent *events;
79 int events_size;
80 int kq;
Narayan Kamathfc74cb42017-09-13 12:53:52 +010081 int notify_event_added;
Christopher Wileye8679812015-07-01 13:36:18 -070082 pid_t pid;
83};
84
85static void kqop_free(struct kqop *kqop);
86
87static void *kq_init(struct event_base *);
88static int kq_sig_add(struct event_base *, int, short, short, void *);
89static int kq_sig_del(struct event_base *, int, short, short, void *);
90static int kq_dispatch(struct event_base *, struct timeval *);
91static void kq_dealloc(struct event_base *);
92
93const struct eventop kqops = {
94 "kqueue",
95 kq_init,
Narayan Kamathfc74cb42017-09-13 12:53:52 +010096 event_changelist_add_,
97 event_changelist_del_,
Christopher Wileye8679812015-07-01 13:36:18 -070098 kq_dispatch,
99 kq_dealloc,
100 1 /* need reinit */,
101 EV_FEATURE_ET|EV_FEATURE_O1|EV_FEATURE_FDS,
102 EVENT_CHANGELIST_FDINFO_SIZE
103};
104
105static const struct eventop kqsigops = {
106 "kqueue_signal",
107 NULL,
108 kq_sig_add,
109 kq_sig_del,
110 NULL,
111 NULL,
112 1 /* need reinit */,
113 0,
114 0
115};
116
117static void *
118kq_init(struct event_base *base)
119{
120 int kq = -1;
121 struct kqop *kqueueop = NULL;
122
123 if (!(kqueueop = mm_calloc(1, sizeof(struct kqop))))
124 return (NULL);
125
126/* Initialize the kernel queue */
127
128 if ((kq = kqueue()) == -1) {
129 event_warn("kqueue");
130 goto err;
131 }
132
133 kqueueop->kq = kq;
134
135 kqueueop->pid = getpid();
136
137 /* Initialize fields */
138 kqueueop->changes = mm_calloc(NEVENT, sizeof(struct kevent));
139 if (kqueueop->changes == NULL)
140 goto err;
141 kqueueop->events = mm_calloc(NEVENT, sizeof(struct kevent));
142 if (kqueueop->events == NULL)
143 goto err;
144 kqueueop->events_size = kqueueop->changes_size = NEVENT;
145
146 /* Check for Mac OS X kqueue bug. */
147 memset(&kqueueop->changes[0], 0, sizeof kqueueop->changes[0]);
148 kqueueop->changes[0].ident = -1;
149 kqueueop->changes[0].filter = EVFILT_READ;
150 kqueueop->changes[0].flags = EV_ADD;
151 /*
152 * If kqueue works, then kevent will succeed, and it will
153 * stick an error in events[0]. If kqueue is broken, then
154 * kevent will fail.
155 */
156 if (kevent(kq,
157 kqueueop->changes, 1, kqueueop->events, NEVENT, NULL) != 1 ||
158 (int)kqueueop->events[0].ident != -1 ||
Narayan Kamathfc74cb42017-09-13 12:53:52 +0100159 !(kqueueop->events[0].flags & EV_ERROR)) {
Christopher Wileye8679812015-07-01 13:36:18 -0700160 event_warn("%s: detected broken kqueue; not using.", __func__);
161 goto err;
162 }
163
164 base->evsigsel = &kqsigops;
165
166 return (kqueueop);
167err:
168 if (kqueueop)
169 kqop_free(kqueueop);
170
171 return (NULL);
172}
173
Christopher Wileye8679812015-07-01 13:36:18 -0700174#define ADD_UDATA 0x30303
175
176static void
177kq_setup_kevent(struct kevent *out, evutil_socket_t fd, int filter, short change)
178{
179 memset(out, 0, sizeof(struct kevent));
180 out->ident = fd;
181 out->filter = filter;
182
183 if (change & EV_CHANGE_ADD) {
184 out->flags = EV_ADD;
185 /* We set a magic number here so that we can tell 'add'
186 * errors from 'del' errors. */
187 out->udata = INT_TO_UDATA(ADD_UDATA);
188 if (change & EV_ET)
189 out->flags |= EV_CLEAR;
190#ifdef NOTE_EOF
191 /* Make it behave like select() and poll() */
192 if (filter == EVFILT_READ)
193 out->fflags = NOTE_EOF;
194#endif
195 } else {
196 EVUTIL_ASSERT(change & EV_CHANGE_DEL);
197 out->flags = EV_DELETE;
198 }
199}
200
201static int
202kq_build_changes_list(const struct event_changelist *changelist,
203 struct kqop *kqop)
204{
205 int i;
206 int n_changes = 0;
207
208 for (i = 0; i < changelist->n_changes; ++i) {
209 struct event_change *in_ch = &changelist->changes[i];
210 struct kevent *out_ch;
211 if (n_changes >= kqop->changes_size - 1) {
Haibo Huangb2279672019-05-31 16:12:39 -0700212 int newsize;
Christopher Wileye8679812015-07-01 13:36:18 -0700213 struct kevent *newchanges;
214
Haibo Huangb2279672019-05-31 16:12:39 -0700215 if (kqop->changes_size > INT_MAX / 2 ||
216 (size_t)kqop->changes_size * 2 > EV_SIZE_MAX /
217 sizeof(struct kevent)) {
218 event_warnx("%s: int overflow", __func__);
219 return (-1);
220 }
221
222 newsize = kqop->changes_size * 2;
Christopher Wileye8679812015-07-01 13:36:18 -0700223 newchanges = mm_realloc(kqop->changes,
224 newsize * sizeof(struct kevent));
225 if (newchanges == NULL) {
226 event_warn("%s: realloc", __func__);
227 return (-1);
228 }
229 kqop->changes = newchanges;
230 kqop->changes_size = newsize;
231 }
232 if (in_ch->read_change) {
233 out_ch = &kqop->changes[n_changes++];
234 kq_setup_kevent(out_ch, in_ch->fd, EVFILT_READ,
235 in_ch->read_change);
236 }
237 if (in_ch->write_change) {
238 out_ch = &kqop->changes[n_changes++];
239 kq_setup_kevent(out_ch, in_ch->fd, EVFILT_WRITE,
240 in_ch->write_change);
241 }
242 }
243 return n_changes;
244}
245
246static int
247kq_grow_events(struct kqop *kqop, size_t new_size)
248{
249 struct kevent *newresult;
250
251 newresult = mm_realloc(kqop->events,
252 new_size * sizeof(struct kevent));
253
254 if (newresult) {
255 kqop->events = newresult;
256 kqop->events_size = new_size;
257 return 0;
258 } else {
259 return -1;
260 }
261}
262
263static int
264kq_dispatch(struct event_base *base, struct timeval *tv)
265{
266 struct kqop *kqop = base->evbase;
267 struct kevent *events = kqop->events;
268 struct kevent *changes;
269 struct timespec ts, *ts_p = NULL;
270 int i, n_changes, res;
271
272 if (tv != NULL) {
Narayan Kamathfc74cb42017-09-13 12:53:52 +0100273 ts.tv_sec = tv->tv_sec;
274 ts.tv_nsec = tv->tv_usec * 1000;
Christopher Wileye8679812015-07-01 13:36:18 -0700275 ts_p = &ts;
276 }
277
278 /* Build "changes" from "base->changes" */
279 EVUTIL_ASSERT(kqop->changes);
280 n_changes = kq_build_changes_list(&base->changelist, kqop);
281 if (n_changes < 0)
282 return -1;
283
Narayan Kamathfc74cb42017-09-13 12:53:52 +0100284 event_changelist_remove_all_(&base->changelist, base);
Christopher Wileye8679812015-07-01 13:36:18 -0700285
286 /* steal the changes array in case some broken code tries to call
287 * dispatch twice at once. */
288 changes = kqop->changes;
289 kqop->changes = NULL;
290
291 /* Make sure that 'events' is at least as long as the list of changes:
292 * otherwise errors in the changes can get reported as a -1 return
293 * value from kevent() rather than as EV_ERROR events in the events
294 * array.
295 *
296 * (We could instead handle -1 return values from kevent() by
297 * retrying with a smaller changes array or a larger events array,
298 * but this approach seems less risky for now.)
299 */
300 if (kqop->events_size < n_changes) {
301 int new_size = kqop->events_size;
302 do {
303 new_size *= 2;
304 } while (new_size < n_changes);
305
306 kq_grow_events(kqop, new_size);
307 events = kqop->events;
308 }
309
310 EVBASE_RELEASE_LOCK(base, th_base_lock);
311
312 res = kevent(kqop->kq, changes, n_changes,
313 events, kqop->events_size, ts_p);
314
315 EVBASE_ACQUIRE_LOCK(base, th_base_lock);
316
317 EVUTIL_ASSERT(kqop->changes == NULL);
318 kqop->changes = changes;
319
320 if (res == -1) {
321 if (errno != EINTR) {
322 event_warn("kevent");
323 return (-1);
324 }
325
326 return (0);
327 }
328
329 event_debug(("%s: kevent reports %d", __func__, res));
330
331 for (i = 0; i < res; i++) {
332 int which = 0;
333
334 if (events[i].flags & EV_ERROR) {
335 switch (events[i].data) {
336
337 /* Can occur on delete if we are not currently
338 * watching any events on this fd. That can
339 * happen when the fd was closed and another
340 * file was opened with that fd. */
341 case ENOENT:
342 /* Can occur for reasons not fully understood
343 * on FreeBSD. */
344 case EINVAL:
345 continue;
Narayan Kamathfc74cb42017-09-13 12:53:52 +0100346#if defined(__FreeBSD__)
347 /*
348 * This currently occurs if an FD is closed
349 * before the EV_DELETE makes it out via kevent().
350 * The FreeBSD capabilities code sees the blank
351 * capability set and rejects the request to
352 * modify an event.
353 *
354 * To be strictly correct - when an FD is closed,
355 * all the registered events are also removed.
356 * Queuing EV_DELETE to a closed FD is wrong.
357 * The event(s) should just be deleted from
358 * the pending changelist.
359 */
360 case ENOTCAPABLE:
361 continue;
362#endif
Christopher Wileye8679812015-07-01 13:36:18 -0700363
364 /* Can occur on a delete if the fd is closed. */
365 case EBADF:
366 /* XXXX On NetBSD, we can also get EBADF if we
367 * try to add the write side of a pipe, but
368 * the read side has already been closed.
369 * Other BSDs call this situation 'EPIPE'. It
370 * would be good if we had a way to report
371 * this situation. */
372 continue;
373 /* These two can occur on an add if the fd was one side
374 * of a pipe, and the other side was closed. */
375 case EPERM:
376 case EPIPE:
377 /* Report read events, if we're listening for
378 * them, so that the user can learn about any
379 * add errors. (If the operation was a
380 * delete, then udata should be cleared.) */
381 if (events[i].udata) {
382 /* The operation was an add:
383 * report the error as a read. */
384 which |= EV_READ;
385 break;
386 } else {
387 /* The operation was a del:
388 * report nothing. */
389 continue;
390 }
391
392 /* Other errors shouldn't occur. */
393 default:
394 errno = events[i].data;
395 return (-1);
396 }
397 } else if (events[i].filter == EVFILT_READ) {
398 which |= EV_READ;
399 } else if (events[i].filter == EVFILT_WRITE) {
400 which |= EV_WRITE;
401 } else if (events[i].filter == EVFILT_SIGNAL) {
402 which |= EV_SIGNAL;
Narayan Kamathfc74cb42017-09-13 12:53:52 +0100403#ifdef EVFILT_USER
404 } else if (events[i].filter == EVFILT_USER) {
405 base->is_notify_pending = 0;
406#endif
Christopher Wileye8679812015-07-01 13:36:18 -0700407 }
408
409 if (!which)
410 continue;
411
412 if (events[i].filter == EVFILT_SIGNAL) {
Narayan Kamathfc74cb42017-09-13 12:53:52 +0100413 evmap_signal_active_(base, events[i].ident, 1);
Christopher Wileye8679812015-07-01 13:36:18 -0700414 } else {
Narayan Kamathfc74cb42017-09-13 12:53:52 +0100415 evmap_io_active_(base, events[i].ident, which | EV_ET);
Christopher Wileye8679812015-07-01 13:36:18 -0700416 }
417 }
418
419 if (res == kqop->events_size) {
420 /* We used all the events space that we have. Maybe we should
421 make it bigger. */
422 kq_grow_events(kqop, kqop->events_size * 2);
423 }
424
425 return (0);
426}
427
428static void
429kqop_free(struct kqop *kqop)
430{
431 if (kqop->changes)
432 mm_free(kqop->changes);
433 if (kqop->events)
434 mm_free(kqop->events);
435 if (kqop->kq >= 0 && kqop->pid == getpid())
436 close(kqop->kq);
437 memset(kqop, 0, sizeof(struct kqop));
438 mm_free(kqop);
439}
440
441static void
442kq_dealloc(struct event_base *base)
443{
444 struct kqop *kqop = base->evbase;
Narayan Kamathfc74cb42017-09-13 12:53:52 +0100445 evsig_dealloc_(base);
Christopher Wileye8679812015-07-01 13:36:18 -0700446 kqop_free(kqop);
447}
448
449/* signal handling */
450static int
451kq_sig_add(struct event_base *base, int nsignal, short old, short events, void *p)
452{
453 struct kqop *kqop = base->evbase;
454 struct kevent kev;
455 struct timespec timeout = { 0, 0 };
456 (void)p;
457
458 EVUTIL_ASSERT(nsignal >= 0 && nsignal < NSIG);
459
460 memset(&kev, 0, sizeof(kev));
461 kev.ident = nsignal;
462 kev.filter = EVFILT_SIGNAL;
463 kev.flags = EV_ADD;
464
465 /* Be ready for the signal if it is sent any
466 * time between now and the next call to
467 * kq_dispatch. */
468 if (kevent(kqop->kq, &kev, 1, NULL, 0, &timeout) == -1)
469 return (-1);
470
Narayan Kamathfc74cb42017-09-13 12:53:52 +0100471 /* We can set the handler for most signals to SIG_IGN and
472 * still have them reported to us in the queue. However,
473 * if the handler for SIGCHLD is SIG_IGN, the system reaps
474 * zombie processes for us, and we don't get any notification.
475 * This appears to be the only signal with this quirk. */
476 if (evsig_set_handler_(base, nsignal,
477 nsignal == SIGCHLD ? SIG_DFL : SIG_IGN) == -1)
Christopher Wileye8679812015-07-01 13:36:18 -0700478 return (-1);
479
480 return (0);
481}
482
483static int
484kq_sig_del(struct event_base *base, int nsignal, short old, short events, void *p)
485{
486 struct kqop *kqop = base->evbase;
487 struct kevent kev;
488
489 struct timespec timeout = { 0, 0 };
490 (void)p;
491
492 EVUTIL_ASSERT(nsignal >= 0 && nsignal < NSIG);
493
494 memset(&kev, 0, sizeof(kev));
495 kev.ident = nsignal;
496 kev.filter = EVFILT_SIGNAL;
497 kev.flags = EV_DELETE;
498
499 /* Because we insert signal events
500 * immediately, we need to delete them
501 * immediately, too */
502 if (kevent(kqop->kq, &kev, 1, NULL, 0, &timeout) == -1)
503 return (-1);
504
Narayan Kamathfc74cb42017-09-13 12:53:52 +0100505 if (evsig_restore_handler_(base, nsignal) == -1)
Christopher Wileye8679812015-07-01 13:36:18 -0700506 return (-1);
507
508 return (0);
509}
Narayan Kamathfc74cb42017-09-13 12:53:52 +0100510
511
512/* OSX 10.6 and FreeBSD 8.1 add support for EVFILT_USER, which we can use
513 * to wake up the event loop from another thread. */
514
515/* Magic number we use for our filter ID. */
516#define NOTIFY_IDENT 42
517
518int
519event_kq_add_notify_event_(struct event_base *base)
520{
521 struct kqop *kqop = base->evbase;
522#if defined(EVFILT_USER) && defined(NOTE_TRIGGER)
523 struct kevent kev;
524 struct timespec timeout = { 0, 0 };
525#endif
526
527 if (kqop->notify_event_added)
528 return 0;
529
530#if defined(EVFILT_USER) && defined(NOTE_TRIGGER)
531 memset(&kev, 0, sizeof(kev));
532 kev.ident = NOTIFY_IDENT;
533 kev.filter = EVFILT_USER;
534 kev.flags = EV_ADD | EV_CLEAR;
535
536 if (kevent(kqop->kq, &kev, 1, NULL, 0, &timeout) == -1) {
537 event_warn("kevent: adding EVFILT_USER event");
538 return -1;
539 }
540
541 kqop->notify_event_added = 1;
542
543 return 0;
544#else
545 return -1;
546#endif
547}
548
549int
550event_kq_notify_base_(struct event_base *base)
551{
552 struct kqop *kqop = base->evbase;
553#if defined(EVFILT_USER) && defined(NOTE_TRIGGER)
554 struct kevent kev;
555 struct timespec timeout = { 0, 0 };
556#endif
557 if (! kqop->notify_event_added)
558 return -1;
559
560#if defined(EVFILT_USER) && defined(NOTE_TRIGGER)
561 memset(&kev, 0, sizeof(kev));
562 kev.ident = NOTIFY_IDENT;
563 kev.filter = EVFILT_USER;
564 kev.fflags = NOTE_TRIGGER;
565
566 if (kevent(kqop->kq, &kev, 1, NULL, 0, &timeout) == -1) {
567 event_warn("kevent: triggering EVFILT_USER event");
568 return -1;
569 }
570
571 return 0;
572#else
573 return -1;
574#endif
575}
576
577#endif /* EVENT__HAVE_KQUEUE */