Changes to update Tomato RAF.
[tomato.git] / release / src / router / dnscrypt / src / libevent / kqueue.c
blob6d9d4becbedd93600916fde435eb96c4b684156a
1 /* $OpenBSD: kqueue.c,v 1.5 2002/07/10 14:41:31 art Exp $ */
3 /*
4 * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
5 * Copyright 2007-2012 Niels Provos and Nick Mathewson
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.
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.
29 #include "event2/event-config.h"
31 #ifndef _GNU_SOURCE
32 # define _GNU_SOURCE
33 #endif
35 #include <sys/types.h>
36 #ifdef _EVENT_HAVE_SYS_TIME_H
37 #include <sys/time.h>
38 #endif
39 #include <sys/queue.h>
40 #include <sys/event.h>
41 #include <signal.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <unistd.h>
46 #include <errno.h>
47 #ifdef _EVENT_HAVE_INTTYPES_H
48 #include <inttypes.h>
49 #endif
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. */
54 #if defined(_EVENT_HAVE_INTTYPES_H) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && !defined(__darwin__) && !defined(__APPLE__)
55 #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
62 #include "event-internal.h"
63 #include "log-internal.h"
64 #include "evmap-internal.h"
65 #include "event2/thread.h"
66 #include "evthread-internal.h"
67 #include "changelist-internal.h"
69 #define NEVENT 64
71 struct kqop {
72 struct kevent *changes;
73 int changes_size;
75 struct kevent *events;
76 int events_size;
77 int kq;
78 pid_t pid;
81 static void kqop_free(struct kqop *kqop);
83 static void *kq_init(struct event_base *);
84 static int kq_sig_add(struct event_base *, int, short, short, void *);
85 static int kq_sig_del(struct event_base *, int, short, short, void *);
86 static int kq_dispatch(struct event_base *, struct timeval *);
87 static void kq_dealloc(struct event_base *);
89 const struct eventop kqops = {
90 "kqueue",
91 kq_init,
92 event_changelist_add,
93 event_changelist_del,
94 kq_dispatch,
95 kq_dealloc,
96 1 /* need reinit */,
97 EV_FEATURE_ET|EV_FEATURE_O1|EV_FEATURE_FDS,
98 EVENT_CHANGELIST_FDINFO_SIZE
101 static const struct eventop kqsigops = {
102 "kqueue_signal",
103 NULL,
104 kq_sig_add,
105 kq_sig_del,
106 NULL,
107 NULL,
108 1 /* need reinit */,
113 static void *
114 kq_init(struct event_base *base)
116 int kq = -1;
117 struct kqop *kqueueop = NULL;
119 if (!(kqueueop = mm_calloc(1, sizeof(struct kqop))))
120 return (NULL);
122 /* Initialize the kernel queue */
124 if ((kq = kqueue()) == -1) {
125 event_warn("kqueue");
126 goto err;
129 kqueueop->kq = kq;
131 kqueueop->pid = getpid();
133 /* Initialize fields */
134 kqueueop->changes = mm_calloc(NEVENT, sizeof(struct kevent));
135 if (kqueueop->changes == NULL)
136 goto err;
137 kqueueop->events = mm_calloc(NEVENT, sizeof(struct kevent));
138 if (kqueueop->events == NULL)
139 goto err;
140 kqueueop->events_size = kqueueop->changes_size = NEVENT;
142 /* Check for Mac OS X kqueue bug. */
143 memset(&kqueueop->changes[0], 0, sizeof kqueueop->changes[0]);
144 kqueueop->changes[0].ident = -1;
145 kqueueop->changes[0].filter = EVFILT_READ;
146 kqueueop->changes[0].flags = EV_ADD;
148 * If kqueue works, then kevent will succeed, and it will
149 * stick an error in events[0]. If kqueue is broken, then
150 * kevent will fail.
152 if (kevent(kq,
153 kqueueop->changes, 1, kqueueop->events, NEVENT, NULL) != 1 ||
154 (int)kqueueop->events[0].ident != -1 ||
155 kqueueop->events[0].flags != EV_ERROR) {
156 event_warn("%s: detected broken kqueue; not using.", __func__);
157 goto err;
160 base->evsigsel = &kqsigops;
162 return (kqueueop);
163 err:
164 if (kqueueop)
165 kqop_free(kqueueop);
167 return (NULL);
170 static void
171 kq_sighandler(int sig)
173 /* Do nothing here */
176 #define ADD_UDATA 0x30303
178 static void
179 kq_setup_kevent(struct kevent *out, evutil_socket_t fd, int filter, short change)
181 memset(out, 0, sizeof(struct kevent));
182 out->ident = fd;
183 out->filter = filter;
185 if (change & EV_CHANGE_ADD) {
186 out->flags = EV_ADD;
187 /* We set a magic number here so that we can tell 'add'
188 * errors from 'del' errors. */
189 out->udata = INT_TO_UDATA(ADD_UDATA);
190 if (change & EV_ET)
191 out->flags |= EV_CLEAR;
192 #ifdef NOTE_EOF
193 /* Make it behave like select() and poll() */
194 if (filter == EVFILT_READ)
195 out->fflags = NOTE_EOF;
196 #endif
197 } else {
198 EVUTIL_ASSERT(change & EV_CHANGE_DEL);
199 out->flags = EV_DELETE;
203 static int
204 kq_build_changes_list(const struct event_changelist *changelist,
205 struct kqop *kqop)
207 int i;
208 int n_changes = 0;
210 for (i = 0; i < changelist->n_changes; ++i) {
211 struct event_change *in_ch = &changelist->changes[i];
212 struct kevent *out_ch;
213 if (n_changes >= kqop->changes_size - 1) {
214 int newsize = kqop->changes_size * 2;
215 struct kevent *newchanges;
217 newchanges = mm_realloc(kqop->changes,
218 newsize * sizeof(struct kevent));
219 if (newchanges == NULL) {
220 event_warn("%s: realloc", __func__);
221 return (-1);
223 kqop->changes = newchanges;
224 kqop->changes_size = newsize;
226 if (in_ch->read_change) {
227 out_ch = &kqop->changes[n_changes++];
228 kq_setup_kevent(out_ch, in_ch->fd, EVFILT_READ,
229 in_ch->read_change);
231 if (in_ch->write_change) {
232 out_ch = &kqop->changes[n_changes++];
233 kq_setup_kevent(out_ch, in_ch->fd, EVFILT_WRITE,
234 in_ch->write_change);
237 return n_changes;
240 static int
241 kq_grow_events(struct kqop *kqop, size_t new_size)
243 struct kevent *newresult;
245 newresult = mm_realloc(kqop->events,
246 new_size * sizeof(struct kevent));
248 if (newresult) {
249 kqop->events = newresult;
250 kqop->events_size = new_size;
251 return 0;
252 } else {
253 return -1;
257 static int
258 kq_dispatch(struct event_base *base, struct timeval *tv)
260 struct kqop *kqop = base->evbase;
261 struct kevent *events = kqop->events;
262 struct kevent *changes;
263 struct timespec ts, *ts_p = NULL;
264 int i, n_changes, res;
266 if (tv != NULL) {
267 TIMEVAL_TO_TIMESPEC(tv, &ts);
268 ts_p = &ts;
271 /* Build "changes" from "base->changes" */
272 EVUTIL_ASSERT(kqop->changes);
273 n_changes = kq_build_changes_list(&base->changelist, kqop);
274 if (n_changes < 0)
275 return -1;
277 event_changelist_remove_all(&base->changelist, base);
279 /* steal the changes array in case some broken code tries to call
280 * dispatch twice at once. */
281 changes = kqop->changes;
282 kqop->changes = NULL;
284 /* Make sure that 'events' is at least as long as the list of changes:
285 * otherwise errors in the changes can get reported as a -1 return
286 * value from kevent() rather than as EV_ERROR events in the events
287 * array.
289 * (We could instead handle -1 return values from kevent() by
290 * retrying with a smaller changes array or a larger events array,
291 * but this approach seems less risky for now.)
293 if (kqop->events_size < n_changes) {
294 int new_size = kqop->events_size;
295 do {
296 new_size *= 2;
297 } while (new_size < n_changes);
299 kq_grow_events(kqop, new_size);
300 events = kqop->events;
303 EVBASE_RELEASE_LOCK(base, th_base_lock);
305 res = kevent(kqop->kq, changes, n_changes,
306 events, kqop->events_size, ts_p);
308 EVBASE_ACQUIRE_LOCK(base, th_base_lock);
310 EVUTIL_ASSERT(kqop->changes == NULL);
311 kqop->changes = changes;
313 if (res == -1) {
314 if (errno != EINTR) {
315 event_warn("kevent");
316 return (-1);
319 return (0);
322 event_debug(("%s: kevent reports %d", __func__, res));
324 for (i = 0; i < res; i++) {
325 int which = 0;
327 if (events[i].flags & EV_ERROR) {
328 switch (events[i].data) {
330 /* Can occur on delete if we are not currently
331 * watching any events on this fd. That can
332 * happen when the fd was closed and another
333 * file was opened with that fd. */
334 case ENOENT:
335 /* Can occur for reasons not fully understood
336 * on FreeBSD. */
337 case EINVAL:
338 continue;
340 /* Can occur on a delete if the fd is closed. */
341 case EBADF:
342 /* XXXX On NetBSD, we can also get EBADF if we
343 * try to add the write side of a pipe, but
344 * the read side has already been closed.
345 * Other BSDs call this situation 'EPIPE'. It
346 * would be good if we had a way to report
347 * this situation. */
348 continue;
349 /* These two can occur on an add if the fd was one side
350 * of a pipe, and the other side was closed. */
351 case EPERM:
352 case EPIPE:
353 /* Report read events, if we're listening for
354 * them, so that the user can learn about any
355 * add errors. (If the operation was a
356 * delete, then udata should be cleared.) */
357 if (events[i].udata) {
358 /* The operation was an add:
359 * report the error as a read. */
360 which |= EV_READ;
361 break;
362 } else {
363 /* The operation was a del:
364 * report nothing. */
365 continue;
368 /* Other errors shouldn't occur. */
369 default:
370 errno = events[i].data;
371 return (-1);
373 } else if (events[i].filter == EVFILT_READ) {
374 which |= EV_READ;
375 } else if (events[i].filter == EVFILT_WRITE) {
376 which |= EV_WRITE;
377 } else if (events[i].filter == EVFILT_SIGNAL) {
378 which |= EV_SIGNAL;
381 if (!which)
382 continue;
384 if (events[i].filter == EVFILT_SIGNAL) {
385 evmap_signal_active(base, events[i].ident, 1);
386 } else {
387 evmap_io_active(base, events[i].ident, which | EV_ET);
391 if (res == kqop->events_size) {
392 /* We used all the events space that we have. Maybe we should
393 make it bigger. */
394 kq_grow_events(kqop, kqop->events_size * 2);
397 return (0);
400 static void
401 kqop_free(struct kqop *kqop)
403 if (kqop->changes)
404 mm_free(kqop->changes);
405 if (kqop->events)
406 mm_free(kqop->events);
407 if (kqop->kq >= 0 && kqop->pid == getpid())
408 close(kqop->kq);
409 memset(kqop, 0, sizeof(struct kqop));
410 mm_free(kqop);
413 static void
414 kq_dealloc(struct event_base *base)
416 struct kqop *kqop = base->evbase;
417 evsig_dealloc(base);
418 kqop_free(kqop);
421 /* signal handling */
422 static int
423 kq_sig_add(struct event_base *base, int nsignal, short old, short events, void *p)
425 struct kqop *kqop = base->evbase;
426 struct kevent kev;
427 struct timespec timeout = { 0, 0 };
428 (void)p;
430 EVUTIL_ASSERT(nsignal >= 0 && nsignal < NSIG);
432 memset(&kev, 0, sizeof(kev));
433 kev.ident = nsignal;
434 kev.filter = EVFILT_SIGNAL;
435 kev.flags = EV_ADD;
437 /* Be ready for the signal if it is sent any
438 * time between now and the next call to
439 * kq_dispatch. */
440 if (kevent(kqop->kq, &kev, 1, NULL, 0, &timeout) == -1)
441 return (-1);
443 /* XXXX The manpage suggest we could use SIG_IGN instead of a
444 * do-nothing handler */
445 if (_evsig_set_handler(base, nsignal, kq_sighandler) == -1)
446 return (-1);
448 return (0);
451 static int
452 kq_sig_del(struct event_base *base, int nsignal, short old, short events, void *p)
454 struct kqop *kqop = base->evbase;
455 struct kevent kev;
457 struct timespec timeout = { 0, 0 };
458 (void)p;
460 EVUTIL_ASSERT(nsignal >= 0 && nsignal < NSIG);
462 memset(&kev, 0, sizeof(kev));
463 kev.ident = nsignal;
464 kev.filter = EVFILT_SIGNAL;
465 kev.flags = EV_DELETE;
467 /* Because we insert signal events
468 * immediately, we need to delete them
469 * immediately, too */
470 if (kevent(kqop->kq, &kev, 1, NULL, 0, &timeout) == -1)
471 return (-1);
473 if (_evsig_restore_handler(base, nsignal) == -1)
474 return (-1);
476 return (0);