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