xref: /libevent-2.1.12/kqueue.c (revision e5cf9879)
1 /*	$OpenBSD: kqueue.c,v 1.5 2002/07/10 14:41:31 art Exp $	*/
2 
3 /*
4  * Copyright 2000-2007 Niels Provos <[email protected]>
5  * Copyright 2007-2009 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 "event-config.h"
30 
31 #define _GNU_SOURCE
32 
33 #include <sys/types.h>
34 #ifdef _EVENT_HAVE_SYS_TIME_H
35 #include <sys/time.h>
36 #endif
37 #include <sys/queue.h>
38 #include <sys/event.h>
39 #include <signal.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
44 #include <errno.h>
45 #ifdef _EVENT_HAVE_INTTYPES_H
46 #include <inttypes.h>
47 #endif
48 
49 /* Some platforms apparently define the udata field of struct kevent as
50  * intptr_t, whereas others define it as void*.  There doesn't seem to be an
51  * easy way to tell them apart via autoconf, so we need to use OS macros. */
52 #if defined(_EVENT_HAVE_INTTYPES_H) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && !defined(__darwin__) && !defined(__APPLE__)
53 #define PTR_TO_UDATA(x)	((intptr_t)(x))
54 #else
55 #define PTR_TO_UDATA(x)	(x)
56 #endif
57 
58 #include "event-internal.h"
59 #include "log-internal.h"
60 #include "evmap-internal.h"
61 #include "event2/thread.h"
62 #include "evthread-internal.h"
63 #include "changelist-internal.h"
64 
65 #define NEVENT		64
66 
67 struct kqop {
68 	struct kevent *changes;
69 	int changes_size;
70 
71 	struct kevent *events;
72 	int events_size;
73 	int kq;
74 	pid_t pid;
75 };
76 
77 static void kqop_free(struct kqop *kqop);
78 
79 static void *kq_init	(struct event_base *);
80 static int kq_sig_add (struct event_base *, int, short, short, void *);
81 static int kq_sig_del (struct event_base *, int, short, short, void *);
82 static int kq_dispatch	(struct event_base *, struct timeval *);
83 static void kq_dealloc (struct event_base *);
84 
85 const struct eventop kqops = {
86 	"kqueue",
87 	kq_init,
88 	event_changelist_add,
89 	event_changelist_del,
90 	kq_dispatch,
91 	kq_dealloc,
92 	1 /* need reinit */,
93     EV_FEATURE_ET|EV_FEATURE_O1|EV_FEATURE_FDS,
94 	EVENT_CHANGELIST_FDINFO_SIZE
95 };
96 
97 static const struct eventop kqsigops = {
98 	"kqueue_signal",
99 	NULL,
100 	kq_sig_add,
101 	kq_sig_del,
102 	NULL,
103 	NULL,
104 	1 /* need reinit */,
105 	0,
106 	0
107 };
108 
109 static void *
110 kq_init(struct event_base *base)
111 {
112 	int kq = -1;
113 	struct kqop *kqueueop = NULL;
114 
115 	if (!(kqueueop = mm_calloc(1, sizeof(struct kqop))))
116 		return (NULL);
117 
118 /* Initialize the kernel queue */
119 
120 	if ((kq = kqueue()) == -1) {
121 		event_warn("kqueue");
122 		goto err;
123 	}
124 
125 	kqueueop->kq = kq;
126 
127 	kqueueop->pid = getpid();
128 
129 	/* Initialize fields */
130 	kqueueop->changes = mm_calloc(NEVENT, sizeof(struct kevent));
131 	if (kqueueop->changes == NULL)
132 		goto err;
133 	kqueueop->events = mm_calloc(NEVENT, sizeof(struct kevent));
134 	if (kqueueop->events == NULL)
135 		goto err;
136 	kqueueop->events_size = kqueueop->changes_size = NEVENT;
137 
138 	/* Check for Mac OS X kqueue bug. */
139 	memset(&kqueueop->changes[0], 0, sizeof kqueueop->changes[0]);
140 	kqueueop->changes[0].ident = -1;
141 	kqueueop->changes[0].filter = EVFILT_READ;
142 	kqueueop->changes[0].flags = EV_ADD;
143 	/*
144 	 * If kqueue works, then kevent will succeed, and it will
145 	 * stick an error in events[0].  If kqueue is broken, then
146 	 * kevent will fail.
147 	 */
148 	if (kevent(kq,
149 		kqueueop->changes, 1, kqueueop->events, NEVENT, NULL) != 1 ||
150 	    kqueueop->events[0].ident != -1 ||
151 	    kqueueop->events[0].flags != EV_ERROR) {
152 		event_warn("%s: detected broken kqueue; not using.", __func__);
153 		goto err;
154 	}
155 
156 	base->evsigsel = &kqsigops;
157 	base->evsigbase = kqueueop;
158 
159 	return (kqueueop);
160 err:
161 	if (kqueueop)
162 		kqop_free(kqueueop);
163 
164 	return (NULL);
165 }
166 
167 static void
168 kq_sighandler(int sig)
169 {
170 	/* Do nothing here */
171 }
172 
173 static void
174 kq_setup_kevent(struct kevent *out, evutil_socket_t fd, int filter, short change)
175 {
176 	memset(out, 0, sizeof(out));
177 	out->ident = fd;
178 	out->filter = filter;
179 
180 	if (change & EV_CHANGE_ADD) {
181 		out->flags = EV_ADD;
182 		if (change & EV_ET)
183 			out->flags |= EV_CLEAR;
184 #ifdef NOTE_EOF
185 		/* Make it behave like select() and poll() */
186 		if (filter == EVFILT_READ)
187 			out->fflags = NOTE_EOF;
188 #endif
189 	} else {
190 		EVUTIL_ASSERT(change & EV_CHANGE_DEL);
191 		out->flags = EV_DELETE;
192 	}
193 }
194 
195 static int
196 kq_build_changes_list(const struct event_changelist *changelist,
197     struct kqop *kqop)
198 {
199 	int i;
200 	int n_changes = 0;
201 
202 	for (i = 0; i < changelist->n_changes; ++i) {
203 		struct event_change *in_ch = &changelist->changes[i];
204 		struct kevent *out_ch;
205 		if (n_changes >= kqop->changes_size - 1) {
206 			int newsize = kqop->changes_size * 2;
207 			struct kevent *newchanges;
208 
209 			newchanges = mm_realloc(kqop->changes,
210 			    newsize * sizeof(struct kevent));
211 			if (newchanges == NULL) {
212 				event_warn("%s: realloc", __func__);
213 				return (-1);
214 			}
215 			kqop->changes = newchanges;
216 			kqop->changes_size = newsize;
217 		}
218 		if (in_ch->read_change) {
219 			out_ch = &kqop->changes[n_changes++];
220 			kq_setup_kevent(out_ch, in_ch->fd, EVFILT_READ,
221 			    in_ch->read_change);
222 		}
223 		if (in_ch->write_change) {
224 			out_ch = &kqop->changes[n_changes++];
225 			kq_setup_kevent(out_ch, in_ch->fd, EVFILT_WRITE,
226 			    in_ch->write_change);
227 		}
228 	}
229 	return n_changes;
230 }
231 
232 static int
233 kq_dispatch(struct event_base *base, struct timeval *tv)
234 {
235 	struct kqop *kqop = base->evbase;
236 	struct kevent *events = kqop->events;
237 	struct kevent *changes;
238 	struct timespec ts, *ts_p = NULL;
239 	int i, n_changes, res;
240 
241 	if (tv != NULL) {
242 		TIMEVAL_TO_TIMESPEC(tv, &ts);
243 		ts_p = &ts;
244 	}
245 
246 	/* Build "changes" from "base->changes" */
247 	EVUTIL_ASSERT(kqop->changes);
248 	n_changes = kq_build_changes_list(&base->changelist, kqop);
249 	if (n_changes < 0)
250 		return -1;
251 
252 	event_changelist_remove_all(&base->changelist, base);
253 
254 	/* steal the changes array in case some broken code tries to call
255 	 * dispatch twice at once. */
256 	changes = kqop->changes;
257 	kqop->changes = NULL;
258 
259 	EVBASE_RELEASE_LOCK(base, th_base_lock);
260 
261 	res = kevent(kqop->kq, changes, n_changes,
262 	    events, kqop->events_size, ts_p);
263 
264 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
265 
266 	EVUTIL_ASSERT(kqop->changes == NULL);
267 	kqop->changes = changes;
268 
269 	if (res == -1) {
270 		if (errno != EINTR) {
271 			event_warn("kevent");
272 			return (-1);
273 		}
274 
275 		return (0);
276 	}
277 
278 	event_debug(("%s: kevent reports %d", __func__, res));
279 
280 	for (i = 0; i < res; i++) {
281 		int which = 0;
282 
283 		if (events[i].flags & EV_ERROR) {
284 			/*
285 			 * Error messages that can happen, when a delete fails.
286 			 *   EBADF happens when the file descriptor has been
287 			 *   closed,
288 			 *   ENOENT when the file descriptor was closed and
289 			 *   then reopened.
290 			 *   EINVAL for some reasons not understood; EINVAL
291 			 *   should not be returned ever; but FreeBSD does :-\
292 			 * An error is also indicated when a callback deletes
293 			 * an event we are still processing.  In that case
294 			 * the data field is set to ENOENT.
295 			 */
296 			if (events[i].data == EBADF ||
297 			    events[i].data == EINVAL ||
298 			    events[i].data == ENOENT)
299 				continue;
300 			errno = events[i].data;
301 			return (-1);
302 		}
303 
304 		if (events[i].filter == EVFILT_READ) {
305 			which |= EV_READ;
306 		} else if (events[i].filter == EVFILT_WRITE) {
307 			which |= EV_WRITE;
308 		} else if (events[i].filter == EVFILT_SIGNAL) {
309 			which |= EV_SIGNAL;
310 		}
311 
312 		if (!which)
313 			continue;
314 
315 		if (events[i].filter == EVFILT_SIGNAL) {
316 			evmap_signal_active(base, events[i].ident, 1);
317 		} else {
318 			evmap_io_active(base, events[i].ident, which | EV_ET);
319 		}
320 	}
321 
322 	if (res == kqop->events_size) {
323 		struct kevent *newresult;
324 		int size = kqop->events_size;
325 		/* We used all the events space that we have. Maybe we should
326 		   make it bigger. */
327 		size *= 2;
328 		newresult = mm_realloc(kqop->events,
329 		    size * sizeof(struct kevent));
330 		if (newresult) {
331 			kqop->events = newresult;
332 			kqop->events_size = size;
333 		}
334 	}
335 
336 	return (0);
337 }
338 
339 static void
340 kqop_free(struct kqop *kqop)
341 {
342 	if (kqop->changes)
343 		mm_free(kqop->changes);
344 	if (kqop->events)
345 		mm_free(kqop->events);
346 	if (kqop->kq >= 0 && kqop->pid == getpid())
347 		close(kqop->kq);
348 	memset(kqop, 0, sizeof(struct kqop));
349 	mm_free(kqop);
350 }
351 
352 static void
353 kq_dealloc(struct event_base *base)
354 {
355 	struct kqop *kqop = base->evbase;
356 	evsig_dealloc(base);
357 	kqop_free(kqop);
358 }
359 
360 /* signal handling */
361 static int
362 kq_sig_add(struct event_base *base, int nsignal, short old, short events, void *p)
363 {
364 	struct kqop *kqop = base->evbase;
365 	struct kevent kev;
366 	struct timespec timeout = { 0, 0 };
367 	(void)p;
368 
369 	EVUTIL_ASSERT(nsignal >= 0 && nsignal < NSIG);
370 
371 	memset(&kev, 0, sizeof(kev));
372 	kev.ident = nsignal;
373 	kev.filter = EVFILT_SIGNAL;
374 	kev.flags = EV_ADD;
375 
376 	/* Be ready for the signal if it is sent any
377 	 * time between now and the next call to
378 	 * kq_dispatch. */
379 	if (kevent(kqop->kq, &kev, 1, NULL, 0, &timeout) == -1)
380 		return (-1);
381 
382 	if (_evsig_set_handler(base, nsignal, kq_sighandler) == -1)
383 		return (-1);
384 
385 	return (0);
386 }
387 
388 static int
389 kq_sig_del(struct event_base *base, int nsignal, short old, short events, void *p)
390 {
391 	struct kqop *kqop = base->evbase;
392 	struct kevent kev;
393 
394 	struct timespec timeout = { 0, 0 };
395 	(void)p;
396 
397 	EVUTIL_ASSERT(nsignal >= 0 && nsignal < NSIG);
398 
399 	memset(&kev, 0, sizeof(kev));
400 	kev.ident = nsignal;
401 	kev.filter = EVFILT_SIGNAL;
402 	kev.flags = EV_DELETE;
403 
404 	/* Because we insert signal events
405 	 * immediately, we need to delete them
406 	 * immediately, too */
407 	if (kevent(kqop->kq, &kev, 1, NULL, 0, &timeout) == -1)
408 		return (-1);
409 
410 	if (_evsig_restore_handler(base, nsignal) == -1)
411 		return (-1);
412 
413 	return (0);
414 }
415