kern_event.c revision 1.151 1 /* $NetBSD: kern_event.c,v 1.151 2026/01/04 01:33:02 riastradh Exp $ */
2
3 /*-
4 * Copyright (c) 2008, 2009, 2021 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Andrew Doran.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 /*-
33 * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon (at) FreeBSD.org>
34 * Copyright (c) 2009 Apple, Inc
35 * All rights reserved.
36 *
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions
39 * are met:
40 * 1. Redistributions of source code must retain the above copyright
41 * notice, this list of conditions and the following disclaimer.
42 * 2. Redistributions in binary form must reproduce the above copyright
43 * notice, this list of conditions and the following disclaimer in the
44 * documentation and/or other materials provided with the distribution.
45 *
46 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
47 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
48 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
49 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
50 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
51 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
52 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
53 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
54 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
55 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
56 * SUCH DAMAGE.
57 *
58 * FreeBSD: src/sys/kern/kern_event.c,v 1.27 2001/07/05 17:10:44 rwatson Exp
59 */
60
61 #ifdef _KERNEL_OPT
62 #include "opt_ddb.h"
63 #endif /* _KERNEL_OPT */
64
65 #include <sys/cdefs.h>
66 __KERNEL_RCSID(0, "$NetBSD: kern_event.c,v 1.151 2026/01/04 01:33:02 riastradh Exp $");
67
68 #include <sys/param.h>
69 #include <sys/types.h>
70
71 #include <sys/atomic.h>
72 #include <sys/conf.h>
73 #include <sys/event.h>
74 #include <sys/eventvar.h>
75 #include <sys/file.h>
76 #include <sys/filedesc.h>
77 #include <sys/kauth.h>
78 #include <sys/kernel.h>
79 #include <sys/kmem.h>
80 #include <sys/poll.h>
81 #include <sys/proc.h>
82 #include <sys/queue.h>
83 #include <sys/select.h>
84 #include <sys/stat.h>
85 #include <sys/syscallargs.h>
86 #include <sys/systm.h>
87 #include <sys/wait.h>
88
89 static int kqueue_scan(file_t *, size_t, struct kevent *,
90 const struct timespec *, register_t *,
91 const struct kevent_ops *, struct kevent *,
92 size_t);
93 static int kqueue_ioctl(file_t *, u_long, void *);
94 static int kqueue_fcntl(file_t *, u_int, void *);
95 static int kqueue_poll(file_t *, int);
96 static int kqueue_kqfilter(file_t *, struct knote *);
97 static int kqueue_stat(file_t *, struct stat *);
98 static int kqueue_close(file_t *);
99 static void kqueue_restart(file_t *);
100 static int kqueue_fpathconf(file_t *, int, register_t *);
101 static int kqueue_register(struct kqueue *, struct kevent *);
102 static void kqueue_doclose(struct kqueue *, struct klist *, int);
103
104 static void knote_detach(struct knote *, filedesc_t *fdp, bool);
105 static void knote_enqueue(struct knote *);
106 static void knote_activate(struct knote *);
107 static void knote_activate_locked(struct knote *);
108 static void knote_deactivate_locked(struct knote *);
109
110 static void filt_kqdetach(struct knote *);
111 static int filt_kqueue(struct knote *, long hint);
112 static int filt_procattach(struct knote *);
113 static void filt_procdetach(struct knote *);
114 static int filt_proc(struct knote *, long hint);
115 static int filt_fileattach(struct knote *);
116 static void filt_timerexpire(void *x);
117 static int filt_timerattach(struct knote *);
118 static void filt_timerdetach(struct knote *);
119 static int filt_timer(struct knote *, long hint);
120 static int filt_timertouch(struct knote *, struct kevent *, long type);
121 static int filt_userattach(struct knote *);
122 static void filt_userdetach(struct knote *);
123 static int filt_user(struct knote *, long hint);
124 static int filt_usertouch(struct knote *, struct kevent *, long type);
125
126 /*
127 * Private knote state that should never be exposed outside
128 * of kern_event.c
129 *
130 * Field locking:
131 *
132 * q kn_kq->kq_lock
133 */
134 struct knote_impl {
135 struct knote ki_knote;
136 unsigned int ki_influx; /* q: in-flux counter */
137 kmutex_t ki_foplock; /* for kn_filterops */
138 };
139
140 #define KIMPL_TO_KNOTE(kip) (&(kip)->ki_knote)
141 #define KNOTE_TO_KIMPL(knp) container_of((knp), struct knote_impl, ki_knote)
142
143 static inline struct knote *
144 knote_alloc(bool sleepok)
145 {
146 struct knote_impl *ki;
147
148 ki = kmem_zalloc(sizeof(*ki), sleepok ? KM_SLEEP : KM_NOSLEEP);
149 mutex_init(&ki->ki_foplock, MUTEX_DEFAULT, IPL_NONE);
150
151 return KIMPL_TO_KNOTE(ki);
152 }
153
154 static inline void
155 knote_free(struct knote *kn)
156 {
157 struct knote_impl *ki = KNOTE_TO_KIMPL(kn);
158
159 mutex_destroy(&ki->ki_foplock);
160 kmem_free(ki, sizeof(*ki));
161 }
162
163 static inline void
164 knote_foplock_enter(struct knote *kn)
165 {
166 mutex_enter(&KNOTE_TO_KIMPL(kn)->ki_foplock);
167 }
168
169 static inline void
170 knote_foplock_exit(struct knote *kn)
171 {
172 mutex_exit(&KNOTE_TO_KIMPL(kn)->ki_foplock);
173 }
174
175 static inline bool __diagused
176 knote_foplock_owned(struct knote *kn)
177 {
178 return mutex_owned(&KNOTE_TO_KIMPL(kn)->ki_foplock);
179 }
180
181 static const struct fileops kqueueops = {
182 .fo_name = "kqueue",
183 .fo_read = (void *)enxio,
184 .fo_write = (void *)enxio,
185 .fo_ioctl = kqueue_ioctl,
186 .fo_fcntl = kqueue_fcntl,
187 .fo_poll = kqueue_poll,
188 .fo_stat = kqueue_stat,
189 .fo_close = kqueue_close,
190 .fo_kqfilter = kqueue_kqfilter,
191 .fo_restart = kqueue_restart,
192 .fo_fpathconf = kqueue_fpathconf,
193 };
194
195 static void
196 filt_nopdetach(struct knote *kn __unused)
197 {
198 }
199
200 static int
201 filt_nopevent(struct knote *kn __unused, long hint __unused)
202 {
203 return 0;
204 }
205
206 static const struct filterops nop_fd_filtops = {
207 .f_flags = FILTEROP_ISFD | FILTEROP_MPSAFE,
208 .f_attach = NULL,
209 .f_detach = filt_nopdetach,
210 .f_event = filt_nopevent,
211 };
212
213 static const struct filterops nop_filtops = {
214 .f_flags = FILTEROP_MPSAFE,
215 .f_attach = NULL,
216 .f_detach = filt_nopdetach,
217 .f_event = filt_nopevent,
218 };
219
220 static const struct filterops kqread_filtops = {
221 .f_flags = FILTEROP_ISFD | FILTEROP_MPSAFE,
222 .f_attach = NULL,
223 .f_detach = filt_kqdetach,
224 .f_event = filt_kqueue,
225 };
226
227 static const struct filterops proc_filtops = {
228 .f_flags = FILTEROP_MPSAFE,
229 .f_attach = filt_procattach,
230 .f_detach = filt_procdetach,
231 .f_event = filt_proc,
232 };
233
234 /*
235 * file_filtops is not marked MPSAFE because it's going to call
236 * fileops::fo_kqfilter(), which might not be. That function,
237 * however, will override the knote's filterops, and thus will
238 * inherit the MPSAFE-ness of the back-end at that time.
239 */
240 static const struct filterops file_filtops = {
241 .f_flags = FILTEROP_ISFD,
242 .f_attach = filt_fileattach,
243 .f_detach = NULL,
244 .f_event = NULL,
245 };
246
247 static const struct filterops timer_filtops = {
248 .f_flags = FILTEROP_MPSAFE,
249 .f_attach = filt_timerattach,
250 .f_detach = filt_timerdetach,
251 .f_event = filt_timer,
252 .f_touch = filt_timertouch,
253 };
254
255 static const struct filterops user_filtops = {
256 .f_flags = FILTEROP_MPSAFE,
257 .f_attach = filt_userattach,
258 .f_detach = filt_userdetach,
259 .f_event = filt_user,
260 .f_touch = filt_usertouch,
261 };
262
263 static u_int kq_ncallouts = 0;
264 static int kq_calloutmax = (4 * 1024);
265
266 #define KN_HASHSIZE 64 /* XXX should be tunable */
267 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
268
269 extern const struct filterops fs_filtops; /* vfs_syscalls.c */
270 extern const struct filterops sig_filtops; /* kern_sig.c */
271
272 /*
273 * Table for all system-defined filters.
274 * These should be listed in the numeric order of the EVFILT_* defines.
275 * If filtops is NULL, the filter isn't implemented in NetBSD.
276 * End of list is when name is NULL.
277 *
278 * Note that 'refcnt' is meaningless for built-in filters.
279 */
280 struct kfilter {
281 const char *name; /* name of filter */
282 uint32_t filter; /* id of filter */
283 unsigned refcnt; /* reference count */
284 const struct filterops *filtops;/* operations for filter */
285 size_t namelen; /* length of name string */
286 };
287
288 /* System defined filters */
289 static struct kfilter sys_kfilters[] = {
290 { "EVFILT_READ", EVFILT_READ, 0, &file_filtops, 0 },
291 { "EVFILT_WRITE", EVFILT_WRITE, 0, &file_filtops, 0, },
292 { "EVFILT_AIO", EVFILT_AIO, 0, NULL, 0 },
293 { "EVFILT_VNODE", EVFILT_VNODE, 0, &file_filtops, 0 },
294 { "EVFILT_PROC", EVFILT_PROC, 0, &proc_filtops, 0 },
295 { "EVFILT_SIGNAL", EVFILT_SIGNAL, 0, &sig_filtops, 0 },
296 { "EVFILT_TIMER", EVFILT_TIMER, 0, &timer_filtops, 0 },
297 { "EVFILT_FS", EVFILT_FS, 0, &fs_filtops, 0 },
298 { "EVFILT_USER", EVFILT_USER, 0, &user_filtops, 0 },
299 { "EVFILT_EMPTY", EVFILT_EMPTY, 0, &file_filtops, 0 },
300 { NULL, 0, 0, NULL, 0 },
301 };
302
303 /* User defined kfilters */
304 static struct kfilter *user_kfilters; /* array */
305 static int user_kfilterc; /* current offset */
306 static int user_kfiltermaxc; /* max size so far */
307 static size_t user_kfiltersz; /* size of allocated memory */
308
309 /*
310 * Global Locks.
311 *
312 * Lock order:
313 *
314 * kqueue_filter_lock
315 * -> kn_kq->kq_fdp->fd_lock
316 * -> knote foplock (if taken)
317 * -> object lock (e.g., device driver lock, &c.)
318 * -> kn_kq->kq_lock
319 *
320 * Locking rules. ==> indicates the lock is acquired by the backing
321 * object, locks prior are acquired before calling filter ops:
322 *
323 * f_attach: fdp->fd_lock -> knote foplock ->
324 * (maybe) KERNEL_LOCK ==> backing object lock
325 *
326 * f_detach: fdp->fd_lock -> knote foplock ->
327 * (maybe) KERNEL_LOCK ==> backing object lock
328 *
329 * f_event via kevent: fdp->fd_lock -> knote foplock ->
330 * (maybe) KERNEL_LOCK ==> backing object lock
331 * N.B. NOTE_SUBMIT will never be set in the "hint" argument
332 * in this case.
333 *
334 * f_event via knote (via backing object: Whatever caller guarantees.
335 * Typically:
336 * f_event(NOTE_SUBMIT): caller has already acquired backing
337 * object lock.
338 * f_event(!NOTE_SUBMIT): caller has not acquired backing object,
339 * lock or has possibly acquired KERNEL_LOCK. Backing object
340 * lock may or may not be acquired as-needed.
341 * N.B. the knote foplock will **not** be acquired in this case. The
342 * caller guarantees that klist_fini() will not be called concurrently
343 * with knote().
344 *
345 * f_touch: fdp->fd_lock -> kn_kq->kq_lock (spin lock)
346 * N.B. knote foplock is **not** acquired in this case and
347 * the caller must guarantee that klist_fini() will never
348 * be called. kevent_register() restricts filters that
349 * provide f_touch to known-safe cases.
350 *
351 * klist_fini(): Caller must guarantee that no more knotes can
352 * be attached to the klist, and must **not** hold the backing
353 * object's lock; klist_fini() itself will acquire the foplock
354 * of each knote on the klist.
355 *
356 * Locking rules when detaching knotes:
357 *
358 * There are some situations where knote submission may require dropping
359 * locks (see knote_proc_fork()). In order to support this, it's possible
360 * to mark a knote as being 'in-flux'. Such a knote is guaranteed not to
361 * be detached while it remains in-flux. Because it will not be detached,
362 * locks can be dropped so e.g. memory can be allocated, locks on other
363 * data structures can be acquired, etc. During this time, any attempt to
364 * detach an in-flux knote must wait until the knote is no longer in-flux.
365 * When this happens, the knote is marked for death (KN_WILLDETACH) and the
366 * LWP who gets to finish the detach operation is recorded in the knote's
367 * 'udata' field (which is no longer required for its original purpose once
368 * a knote is so marked). Code paths that lead to knote_detach() must ensure
369 * that their LWP is the one tasked with its final demise after waiting for
370 * the in-flux status of the knote to clear. Note that once a knote is
371 * marked KN_WILLDETACH, no code paths may put it into an in-flux state.
372 *
373 * Once the special circumstances have been handled, the locks are re-
374 * acquired in the proper order (object lock -> kq_lock), the knote taken
375 * out of flux, and any waiters are notified. Because waiters must have
376 * also dropped *their* locks in order to safely block, they must re-
377 * validate all of their assumptions; see knote_detach_quiesce(). See also
378 * the kqueue_register() (EV_ADD, EV_DELETE) and kqueue_scan() (EV_ONESHOT)
379 * cases.
380 *
381 * When kqueue_scan() encounters an in-flux knote, the situation is
382 * treated like another LWP's list marker.
383 *
384 * LISTEN WELL: It is important to not hold knotes in flux for an
385 * extended period of time! In-flux knotes effectively block any
386 * progress of the kqueue_scan() operation. Any code paths that place
387 * knotes in-flux should be careful to not block for indefinite periods
388 * of time, such as for memory allocation (i.e. KM_NOSLEEP is OK, but
389 * KM_SLEEP is not).
390 */
391 static krwlock_t kqueue_filter_lock; /* lock on filter lists */
392
393 #define KQ_FLUX_WAIT(kq) (void)cv_wait(&kq->kq_cv, &kq->kq_lock)
394 #define KQ_FLUX_WAKEUP(kq) cv_broadcast(&kq->kq_cv)
395
396 static inline bool
397 kn_in_flux(struct knote *kn)
398 {
399 KASSERT(mutex_owned(&kn->kn_kq->kq_lock));
400 return KNOTE_TO_KIMPL(kn)->ki_influx != 0;
401 }
402
403 static inline bool
404 kn_enter_flux(struct knote *kn)
405 {
406 KASSERT(mutex_owned(&kn->kn_kq->kq_lock));
407
408 if (kn->kn_status & KN_WILLDETACH) {
409 return false;
410 }
411
412 struct knote_impl *ki = KNOTE_TO_KIMPL(kn);
413 KASSERT(ki->ki_influx < UINT_MAX);
414 ki->ki_influx++;
415
416 return true;
417 }
418
419 static inline bool
420 kn_leave_flux(struct knote *kn)
421 {
422 KASSERT(mutex_owned(&kn->kn_kq->kq_lock));
423
424 struct knote_impl *ki = KNOTE_TO_KIMPL(kn);
425 KASSERT(ki->ki_influx > 0);
426 ki->ki_influx--;
427 return ki->ki_influx == 0;
428 }
429
430 static void
431 kn_wait_flux(struct knote *kn, bool can_loop)
432 {
433 struct knote_impl *ki = KNOTE_TO_KIMPL(kn);
434 bool loop;
435
436 KASSERT(mutex_owned(&kn->kn_kq->kq_lock));
437
438 /*
439 * It may not be safe for us to touch the knote again after
440 * dropping the kq_lock. The caller has let us know in
441 * 'can_loop'.
442 */
443 for (loop = true; loop && ki->ki_influx != 0; loop = can_loop) {
444 KQ_FLUX_WAIT(kn->kn_kq);
445 }
446 }
447
448 #define KNOTE_WILLDETACH(kn) \
449 do { \
450 (kn)->kn_status |= KN_WILLDETACH; \
451 (kn)->kn_kevent.udata = curlwp; \
452 } while (/*CONSTCOND*/0)
453
454 /*
455 * Wait until the specified knote is in a quiescent state and
456 * safe to detach. Returns true if we potentially blocked (and
457 * thus dropped our locks).
458 */
459 static bool
460 knote_detach_quiesce(struct knote *kn)
461 {
462 struct kqueue *kq = kn->kn_kq;
463 filedesc_t *fdp = kq->kq_fdp;
464
465 KASSERT(mutex_owned(&fdp->fd_lock));
466
467 mutex_spin_enter(&kq->kq_lock);
468 /*
469 * There are two cases where we might see KN_WILLDETACH here:
470 *
471 * 1. Someone else has already started detaching the knote but
472 * had to wait for it to settle first.
473 *
474 * 2. We had to wait for it to settle, and had to come back
475 * around after re-acquiring the locks.
476 *
477 * When KN_WILLDETACH is set, we also set the LWP that claimed
478 * the prize of finishing the detach in the 'udata' field of the
479 * knote (which will never be used again for its usual purpose
480 * once the note is in this state). If it doesn't point to us,
481 * we must drop the locks and let them in to finish the job.
482 *
483 * Otherwise, once we have claimed the knote for ourselves, we
484 * can finish waiting for it to settle. The is the only scenario
485 * where touching a detaching knote is safe after dropping the
486 * locks.
487 */
488 if ((kn->kn_status & KN_WILLDETACH) != 0 &&
489 kn->kn_kevent.udata != curlwp) {
490 /*
491 * N.B. it is NOT safe for us to touch the knote again
492 * after dropping the locks here. The caller must go
493 * back around and re-validate everything. However, if
494 * the knote is in-flux, we want to block to minimize
495 * busy-looping.
496 */
497 mutex_exit(&fdp->fd_lock);
498 if (kn_in_flux(kn)) {
499 kn_wait_flux(kn, false);
500 mutex_spin_exit(&kq->kq_lock);
501 return true;
502 }
503 mutex_spin_exit(&kq->kq_lock);
504 preempt_point();
505 return true;
506 }
507 /*
508 * If we get here, we know that we will be claiming the
509 * detach responsibilies, or that we already have and
510 * this is the second attempt after re-validation.
511 */
512 KASSERT((kn->kn_status & KN_WILLDETACH) == 0 ||
513 kn->kn_kevent.udata == curlwp);
514 /*
515 * Similarly, if we get here, either we are just claiming it
516 * and may have to wait for it to settle, or if this is the
517 * second attempt after re-validation that no other code paths
518 * have put it in-flux.
519 */
520 KASSERT((kn->kn_status & KN_WILLDETACH) == 0 ||
521 kn_in_flux(kn) == false);
522 KNOTE_WILLDETACH(kn);
523 if (kn_in_flux(kn)) {
524 mutex_exit(&fdp->fd_lock);
525 kn_wait_flux(kn, true);
526 /*
527 * It is safe for us to touch the knote again after
528 * dropping the locks, but the caller must still
529 * re-validate everything because other aspects of
530 * the environment may have changed while we blocked.
531 */
532 KASSERT(kn_in_flux(kn) == false);
533 mutex_spin_exit(&kq->kq_lock);
534 return true;
535 }
536 mutex_spin_exit(&kq->kq_lock);
537
538 return false;
539 }
540
541 /*
542 * Calls into the filterops need to be resilient against things which
543 * destroy a klist, e.g. device detach, freeing a vnode, etc., to avoid
544 * chasing garbage pointers (to data, or even potentially code in a
545 * module about to be unloaded). To that end, we acquire the
546 * knote foplock before calling into the filter ops. When a driver
547 * (or anything else) is tearing down its klist, klist_fini() enumerates
548 * each knote, acquires its foplock, and replaces the filterops with a
549 * nop stub, allowing knote detach (when descriptors are closed) to safely
550 * proceed.
551 */
552
553 static int
554 filter_attach(struct knote *kn)
555 {
556 int rv;
557
558 KASSERT(knote_foplock_owned(kn));
559 KASSERT(kn->kn_fop != NULL);
560 KASSERT(kn->kn_fop->f_attach != NULL);
561
562 /*
563 * N.B. that kn->kn_fop may change as the result of calling
564 * f_attach(). After f_attach() returns, kn->kn_fop may not
565 * be modified by code outside of klist_fini().
566 */
567 if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
568 rv = kn->kn_fop->f_attach(kn);
569 } else {
570 KERNEL_LOCK(1, NULL);
571 rv = kn->kn_fop->f_attach(kn);
572 KERNEL_UNLOCK_ONE(NULL);
573 }
574
575 return rv;
576 }
577
578 static void
579 filter_detach(struct knote *kn)
580 {
581
582 KASSERT(knote_foplock_owned(kn));
583 KASSERT(kn->kn_fop != NULL);
584 KASSERT(kn->kn_fop->f_detach != NULL);
585
586 if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
587 kn->kn_fop->f_detach(kn);
588 } else {
589 KERNEL_LOCK(1, NULL);
590 kn->kn_fop->f_detach(kn);
591 KERNEL_UNLOCK_ONE(NULL);
592 }
593 }
594
595 static int
596 filter_event(struct knote *kn, long hint, bool submitting)
597 {
598 int rv;
599
600 /* See knote(). */
601 KASSERT(submitting || knote_foplock_owned(kn));
602 KASSERT(kn->kn_fop != NULL);
603 KASSERT(kn->kn_fop->f_event != NULL);
604
605 if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
606 rv = kn->kn_fop->f_event(kn, hint);
607 } else {
608 KERNEL_LOCK(1, NULL);
609 rv = kn->kn_fop->f_event(kn, hint);
610 KERNEL_UNLOCK_ONE(NULL);
611 }
612
613 return rv;
614 }
615
616 static int
617 filter_touch(struct knote *kn, struct kevent *kev, long type)
618 {
619
620 /*
621 * XXX We cannot assert that the knote foplock is held here
622 * XXX beause we cannot safely acquire it in all cases
623 * XXX where "touch" will be used in kqueue_scan(). We just
624 * XXX have to assume that f_touch will always be safe to call,
625 * XXX and kqueue_register() allows only the two known-safe
626 * XXX users of that op.
627 */
628
629 KASSERT(kn->kn_fop != NULL);
630 KASSERT(kn->kn_fop->f_touch != NULL);
631
632 return kn->kn_fop->f_touch(kn, kev, type);
633 }
634
635 static kauth_listener_t kqueue_listener;
636
637 static int
638 kqueue_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
639 void *arg0, void *arg1, void *arg2, void *arg3)
640 {
641 struct proc *p;
642 int result;
643
644 result = KAUTH_RESULT_DEFER;
645 p = arg0;
646
647 if (action != KAUTH_PROCESS_KEVENT_FILTER)
648 return result;
649
650 if ((kauth_cred_getuid(p->p_cred) != kauth_cred_getuid(cred) ||
651 ISSET(p->p_flag, PK_SUGID)))
652 return result;
653
654 result = KAUTH_RESULT_ALLOW;
655
656 return result;
657 }
658
659 /*
660 * Initialize the kqueue subsystem.
661 */
662 void
663 kqueue_init(void)
664 {
665
666 rw_init(&kqueue_filter_lock);
667
668 kqueue_listener = kauth_listen_scope(KAUTH_SCOPE_PROCESS,
669 kqueue_listener_cb, NULL);
670 }
671
672 /*
673 * Find kfilter entry by name, or NULL if not found.
674 */
675 static struct kfilter *
676 kfilter_byname_sys(const char *name)
677 {
678 int i;
679
680 KASSERT(rw_lock_held(&kqueue_filter_lock));
681
682 for (i = 0; sys_kfilters[i].name != NULL; i++) {
683 if (strcmp(name, sys_kfilters[i].name) == 0)
684 return &sys_kfilters[i];
685 }
686 return NULL;
687 }
688
689 static struct kfilter *
690 kfilter_byname_user(const char *name)
691 {
692 int i;
693
694 KASSERT(rw_lock_held(&kqueue_filter_lock));
695
696 /* user filter slots have a NULL name if previously deregistered */
697 for (i = 0; i < user_kfilterc ; i++) {
698 if (user_kfilters[i].name != NULL &&
699 strcmp(name, user_kfilters[i].name) == 0)
700 return &user_kfilters[i];
701 }
702 return NULL;
703 }
704
705 static struct kfilter *
706 kfilter_byname(const char *name)
707 {
708 struct kfilter *kfilter;
709
710 KASSERT(rw_lock_held(&kqueue_filter_lock));
711
712 if ((kfilter = kfilter_byname_sys(name)) != NULL)
713 return kfilter;
714
715 return kfilter_byname_user(name);
716 }
717
718 /*
719 * Find kfilter entry by filter id, or NULL if not found.
720 * Assumes entries are indexed in filter id order, for speed.
721 */
722 static struct kfilter *
723 kfilter_byfilter(uint32_t filter)
724 {
725 struct kfilter *kfilter;
726
727 KASSERT(rw_lock_held(&kqueue_filter_lock));
728
729 if (filter < EVFILT_SYSCOUNT) /* it's a system filter */
730 kfilter = &sys_kfilters[filter];
731 else if (user_kfilters != NULL &&
732 filter < EVFILT_SYSCOUNT + user_kfilterc)
733 /* it's a user filter */
734 kfilter = &user_kfilters[filter - EVFILT_SYSCOUNT];
735 else
736 return (NULL); /* out of range */
737 KASSERT(kfilter->filter == filter); /* sanity check! */
738 return (kfilter);
739 }
740
741 /*
742 * Register a new kfilter. Stores the entry in user_kfilters.
743 * Returns 0 if operation succeeded, or an appropriate errno(2) otherwise.
744 * If retfilter != NULL, the new filterid is returned in it.
745 */
746 int
747 kfilter_register(const char *name, const struct filterops *filtops,
748 int *retfilter)
749 {
750 struct kfilter *kfilter;
751 size_t len;
752 int i;
753
754 if (name == NULL || name[0] == '\0' || filtops == NULL)
755 return (EINVAL); /* invalid args */
756
757 rw_enter(&kqueue_filter_lock, RW_WRITER);
758 if (kfilter_byname(name) != NULL) {
759 rw_exit(&kqueue_filter_lock);
760 return (EEXIST); /* already exists */
761 }
762 if (user_kfilterc > 0xffffffff - EVFILT_SYSCOUNT) {
763 rw_exit(&kqueue_filter_lock);
764 return (EINVAL); /* too many */
765 }
766
767 for (i = 0; i < user_kfilterc; i++) {
768 kfilter = &user_kfilters[i];
769 if (kfilter->name == NULL) {
770 /* Previously deregistered slot. Reuse. */
771 goto reuse;
772 }
773 }
774
775 /* check if need to grow user_kfilters */
776 if (user_kfilterc + 1 > user_kfiltermaxc) {
777 /* Grow in KFILTER_EXTENT chunks. */
778 user_kfiltermaxc += KFILTER_EXTENT;
779 len = user_kfiltermaxc * sizeof(*kfilter);
780 kfilter = kmem_alloc(len, KM_SLEEP);
781 memset((char *)kfilter + user_kfiltersz, 0, len - user_kfiltersz);
782 if (user_kfilters != NULL) {
783 memcpy(kfilter, user_kfilters, user_kfiltersz);
784 kmem_free(user_kfilters, user_kfiltersz);
785 }
786 user_kfiltersz = len;
787 user_kfilters = kfilter;
788 }
789 /* Adding new slot */
790 kfilter = &user_kfilters[user_kfilterc++];
791 reuse:
792 kfilter->name = kmem_strdupsize(name, &kfilter->namelen, KM_SLEEP);
793
794 kfilter->filter = (kfilter - user_kfilters) + EVFILT_SYSCOUNT;
795
796 kfilter->filtops = kmem_alloc(sizeof(*filtops), KM_SLEEP);
797 memcpy(__UNCONST(kfilter->filtops), filtops, sizeof(*filtops));
798
799 if (retfilter != NULL)
800 *retfilter = kfilter->filter;
801 rw_exit(&kqueue_filter_lock);
802
803 return (0);
804 }
805
806 /*
807 * Unregister a kfilter previously registered with kfilter_register.
808 * This retains the filter id, but clears the name and frees filtops (filter
809 * operations), so that the number isn't reused during a boot.
810 * Returns 0 if operation succeeded, or an appropriate errno(2) otherwise.
811 */
812 int
813 kfilter_unregister(const char *name)
814 {
815 struct kfilter *kfilter;
816
817 if (name == NULL || name[0] == '\0')
818 return (EINVAL); /* invalid name */
819
820 rw_enter(&kqueue_filter_lock, RW_WRITER);
821 if (kfilter_byname_sys(name) != NULL) {
822 rw_exit(&kqueue_filter_lock);
823 return (EINVAL); /* can't detach system filters */
824 }
825
826 kfilter = kfilter_byname_user(name);
827 if (kfilter == NULL) {
828 rw_exit(&kqueue_filter_lock);
829 return (ENOENT);
830 }
831 if (kfilter->refcnt != 0) {
832 rw_exit(&kqueue_filter_lock);
833 return (EBUSY);
834 }
835
836 /* Cast away const (but we know it's safe. */
837 kmem_free(__UNCONST(kfilter->name), kfilter->namelen);
838 kfilter->name = NULL; /* mark as `not implemented' */
839
840 if (kfilter->filtops != NULL) {
841 /* Cast away const (but we know it's safe. */
842 kmem_free(__UNCONST(kfilter->filtops),
843 sizeof(*kfilter->filtops));
844 kfilter->filtops = NULL; /* mark as `not implemented' */
845 }
846 rw_exit(&kqueue_filter_lock);
847
848 return (0);
849 }
850
851
852 /*
853 * Filter attach method for EVFILT_READ and EVFILT_WRITE on normal file
854 * descriptors. Calls fileops kqfilter method for given file descriptor.
855 */
856 static int
857 filt_fileattach(struct knote *kn)
858 {
859 file_t *fp;
860
861 fp = kn->kn_obj;
862
863 return (*fp->f_ops->fo_kqfilter)(fp, kn);
864 }
865
866 /*
867 * Filter detach method for EVFILT_READ on kqueue descriptor.
868 */
869 static void
870 filt_kqdetach(struct knote *kn)
871 {
872 struct kqueue *kq;
873
874 kq = ((file_t *)kn->kn_obj)->f_kqueue;
875
876 mutex_spin_enter(&kq->kq_lock);
877 selremove_knote(&kq->kq_sel, kn);
878 mutex_spin_exit(&kq->kq_lock);
879 }
880
881 /*
882 * Filter event method for EVFILT_READ on kqueue descriptor.
883 */
884 /*ARGSUSED*/
885 static int
886 filt_kqueue(struct knote *kn, long hint)
887 {
888 struct kqueue *kq;
889 int rv;
890
891 kq = ((file_t *)kn->kn_obj)->f_kqueue;
892
893 if (hint != NOTE_SUBMIT)
894 mutex_spin_enter(&kq->kq_lock);
895 kn->kn_data = KQ_COUNT(kq);
896 rv = (kn->kn_data > 0);
897 if (hint != NOTE_SUBMIT)
898 mutex_spin_exit(&kq->kq_lock);
899
900 return rv;
901 }
902
903 /*
904 * Filter attach method for EVFILT_PROC.
905 */
906 static int
907 filt_procattach(struct knote *kn)
908 {
909 struct proc *p;
910
911 mutex_enter(&proc_lock);
912 p = proc_find(kn->kn_id);
913 if (p == NULL) {
914 mutex_exit(&proc_lock);
915 return ESRCH;
916 }
917
918 /*
919 * Fail if it's not owned by you, or the last exec gave us
920 * setuid/setgid privs (unless you're root).
921 */
922 mutex_enter(p->p_lock);
923 mutex_exit(&proc_lock);
924 if (kauth_authorize_process(curlwp->l_cred,
925 KAUTH_PROCESS_KEVENT_FILTER, p, NULL, NULL, NULL) != 0) {
926 mutex_exit(p->p_lock);
927 return EACCES;
928 }
929
930 kn->kn_obj = p;
931 kn->kn_flags |= EV_CLEAR; /* automatically set */
932
933 /*
934 * NOTE_CHILD is only ever generated internally; don't let it
935 * leak in from user-space. See knote_proc_fork_track().
936 */
937 kn->kn_sfflags &= ~NOTE_CHILD;
938
939 klist_insert(&p->p_klist, kn);
940 mutex_exit(p->p_lock);
941
942 return 0;
943 }
944
945 /*
946 * Filter detach method for EVFILT_PROC.
947 *
948 * The knote may be attached to a different process, which may exit,
949 * leaving nothing for the knote to be attached to. So when the process
950 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
951 * it will be deleted when read out. However, as part of the knote deletion,
952 * this routine is called, so a check is needed to avoid actually performing
953 * a detach, because the original process might not exist any more.
954 */
955 static void
956 filt_procdetach(struct knote *kn)
957 {
958 struct kqueue *kq = kn->kn_kq;
959 struct proc *p;
960
961 /*
962 * We have to synchronize with knote_proc_exit(), but we
963 * are forced to acquire the locks in the wrong order here
964 * because we can't be sure kn->kn_obj is valid unless
965 * KN_DETACHED is not set.
966 */
967 again:
968 mutex_spin_enter(&kq->kq_lock);
969 if ((kn->kn_status & KN_DETACHED) == 0) {
970 p = kn->kn_obj;
971 if (!mutex_tryenter(p->p_lock)) {
972 mutex_spin_exit(&kq->kq_lock);
973 preempt_point();
974 goto again;
975 }
976 kn->kn_status |= KN_DETACHED;
977 klist_remove(&p->p_klist, kn);
978 mutex_exit(p->p_lock);
979 }
980 mutex_spin_exit(&kq->kq_lock);
981 }
982
983 /*
984 * Filter event method for EVFILT_PROC.
985 *
986 * Due to some of the complexities of process locking, we have special
987 * entry points for delivering knote submissions. filt_proc() is used
988 * only to check for activation from kqueue_register() and kqueue_scan().
989 */
990 static int
991 filt_proc(struct knote *kn, long hint)
992 {
993 struct kqueue *kq = kn->kn_kq;
994 uint32_t fflags;
995
996 /*
997 * Because we share the same klist with signal knotes, just
998 * ensure that we're not being invoked for the proc-related
999 * submissions.
1000 */
1001 KASSERT((hint & (NOTE_EXEC | NOTE_EXIT | NOTE_FORK)) == 0);
1002
1003 mutex_spin_enter(&kq->kq_lock);
1004 fflags = kn->kn_fflags;
1005 mutex_spin_exit(&kq->kq_lock);
1006
1007 return fflags != 0;
1008 }
1009
1010 void
1011 knote_proc_exec(struct proc *p)
1012 {
1013 struct knote *kn, *tmpkn;
1014 struct kqueue *kq;
1015 uint32_t fflags;
1016
1017 mutex_enter(p->p_lock);
1018
1019 SLIST_FOREACH_SAFE(kn, &p->p_klist, kn_selnext, tmpkn) {
1020 /* N.B. EVFILT_SIGNAL knotes are on this same list. */
1021 if (kn->kn_fop == &sig_filtops) {
1022 continue;
1023 }
1024 KASSERT(kn->kn_fop == &proc_filtops);
1025
1026 kq = kn->kn_kq;
1027 mutex_spin_enter(&kq->kq_lock);
1028 fflags = (kn->kn_fflags |= (kn->kn_sfflags & NOTE_EXEC));
1029 if (fflags) {
1030 knote_activate_locked(kn);
1031 }
1032 mutex_spin_exit(&kq->kq_lock);
1033 }
1034
1035 mutex_exit(p->p_lock);
1036 }
1037
1038 static int __noinline
1039 knote_proc_fork_track(struct proc *p1, struct proc *p2, struct knote *okn)
1040 {
1041 struct kqueue *kq = okn->kn_kq;
1042
1043 KASSERT(mutex_owned(&kq->kq_lock));
1044 KASSERT(mutex_owned(p1->p_lock));
1045
1046 /*
1047 * We're going to put this knote into flux while we drop
1048 * the locks and create and attach a new knote to track the
1049 * child. If we are not able to enter flux, then this knote
1050 * is about to go away, so skip the notification.
1051 */
1052 if (!kn_enter_flux(okn)) {
1053 return 0;
1054 }
1055
1056 mutex_spin_exit(&kq->kq_lock);
1057 mutex_exit(p1->p_lock);
1058
1059 /*
1060 * We actually have to register *two* new knotes:
1061 *
1062 * ==> One for the NOTE_CHILD notification. This is a forced
1063 * ONESHOT note.
1064 *
1065 * ==> One to actually track the child process as it subsequently
1066 * forks, execs, and, ultimately, exits.
1067 *
1068 * If we only register a single knote, then it's possible for
1069 * for the NOTE_CHILD and NOTE_EXIT to be collapsed into a single
1070 * notification if the child exits before the tracking process
1071 * has received the NOTE_CHILD notification, which applications
1072 * aren't expecting (the event's 'data' field would be clobbered,
1073 * for example).
1074 *
1075 * To do this, what we have here is an **extremely** stripped-down
1076 * version of kqueue_register() that has the following properties:
1077 *
1078 * ==> Does not block to allocate memory. If we are unable
1079 * to allocate memory, we return ENOMEM.
1080 *
1081 * ==> Does not search for existing knotes; we know there
1082 * are not any because this is a new process that isn't
1083 * even visible to other processes yet.
1084 *
1085 * ==> Assumes that the knhash for our kq's descriptor table
1086 * already exists (after all, we're already tracking
1087 * processes with knotes if we got here).
1088 *
1089 * ==> Directly attaches the new tracking knote to the child
1090 * process.
1091 *
1092 * The whole point is to do the minimum amount of work while the
1093 * knote is held in-flux, and to avoid doing extra work in general
1094 * (we already have the new child process; why bother looking it
1095 * up again?).
1096 */
1097 filedesc_t *fdp = kq->kq_fdp;
1098 struct knote *knchild, *kntrack;
1099 int error = 0;
1100
1101 knchild = knote_alloc(false);
1102 kntrack = knote_alloc(false);
1103 if (__predict_false(knchild == NULL || kntrack == NULL)) {
1104 error = ENOMEM;
1105 goto out;
1106 }
1107
1108 kntrack->kn_obj = p2;
1109 kntrack->kn_id = p2->p_pid;
1110 kntrack->kn_kq = kq;
1111 kntrack->kn_fop = okn->kn_fop;
1112 kntrack->kn_kfilter = okn->kn_kfilter;
1113 kntrack->kn_sfflags = okn->kn_sfflags;
1114 kntrack->kn_sdata = p1->p_pid;
1115
1116 kntrack->kn_kevent.ident = p2->p_pid;
1117 kntrack->kn_kevent.filter = okn->kn_filter;
1118 kntrack->kn_kevent.flags =
1119 okn->kn_flags | EV_ADD | EV_ENABLE | EV_CLEAR;
1120 kntrack->kn_kevent.fflags = 0;
1121 kntrack->kn_kevent.data = 0;
1122 kntrack->kn_kevent.udata = okn->kn_kevent.udata; /* preserve udata */
1123
1124 /*
1125 * The child note does not need to be attached to the
1126 * new proc's klist at all.
1127 */
1128 *knchild = *kntrack;
1129 knchild->kn_status = KN_DETACHED;
1130 knchild->kn_sfflags = 0;
1131 knchild->kn_kevent.flags |= EV_ONESHOT;
1132 knchild->kn_kevent.fflags = NOTE_CHILD;
1133 knchild->kn_kevent.data = p1->p_pid; /* parent */
1134
1135 mutex_enter(&fdp->fd_lock);
1136
1137 /*
1138 * We need to check to see if the kq is closing, and skip
1139 * attaching the knote if so. Normally, this isn't necessary
1140 * when coming in the front door because the file descriptor
1141 * layer will synchronize this.
1142 *
1143 * It's safe to test KQ_CLOSING without taking the kq_lock
1144 * here because that flag is only ever set when the fd_lock
1145 * is also held.
1146 */
1147 if (__predict_false(kq->kq_count & KQ_CLOSING)) {
1148 mutex_exit(&fdp->fd_lock);
1149 goto out;
1150 }
1151
1152 /*
1153 * We do the "insert into FD table" and "attach to klist" steps
1154 * in the opposite order of kqueue_register() here to avoid
1155 * having to take p2->p_lock twice. But this is OK because we
1156 * hold fd_lock across the entire operation.
1157 */
1158
1159 mutex_enter(p2->p_lock);
1160 error = kauth_authorize_process(curlwp->l_cred,
1161 KAUTH_PROCESS_KEVENT_FILTER, p2, NULL, NULL, NULL);
1162 if (__predict_false(error != 0)) {
1163 mutex_exit(p2->p_lock);
1164 mutex_exit(&fdp->fd_lock);
1165 error = EACCES;
1166 goto out;
1167 }
1168 klist_insert(&p2->p_klist, kntrack);
1169 mutex_exit(p2->p_lock);
1170
1171 KASSERT(fdp->fd_knhashmask != 0);
1172 KASSERT(fdp->fd_knhash != NULL);
1173 struct klist *list = &fdp->fd_knhash[KN_HASH(kntrack->kn_id,
1174 fdp->fd_knhashmask)];
1175 SLIST_INSERT_HEAD(list, kntrack, kn_link);
1176 SLIST_INSERT_HEAD(list, knchild, kn_link);
1177
1178 /* This adds references for knchild *and* kntrack. */
1179 atomic_add_int(&kntrack->kn_kfilter->refcnt, 2);
1180
1181 knote_activate(knchild);
1182
1183 kntrack = NULL;
1184 knchild = NULL;
1185
1186 mutex_exit(&fdp->fd_lock);
1187
1188 out:
1189 if (__predict_false(knchild != NULL)) {
1190 knote_free(knchild);
1191 }
1192 if (__predict_false(kntrack != NULL)) {
1193 knote_free(kntrack);
1194 }
1195 mutex_enter(p1->p_lock);
1196 mutex_spin_enter(&kq->kq_lock);
1197
1198 if (kn_leave_flux(okn)) {
1199 KQ_FLUX_WAKEUP(kq);
1200 }
1201
1202 return error;
1203 }
1204
1205 void
1206 knote_proc_fork(struct proc *p1, struct proc *p2)
1207 {
1208 struct knote *kn;
1209 struct kqueue *kq;
1210 uint32_t fflags;
1211
1212 mutex_enter(p1->p_lock);
1213
1214 /*
1215 * N.B. We DO NOT use SLIST_FOREACH_SAFE() here because we
1216 * don't want to pre-fetch the next knote; in the event we
1217 * have to drop p_lock, we will have put the knote in-flux,
1218 * meaning that no one will be able to detach it until we
1219 * have taken the knote out of flux. However, that does
1220 * NOT stop someone else from detaching the next note in the
1221 * list while we have it unlocked. Thus, we want to fetch
1222 * the next note in the list only after we have re-acquired
1223 * the lock, and using SLIST_FOREACH() will satisfy that.
1224 */
1225 SLIST_FOREACH(kn, &p1->p_klist, kn_selnext) {
1226 /* N.B. EVFILT_SIGNAL knotes are on this same list. */
1227 if (kn->kn_fop == &sig_filtops) {
1228 continue;
1229 }
1230 KASSERT(kn->kn_fop == &proc_filtops);
1231
1232 kq = kn->kn_kq;
1233 mutex_spin_enter(&kq->kq_lock);
1234 kn->kn_fflags |= (kn->kn_sfflags & NOTE_FORK);
1235 if (__predict_false(kn->kn_sfflags & NOTE_TRACK)) {
1236 /*
1237 * This will drop kq_lock and p_lock and
1238 * re-acquire them before it returns.
1239 */
1240 if (knote_proc_fork_track(p1, p2, kn)) {
1241 kn->kn_fflags |= NOTE_TRACKERR;
1242 }
1243 KASSERT(mutex_owned(p1->p_lock));
1244 KASSERT(mutex_owned(&kq->kq_lock));
1245 }
1246 fflags = kn->kn_fflags;
1247 if (fflags) {
1248 knote_activate_locked(kn);
1249 }
1250 mutex_spin_exit(&kq->kq_lock);
1251 }
1252
1253 mutex_exit(p1->p_lock);
1254 }
1255
1256 void
1257 knote_proc_exit(struct proc *p)
1258 {
1259 struct knote *kn;
1260 struct kqueue *kq;
1261
1262 KASSERT(mutex_owned(p->p_lock));
1263
1264 while (!SLIST_EMPTY(&p->p_klist)) {
1265 kn = SLIST_FIRST(&p->p_klist);
1266 kq = kn->kn_kq;
1267
1268 KASSERT(kn->kn_obj == p);
1269
1270 mutex_spin_enter(&kq->kq_lock);
1271 kn->kn_data = P_WAITSTATUS(p);
1272 /*
1273 * Mark as ONESHOT, so that the knote is g/c'ed
1274 * when read.
1275 */
1276 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
1277 kn->kn_fflags |= kn->kn_sfflags & NOTE_EXIT;
1278
1279 /*
1280 * Detach the knote from the process and mark it as such.
1281 * N.B. EVFILT_SIGNAL are also on p_klist, but by the
1282 * time we get here, all open file descriptors for this
1283 * process have been released, meaning that signal knotes
1284 * will have already been detached.
1285 *
1286 * We need to synchronize this with filt_procdetach().
1287 */
1288 KASSERT(kn->kn_fop == &proc_filtops);
1289 if ((kn->kn_status & KN_DETACHED) == 0) {
1290 kn->kn_status |= KN_DETACHED;
1291 SLIST_REMOVE_HEAD(&p->p_klist, kn_selnext);
1292 }
1293
1294 /*
1295 * Always activate the knote for NOTE_EXIT regardless
1296 * of whether or not the listener cares about it.
1297 * This matches historical behavior.
1298 */
1299 knote_activate_locked(kn);
1300 mutex_spin_exit(&kq->kq_lock);
1301 }
1302 }
1303
1304 #define FILT_TIMER_NOSCHED ((uintptr_t)-1)
1305
1306 static int
1307 filt_timercompute(struct kevent *kev, uintptr_t *tticksp)
1308 {
1309 struct timespec ts;
1310 uintptr_t tticks;
1311
1312 if (kev->fflags & ~(NOTE_TIMER_UNITMASK | NOTE_ABSTIME)) {
1313 return EINVAL;
1314 }
1315
1316 /*
1317 * Convert the event 'data' to a timespec, then convert the
1318 * timespec to callout ticks.
1319 */
1320 switch (kev->fflags & NOTE_TIMER_UNITMASK) {
1321 case NOTE_SECONDS:
1322 ts.tv_sec = kev->data;
1323 ts.tv_nsec = 0;
1324 break;
1325
1326 case NOTE_MSECONDS: /* == historical value 0 */
1327 ts.tv_sec = kev->data / 1000;
1328 ts.tv_nsec = (kev->data % 1000) * 1000000;
1329 break;
1330
1331 case NOTE_USECONDS:
1332 ts.tv_sec = kev->data / 1000000;
1333 ts.tv_nsec = (kev->data % 1000000) * 1000;
1334 break;
1335
1336 case NOTE_NSECONDS:
1337 ts.tv_sec = kev->data / 1000000000;
1338 ts.tv_nsec = kev->data % 1000000000;
1339 break;
1340
1341 default:
1342 return EINVAL;
1343 }
1344
1345 if (kev->fflags & NOTE_ABSTIME) {
1346 struct timespec deadline = ts;
1347
1348 /*
1349 * Get current time.
1350 *
1351 * XXX This is CLOCK_REALTIME. There is no way to
1352 * XXX specify CLOCK_MONOTONIC.
1353 */
1354 nanotime(&ts);
1355
1356 /* Absolute timers do not repeat. */
1357 kev->data = FILT_TIMER_NOSCHED;
1358
1359 /* If we're past the deadline, then the event will fire. */
1360 if (timespeccmp(&deadline, &ts, <=)) {
1361 tticks = FILT_TIMER_NOSCHED;
1362 goto out;
1363 }
1364
1365 /* Calculate how much time is left. */
1366 timespecsub(&deadline, &ts, &ts);
1367 } else {
1368 /* EV_CLEAR automatically set for relative timers. */
1369 kev->flags |= EV_CLEAR;
1370 }
1371
1372 tticks = tstohz(&ts);
1373
1374 /* if the supplied value is under our resolution, use 1 tick */
1375 if (tticks == 0) {
1376 if (kev->data == 0)
1377 return EINVAL;
1378 tticks = 1;
1379 } else if (tticks > INT_MAX) {
1380 return EINVAL;
1381 }
1382
1383 if ((kev->flags & EV_ONESHOT) != 0) {
1384 /* Timer does not repeat. */
1385 kev->data = FILT_TIMER_NOSCHED;
1386 } else {
1387 KASSERT((uintptr_t)tticks != FILT_TIMER_NOSCHED);
1388 kev->data = tticks;
1389 }
1390
1391 out:
1392 *tticksp = tticks;
1393
1394 return 0;
1395 }
1396
1397 static void
1398 filt_timerexpire(void *knx)
1399 {
1400 struct knote *kn = knx;
1401 struct kqueue *kq = kn->kn_kq;
1402
1403 mutex_spin_enter(&kq->kq_lock);
1404 kn->kn_data++;
1405 knote_activate_locked(kn);
1406 if (kn->kn_sdata != FILT_TIMER_NOSCHED) {
1407 KASSERT(kn->kn_sdata > 0);
1408 KASSERT(kn->kn_sdata <= INT_MAX);
1409 callout_schedule((callout_t *)kn->kn_hook,
1410 (int)kn->kn_sdata);
1411 }
1412 mutex_spin_exit(&kq->kq_lock);
1413 }
1414
1415 static inline void
1416 filt_timerstart(struct knote *kn, uintptr_t tticks)
1417 {
1418 callout_t *calloutp = kn->kn_hook;
1419
1420 KASSERT(mutex_owned(&kn->kn_kq->kq_lock));
1421 KASSERT(!callout_pending(calloutp));
1422
1423 if (__predict_false(tticks == FILT_TIMER_NOSCHED)) {
1424 kn->kn_data = 1;
1425 } else {
1426 KASSERT(tticks <= INT_MAX);
1427 callout_reset(calloutp, (int)tticks, filt_timerexpire, kn);
1428 }
1429 }
1430
1431 static int
1432 filt_timerattach(struct knote *kn)
1433 {
1434 callout_t *calloutp;
1435 struct kqueue *kq;
1436 uintptr_t tticks;
1437 int error;
1438
1439 struct kevent kev = {
1440 .flags = kn->kn_flags,
1441 .fflags = kn->kn_sfflags,
1442 .data = kn->kn_sdata,
1443 };
1444
1445 error = filt_timercompute(&kev, &tticks);
1446 if (error) {
1447 return error;
1448 }
1449
1450 if (atomic_inc_uint_nv(&kq_ncallouts) >= kq_calloutmax ||
1451 (calloutp = kmem_alloc(sizeof(*calloutp), KM_NOSLEEP)) == NULL) {
1452 atomic_dec_uint(&kq_ncallouts);
1453 return ENOMEM;
1454 }
1455 callout_init(calloutp, CALLOUT_MPSAFE);
1456
1457 kq = kn->kn_kq;
1458 mutex_spin_enter(&kq->kq_lock);
1459
1460 kn->kn_sdata = kev.data;
1461 kn->kn_flags = kev.flags;
1462 KASSERT(kn->kn_sfflags == kev.fflags);
1463 kn->kn_hook = calloutp;
1464
1465 filt_timerstart(kn, tticks);
1466
1467 mutex_spin_exit(&kq->kq_lock);
1468
1469 return (0);
1470 }
1471
1472 static void
1473 filt_timerdetach(struct knote *kn)
1474 {
1475 callout_t *calloutp;
1476 struct kqueue *kq = kn->kn_kq;
1477
1478 /* prevent rescheduling when we expire */
1479 mutex_spin_enter(&kq->kq_lock);
1480 kn->kn_sdata = FILT_TIMER_NOSCHED;
1481 mutex_spin_exit(&kq->kq_lock);
1482
1483 calloutp = (callout_t *)kn->kn_hook;
1484
1485 /*
1486 * Attempt to stop the callout. This will block if it's
1487 * already running.
1488 */
1489 callout_halt(calloutp, NULL);
1490
1491 callout_destroy(calloutp);
1492 kmem_free(calloutp, sizeof(*calloutp));
1493 atomic_dec_uint(&kq_ncallouts);
1494 }
1495
1496 static int
1497 filt_timertouch(struct knote *kn, struct kevent *kev, long type)
1498 {
1499 struct kqueue *kq = kn->kn_kq;
1500 callout_t *calloutp;
1501 uintptr_t tticks;
1502 int error;
1503
1504 KASSERT(mutex_owned(&kq->kq_lock));
1505
1506 switch (type) {
1507 case EVENT_REGISTER:
1508 /* Only relevant for EV_ADD. */
1509 if ((kev->flags & EV_ADD) == 0) {
1510 return 0;
1511 }
1512
1513 /*
1514 * Stop the timer, under the assumption that if
1515 * an application is re-configuring the timer,
1516 * they no longer care about the old one. We
1517 * can safely drop the kq_lock while we wait
1518 * because fdp->fd_lock will be held throughout,
1519 * ensuring that no one can sneak in with an
1520 * EV_DELETE or close the kq.
1521 */
1522 KASSERT(mutex_owned(&kq->kq_fdp->fd_lock));
1523
1524 calloutp = kn->kn_hook;
1525 callout_halt(calloutp, &kq->kq_lock);
1526 KASSERT(mutex_owned(&kq->kq_lock));
1527 knote_deactivate_locked(kn);
1528 kn->kn_data = 0;
1529
1530 error = filt_timercompute(kev, &tticks);
1531 if (error) {
1532 return error;
1533 }
1534 kn->kn_sdata = kev->data;
1535 kn->kn_flags = kev->flags;
1536 kn->kn_sfflags = kev->fflags;
1537 filt_timerstart(kn, tticks);
1538 break;
1539
1540 case EVENT_PROCESS:
1541 *kev = kn->kn_kevent;
1542 break;
1543
1544 default:
1545 panic("%s: invalid type (%ld)", __func__, type);
1546 }
1547
1548 return 0;
1549 }
1550
1551 static int
1552 filt_timer(struct knote *kn, long hint)
1553 {
1554 struct kqueue *kq = kn->kn_kq;
1555 int rv;
1556
1557 mutex_spin_enter(&kq->kq_lock);
1558 rv = (kn->kn_data != 0);
1559 mutex_spin_exit(&kq->kq_lock);
1560
1561 return rv;
1562 }
1563
1564 static int
1565 filt_userattach(struct knote *kn)
1566 {
1567 struct kqueue *kq = kn->kn_kq;
1568
1569 /*
1570 * EVFILT_USER knotes are not attached to anything in the kernel.
1571 */
1572 mutex_spin_enter(&kq->kq_lock);
1573 kn->kn_hook = NULL;
1574 if (kn->kn_fflags & NOTE_TRIGGER)
1575 kn->kn_hookid = 1;
1576 else
1577 kn->kn_hookid = 0;
1578 mutex_spin_exit(&kq->kq_lock);
1579 return (0);
1580 }
1581
1582 static void
1583 filt_userdetach(struct knote *kn)
1584 {
1585
1586 /*
1587 * EVFILT_USER knotes are not attached to anything in the kernel.
1588 */
1589 }
1590
1591 static int
1592 filt_user(struct knote *kn, long hint)
1593 {
1594 struct kqueue *kq = kn->kn_kq;
1595 int hookid;
1596
1597 mutex_spin_enter(&kq->kq_lock);
1598 hookid = kn->kn_hookid;
1599 mutex_spin_exit(&kq->kq_lock);
1600
1601 return hookid;
1602 }
1603
1604 static int
1605 filt_usertouch(struct knote *kn, struct kevent *kev, long type)
1606 {
1607 int ffctrl;
1608
1609 KASSERT(mutex_owned(&kn->kn_kq->kq_lock));
1610
1611 switch (type) {
1612 case EVENT_REGISTER:
1613 if (kev->fflags & NOTE_TRIGGER)
1614 kn->kn_hookid = 1;
1615
1616 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
1617 kev->fflags &= NOTE_FFLAGSMASK;
1618 switch (ffctrl) {
1619 case NOTE_FFNOP:
1620 break;
1621
1622 case NOTE_FFAND:
1623 kn->kn_sfflags &= kev->fflags;
1624 break;
1625
1626 case NOTE_FFOR:
1627 kn->kn_sfflags |= kev->fflags;
1628 break;
1629
1630 case NOTE_FFCOPY:
1631 kn->kn_sfflags = kev->fflags;
1632 break;
1633
1634 default:
1635 /* XXX Return error? */
1636 break;
1637 }
1638 kn->kn_sdata = kev->data;
1639 if (kev->flags & EV_CLEAR) {
1640 kn->kn_hookid = 0;
1641 kn->kn_data = 0;
1642 kn->kn_fflags = 0;
1643 }
1644 break;
1645
1646 case EVENT_PROCESS:
1647 *kev = kn->kn_kevent;
1648 kev->fflags = kn->kn_sfflags;
1649 kev->data = kn->kn_sdata;
1650 if (kn->kn_flags & EV_CLEAR) {
1651 kn->kn_hookid = 0;
1652 kn->kn_data = 0;
1653 kn->kn_fflags = 0;
1654 }
1655 break;
1656
1657 default:
1658 panic("filt_usertouch() - invalid type (%ld)", type);
1659 break;
1660 }
1661
1662 return 0;
1663 }
1664
1665 /*
1666 * filt_seltrue:
1667 *
1668 * This filter "event" routine simulates seltrue().
1669 */
1670 int
1671 filt_seltrue(struct knote *kn, long hint)
1672 {
1673
1674 /*
1675 * We don't know how much data can be read/written,
1676 * but we know that it *can* be. This is about as
1677 * good as select/poll does as well.
1678 */
1679 kn->kn_data = 0;
1680 return (1);
1681 }
1682
1683 /*
1684 * This provides full kqfilter entry for device switch tables, which
1685 * has same effect as filter using filt_seltrue() as filter method.
1686 */
1687 static void
1688 filt_seltruedetach(struct knote *kn)
1689 {
1690 /* Nothing to do */
1691 }
1692
1693 const struct filterops seltrue_filtops = {
1694 .f_flags = FILTEROP_ISFD | FILTEROP_MPSAFE,
1695 .f_attach = NULL,
1696 .f_detach = filt_seltruedetach,
1697 .f_event = filt_seltrue,
1698 };
1699
1700 int
1701 seltrue_kqfilter(dev_t dev, struct knote *kn)
1702 {
1703 switch (kn->kn_filter) {
1704 case EVFILT_READ:
1705 case EVFILT_WRITE:
1706 kn->kn_fop = &seltrue_filtops;
1707 break;
1708 default:
1709 return (EINVAL);
1710 }
1711
1712 /* Nothing more to do */
1713 return (0);
1714 }
1715
1716 /*
1717 * kqueue(2) system call.
1718 */
1719 static int
1720 kqueue1(struct lwp *l, int flags, register_t *retval)
1721 {
1722 struct kqueue *kq;
1723 file_t *fp;
1724 int fd, error;
1725
1726 if ((error = fd_allocfile(&fp, &fd)) != 0)
1727 return error;
1728 fp->f_flag = FREAD | FWRITE | (flags & (FNONBLOCK|FNOSIGPIPE));
1729 fp->f_type = DTYPE_KQUEUE;
1730 fp->f_ops = &kqueueops;
1731 kq = kmem_zalloc(sizeof(*kq), KM_SLEEP);
1732 mutex_init(&kq->kq_lock, MUTEX_DEFAULT, IPL_SCHED);
1733 cv_init(&kq->kq_cv, "kqueue");
1734 selinit(&kq->kq_sel);
1735 TAILQ_INIT(&kq->kq_head);
1736 fp->f_kqueue = kq;
1737 *retval = fd;
1738 kq->kq_fdp = curlwp->l_fd;
1739 fd_set_exclose(l, fd, (flags & O_CLOEXEC) != 0);
1740 fd_affix(curproc, fp, fd);
1741 return error;
1742 }
1743
1744 /*
1745 * kqueue(2) system call.
1746 */
1747 int
1748 sys_kqueue(struct lwp *l, const void *v, register_t *retval)
1749 {
1750 return kqueue1(l, 0, retval);
1751 }
1752
1753 int
1754 sys_kqueue1(struct lwp *l, const struct sys_kqueue1_args *uap,
1755 register_t *retval)
1756 {
1757 /* {
1758 syscallarg(int) flags;
1759 } */
1760 return kqueue1(l, SCARG(uap, flags), retval);
1761 }
1762
1763 /*
1764 * kevent(2) system call.
1765 */
1766 int
1767 kevent_fetch_changes(void *ctx, const struct kevent *changelist,
1768 struct kevent *changes, size_t index, int n)
1769 {
1770
1771 return copyin(changelist + index, changes, n * sizeof(*changes));
1772 }
1773
1774 int
1775 kevent_put_events(void *ctx, struct kevent *events,
1776 struct kevent *eventlist, size_t index, int n)
1777 {
1778
1779 return copyout(events, eventlist + index, n * sizeof(*events));
1780 }
1781
1782 static const struct kevent_ops kevent_native_ops = {
1783 .keo_private = NULL,
1784 .keo_fetch_timeout = copyin,
1785 .keo_fetch_changes = kevent_fetch_changes,
1786 .keo_put_events = kevent_put_events,
1787 };
1788
1789 int
1790 sys___kevent100(struct lwp *l, const struct sys___kevent100_args *uap,
1791 register_t *retval)
1792 {
1793 /* {
1794 syscallarg(int) fd;
1795 syscallarg(const struct kevent *) changelist;
1796 syscallarg(size_t) nchanges;
1797 syscallarg(struct kevent *) eventlist;
1798 syscallarg(size_t) nevents;
1799 syscallarg(const struct timespec *) timeout;
1800 } */
1801
1802 return kevent1(retval, SCARG(uap, fd), SCARG(uap, changelist),
1803 SCARG(uap, nchanges), SCARG(uap, eventlist), SCARG(uap, nevents),
1804 SCARG(uap, timeout), &kevent_native_ops);
1805 }
1806
1807 int
1808 kevent1(register_t *retval, int fd,
1809 const struct kevent *changelist, size_t nchanges,
1810 struct kevent *eventlist, size_t nevents,
1811 const struct timespec *timeout,
1812 const struct kevent_ops *keops)
1813 {
1814 struct kevent *kevp;
1815 struct kqueue *kq;
1816 struct timespec ts;
1817 size_t i, n, ichange;
1818 int nerrors, error;
1819 struct kevent kevbuf[KQ_NEVENTS]; /* approx 300 bytes on 64-bit */
1820 file_t *fp;
1821
1822 /* check that we're dealing with a kq */
1823 fp = fd_getfile(fd);
1824 if (fp == NULL)
1825 return (EBADF);
1826
1827 if (fp->f_type != DTYPE_KQUEUE) {
1828 fd_putfile(fd);
1829 return (EBADF);
1830 }
1831
1832 if (timeout != NULL) {
1833 error = (*keops->keo_fetch_timeout)(timeout, &ts, sizeof(ts));
1834 if (error)
1835 goto done;
1836 timeout = &ts;
1837 }
1838
1839 kq = fp->f_kqueue;
1840 nerrors = 0;
1841 ichange = 0;
1842
1843 /* traverse list of events to register */
1844 while (nchanges > 0) {
1845 n = MIN(nchanges, __arraycount(kevbuf));
1846 error = (*keops->keo_fetch_changes)(keops->keo_private,
1847 changelist, kevbuf, ichange, n);
1848 if (error)
1849 goto done;
1850 for (i = 0; i < n; i++) {
1851 kevp = &kevbuf[i];
1852 kevp->flags &= ~EV_SYSFLAGS;
1853 /* register each knote */
1854 error = kqueue_register(kq, kevp);
1855 if (!error && !(kevp->flags & EV_RECEIPT))
1856 continue;
1857 if (nevents == 0)
1858 goto done;
1859 kevp->flags = EV_ERROR;
1860 kevp->data = error;
1861 error = (*keops->keo_put_events)
1862 (keops->keo_private, kevp,
1863 eventlist, nerrors, 1);
1864 if (error)
1865 goto done;
1866 nevents--;
1867 nerrors++;
1868 }
1869 nchanges -= n; /* update the results */
1870 ichange += n;
1871 }
1872 if (nerrors) {
1873 *retval = nerrors;
1874 error = 0;
1875 goto done;
1876 }
1877
1878 /* actually scan through the events */
1879 error = kqueue_scan(fp, nevents, eventlist, timeout, retval, keops,
1880 kevbuf, __arraycount(kevbuf));
1881 done:
1882 fd_putfile(fd);
1883 return (error);
1884 }
1885
1886 /*
1887 * Register a given kevent kev onto the kqueue
1888 */
1889 static int
1890 kqueue_register(struct kqueue *kq, struct kevent *kev)
1891 {
1892 struct kfilter *kfilter;
1893 filedesc_t *fdp;
1894 file_t *fp;
1895 fdfile_t *ff;
1896 struct knote *kn, *newkn;
1897 struct klist *list;
1898 int error, fd, rv;
1899
1900 fdp = kq->kq_fdp;
1901 fp = NULL;
1902 kn = NULL;
1903 error = 0;
1904 fd = 0;
1905
1906 newkn = knote_alloc(true);
1907
1908 rw_enter(&kqueue_filter_lock, RW_READER);
1909 kfilter = kfilter_byfilter(kev->filter);
1910 if (kfilter == NULL || kfilter->filtops == NULL) {
1911 /* filter not found nor implemented */
1912 rw_exit(&kqueue_filter_lock);
1913 knote_free(newkn);
1914 return (EINVAL);
1915 }
1916
1917 /* search if knote already exists */
1918 if (kfilter->filtops->f_flags & FILTEROP_ISFD) {
1919 /* monitoring a file descriptor */
1920 /* validate descriptor */
1921 if (kev->ident > INT_MAX
1922 || (fp = fd_getfile(fd = kev->ident)) == NULL) {
1923 rw_exit(&kqueue_filter_lock);
1924 knote_free(newkn);
1925 return EBADF;
1926 }
1927 mutex_enter(&fdp->fd_lock);
1928 ff = fdp->fd_dt->dt_ff[fd];
1929 if (ff->ff_refcnt & FR_CLOSING) {
1930 error = EBADF;
1931 goto doneunlock;
1932 }
1933 if (fd <= fdp->fd_lastkqfile) {
1934 SLIST_FOREACH(kn, &ff->ff_knlist, kn_link) {
1935 if (kq == kn->kn_kq &&
1936 kev->filter == kn->kn_filter)
1937 break;
1938 }
1939 }
1940 } else {
1941 /*
1942 * not monitoring a file descriptor, so
1943 * lookup knotes in internal hash table
1944 */
1945 mutex_enter(&fdp->fd_lock);
1946 if (fdp->fd_knhashmask != 0) {
1947 list = &fdp->fd_knhash[
1948 KN_HASH((u_long)kev->ident, fdp->fd_knhashmask)];
1949 SLIST_FOREACH(kn, list, kn_link) {
1950 if (kev->ident == kn->kn_id &&
1951 kq == kn->kn_kq &&
1952 kev->filter == kn->kn_filter)
1953 break;
1954 }
1955 }
1956 }
1957
1958 /* It's safe to test KQ_CLOSING while holding only the fd_lock. */
1959 KASSERT(mutex_owned(&fdp->fd_lock));
1960 KASSERT((kq->kq_count & KQ_CLOSING) == 0);
1961
1962 /*
1963 * kn now contains the matching knote, or NULL if no match
1964 */
1965 if (kn == NULL) {
1966 if (kev->flags & EV_ADD) {
1967 /* create new knote */
1968 kn = newkn;
1969 newkn = NULL;
1970 kn->kn_obj = fp;
1971 kn->kn_id = kev->ident;
1972 kn->kn_kq = kq;
1973 kn->kn_fop = kfilter->filtops;
1974 kn->kn_kfilter = kfilter;
1975 kn->kn_sfflags = kev->fflags;
1976 kn->kn_sdata = kev->data;
1977 kev->fflags = 0;
1978 kev->data = 0;
1979 kn->kn_kevent = *kev;
1980
1981 KASSERT(kn->kn_fop != NULL);
1982 /*
1983 * XXX Allow only known-safe users of f_touch.
1984 * XXX See filter_touch() for details.
1985 */
1986 if (kn->kn_fop->f_touch != NULL &&
1987 kn->kn_fop != &timer_filtops &&
1988 kn->kn_fop != &user_filtops) {
1989 error = ENOTSUP;
1990 goto fail_ev_add;
1991 }
1992
1993 /*
1994 * apply reference count to knote structure, and
1995 * do not release it at the end of this routine.
1996 */
1997 fp = NULL;
1998
1999 if (!(kn->kn_fop->f_flags & FILTEROP_ISFD)) {
2000 /*
2001 * If knote is not on an fd, store on
2002 * internal hash table.
2003 */
2004 if (fdp->fd_knhashmask == 0) {
2005 /* XXXAD can block with fd_lock held */
2006 fdp->fd_knhash = hashinit(KN_HASHSIZE,
2007 HASH_LIST, true,
2008 &fdp->fd_knhashmask);
2009 }
2010 list = &fdp->fd_knhash[KN_HASH(kn->kn_id,
2011 fdp->fd_knhashmask)];
2012 } else {
2013 /* Otherwise, knote is on an fd. */
2014 list = (struct klist *)
2015 &fdp->fd_dt->dt_ff[kn->kn_id]->ff_knlist;
2016 if ((int)kn->kn_id > fdp->fd_lastkqfile)
2017 fdp->fd_lastkqfile = kn->kn_id;
2018 }
2019 SLIST_INSERT_HEAD(list, kn, kn_link);
2020
2021 /*
2022 * N.B. kn->kn_fop may change as the result
2023 * of filter_attach()!
2024 */
2025 knote_foplock_enter(kn);
2026 error = filter_attach(kn);
2027 if (error != 0) {
2028 #ifdef DEBUG
2029 struct proc *p = curlwp->l_proc;
2030 const file_t *ft = kn->kn_obj;
2031 printf("%s: %s[%d]: event type %d not "
2032 "supported for file type %d/%s "
2033 "(error %d)\n", __func__,
2034 p->p_comm, p->p_pid,
2035 kn->kn_filter, ft ? ft->f_type : -1,
2036 ft ? ft->f_ops->fo_name : "?", error);
2037 #endif
2038
2039 fail_ev_add:
2040 /*
2041 * N.B. no need to check for this note to
2042 * be in-flux, since it was never visible
2043 * to the monitored object.
2044 *
2045 * knote_detach() drops fdp->fd_lock
2046 */
2047 knote_foplock_exit(kn);
2048 mutex_enter(&kq->kq_lock);
2049 KNOTE_WILLDETACH(kn);
2050 KASSERT(kn_in_flux(kn) == false);
2051 mutex_exit(&kq->kq_lock);
2052 knote_detach(kn, fdp, false);
2053 goto done;
2054 }
2055 atomic_inc_uint(&kfilter->refcnt);
2056 goto done_ev_add;
2057 } else {
2058 /* No matching knote and the EV_ADD flag is not set. */
2059 error = ENOENT;
2060 goto doneunlock;
2061 }
2062 }
2063
2064 if (kev->flags & EV_DELETE) {
2065 /*
2066 * Let the world know that this knote is about to go
2067 * away, and wait for it to settle if it's currently
2068 * in-flux.
2069 */
2070 mutex_spin_enter(&kq->kq_lock);
2071 if (kn->kn_status & KN_WILLDETACH) {
2072 /*
2073 * This knote is already on its way out,
2074 * so just be done.
2075 */
2076 mutex_spin_exit(&kq->kq_lock);
2077 goto doneunlock;
2078 }
2079 KNOTE_WILLDETACH(kn);
2080 if (kn_in_flux(kn)) {
2081 mutex_exit(&fdp->fd_lock);
2082 /*
2083 * It's safe for us to conclusively wait for
2084 * this knote to settle because we know we'll
2085 * be completing the detach.
2086 */
2087 kn_wait_flux(kn, true);
2088 KASSERT(kn_in_flux(kn) == false);
2089 mutex_spin_exit(&kq->kq_lock);
2090 mutex_enter(&fdp->fd_lock);
2091 } else {
2092 mutex_spin_exit(&kq->kq_lock);
2093 }
2094
2095 /* knote_detach() drops fdp->fd_lock */
2096 knote_detach(kn, fdp, true);
2097 goto done;
2098 }
2099
2100 /*
2101 * The user may change some filter values after the
2102 * initial EV_ADD, but doing so will not reset any
2103 * filter which have already been triggered.
2104 */
2105 knote_foplock_enter(kn);
2106 kn->kn_kevent.udata = kev->udata;
2107 KASSERT(kn->kn_fop != NULL);
2108 if (!(kn->kn_fop->f_flags & FILTEROP_ISFD) &&
2109 kn->kn_fop->f_touch != NULL) {
2110 mutex_spin_enter(&kq->kq_lock);
2111 error = filter_touch(kn, kev, EVENT_REGISTER);
2112 mutex_spin_exit(&kq->kq_lock);
2113 if (__predict_false(error != 0)) {
2114 /* Never a new knote (which would consume newkn). */
2115 KASSERT(newkn != NULL);
2116 knote_foplock_exit(kn);
2117 goto doneunlock;
2118 }
2119 } else {
2120 kn->kn_sfflags = kev->fflags;
2121 kn->kn_sdata = kev->data;
2122 }
2123
2124 /*
2125 * We can get here if we are trying to attach
2126 * an event to a file descriptor that does not
2127 * support events, and the attach routine is
2128 * broken and does not return an error.
2129 */
2130 done_ev_add:
2131 rv = filter_event(kn, 0, false);
2132 if (rv)
2133 knote_activate(kn);
2134
2135 knote_foplock_exit(kn);
2136
2137 /* disable knote */
2138 if ((kev->flags & EV_DISABLE)) {
2139 mutex_spin_enter(&kq->kq_lock);
2140 if ((kn->kn_status & KN_DISABLED) == 0)
2141 kn->kn_status |= KN_DISABLED;
2142 mutex_spin_exit(&kq->kq_lock);
2143 }
2144
2145 /* enable knote */
2146 if ((kev->flags & EV_ENABLE)) {
2147 knote_enqueue(kn);
2148 }
2149 doneunlock:
2150 mutex_exit(&fdp->fd_lock);
2151 done:
2152 rw_exit(&kqueue_filter_lock);
2153 if (newkn != NULL)
2154 knote_free(newkn);
2155 if (fp != NULL)
2156 fd_putfile(fd);
2157 return (error);
2158 }
2159
2160 #define KN_FMT(buf, kn) \
2161 (snprintb((buf), sizeof(buf), __KN_FLAG_BITS, (kn)->kn_status), buf)
2162
2163 #if defined(DDB)
2164 void
2165 kqueue_printit(struct kqueue *kq, bool full, void (*pr)(const char *, ...))
2166 {
2167 const struct knote *kn;
2168 u_int count;
2169 int nmarker;
2170 char buf[128];
2171
2172 count = 0;
2173 nmarker = 0;
2174
2175 (*pr)("kqueue %p (restart=%d count=%u):\n", kq,
2176 !!(kq->kq_count & KQ_RESTART), KQ_COUNT(kq));
2177 (*pr)(" Queued knotes:\n");
2178 TAILQ_FOREACH(kn, &kq->kq_head, kn_tqe) {
2179 if (kn->kn_status & KN_MARKER) {
2180 nmarker++;
2181 } else {
2182 count++;
2183 }
2184 (*pr)(" knote %p: kq=%p status=%s\n",
2185 kn, kn->kn_kq, KN_FMT(buf, kn));
2186 (*pr)(" id=0x%lx (%lu) filter=%d\n",
2187 (u_long)kn->kn_id, (u_long)kn->kn_id, kn->kn_filter);
2188 if (kn->kn_kq != kq) {
2189 (*pr)(" !!! kn->kn_kq != kq\n");
2190 }
2191 }
2192 if (count != KQ_COUNT(kq)) {
2193 (*pr)(" !!! count(%u) != KQ_COUNT(%u)\n",
2194 count, KQ_COUNT(kq));
2195 }
2196 }
2197 #endif /* DDB */
2198
2199 #if defined(DEBUG)
2200 static void
2201 kqueue_check(const char *func, size_t line, const struct kqueue *kq)
2202 {
2203 const struct knote *kn;
2204 u_int count;
2205 int nmarker;
2206 char buf[128];
2207
2208 KASSERT(mutex_owned(&kq->kq_lock));
2209
2210 count = 0;
2211 nmarker = 0;
2212 TAILQ_FOREACH(kn, &kq->kq_head, kn_tqe) {
2213 if ((kn->kn_status & (KN_MARKER | KN_QUEUED)) == 0) {
2214 panic("%s,%zu: kq=%p kn=%p !(MARKER|QUEUED) %s",
2215 func, line, kq, kn, KN_FMT(buf, kn));
2216 }
2217 if ((kn->kn_status & KN_MARKER) == 0) {
2218 if (kn->kn_kq != kq) {
2219 panic("%s,%zu: kq=%p kn(%p) != kn->kq(%p): %s",
2220 func, line, kq, kn, kn->kn_kq,
2221 KN_FMT(buf, kn));
2222 }
2223 if ((kn->kn_status & KN_ACTIVE) == 0) {
2224 panic("%s,%zu: kq=%p kn=%p: !ACTIVE %s",
2225 func, line, kq, kn, KN_FMT(buf, kn));
2226 }
2227 count++;
2228 if (count > KQ_COUNT(kq)) {
2229 panic("%s,%zu: kq=%p kq->kq_count(%u) != "
2230 "count(%d), nmarker=%d",
2231 func, line, kq, KQ_COUNT(kq), count,
2232 nmarker);
2233 }
2234 } else {
2235 nmarker++;
2236 }
2237 }
2238 }
2239 #define kq_check(a) kqueue_check(__func__, __LINE__, (a))
2240 #else /* defined(DEBUG) */
2241 #define kq_check(a) /* nothing */
2242 #endif /* defined(DEBUG) */
2243
2244 static void
2245 kqueue_restart(file_t *fp)
2246 {
2247 struct kqueue *kq = fp->f_kqueue;
2248 KASSERT(kq != NULL);
2249
2250 mutex_spin_enter(&kq->kq_lock);
2251 kq->kq_count |= KQ_RESTART;
2252 cv_broadcast(&kq->kq_cv);
2253 mutex_spin_exit(&kq->kq_lock);
2254 }
2255
2256 static int
2257 kqueue_fpathconf(struct file *fp, int name, register_t *retval)
2258 {
2259
2260 return EINVAL;
2261 }
2262
2263 /*
2264 * Scan through the list of events on fp (for a maximum of maxevents),
2265 * returning the results in to ulistp. Timeout is determined by tsp; if
2266 * NULL, wait indefinitely, if 0 valued, perform a poll, otherwise wait
2267 * as appropriate.
2268 */
2269 static int
2270 kqueue_scan(file_t *fp, size_t maxevents, struct kevent *ulistp,
2271 const struct timespec *tsp, register_t *retval,
2272 const struct kevent_ops *keops, struct kevent *kevbuf,
2273 size_t kevcnt)
2274 {
2275 struct kqueue *kq;
2276 struct kevent *kevp;
2277 struct timespec ats, sleepts;
2278 struct knote *kn, *marker;
2279 struct knote_impl morker;
2280 size_t count, nkev, nevents;
2281 int timeout, error, touch, rv, influx;
2282 filedesc_t *fdp;
2283
2284 fdp = curlwp->l_fd;
2285 kq = fp->f_kqueue;
2286 count = maxevents;
2287 nkev = nevents = error = 0;
2288 if (count == 0) {
2289 *retval = 0;
2290 return 0;
2291 }
2292
2293 if (tsp) { /* timeout supplied */
2294 ats = *tsp;
2295 if (inittimeleft(&ats, &sleepts) == -1) {
2296 *retval = maxevents;
2297 return EINVAL;
2298 }
2299 timeout = tstohz(&ats);
2300 if (timeout <= 0)
2301 timeout = -1; /* do poll */
2302 } else {
2303 /* no timeout, wait forever */
2304 timeout = 0;
2305 }
2306
2307 memset(&morker, 0, sizeof(morker));
2308 marker = &morker.ki_knote;
2309 marker->kn_kq = kq;
2310 marker->kn_status = KN_MARKER;
2311 mutex_spin_enter(&kq->kq_lock);
2312 retry:
2313 kevp = kevbuf;
2314 if (KQ_COUNT(kq) == 0) {
2315 if (timeout >= 0) {
2316 error = cv_timedwait_sig(&kq->kq_cv,
2317 &kq->kq_lock, timeout);
2318 if (error == 0) {
2319 if (KQ_COUNT(kq) == 0 &&
2320 (kq->kq_count & KQ_RESTART)) {
2321 /* return to clear file reference */
2322 error = ERESTART;
2323 } else if (tsp == NULL || (timeout =
2324 gettimeleft(&ats, &sleepts)) > 0) {
2325 goto retry;
2326 }
2327 } else {
2328 /* don't restart after signals... */
2329 if (error == ERESTART)
2330 error = EINTR;
2331 if (error == EWOULDBLOCK)
2332 error = 0;
2333 }
2334 }
2335 mutex_spin_exit(&kq->kq_lock);
2336 goto done;
2337 }
2338
2339 /* mark end of knote list */
2340 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
2341 influx = 0;
2342
2343 /*
2344 * Acquire the fdp->fd_lock interlock to avoid races with
2345 * file creation/destruction from other threads.
2346 */
2347 mutex_spin_exit(&kq->kq_lock);
2348 relock:
2349 mutex_enter(&fdp->fd_lock);
2350 mutex_spin_enter(&kq->kq_lock);
2351
2352 while (count != 0) {
2353 /*
2354 * Get next knote. We are guaranteed this will never
2355 * be NULL because of the marker we inserted above.
2356 */
2357 kn = TAILQ_FIRST(&kq->kq_head);
2358
2359 bool kn_is_other_marker =
2360 (kn->kn_status & KN_MARKER) != 0 && kn != marker;
2361 bool kn_is_detaching = (kn->kn_status & KN_WILLDETACH) != 0;
2362 bool kn_is_in_flux = kn_in_flux(kn);
2363
2364 /*
2365 * If we found a marker that's not ours, or this knote
2366 * is in a state of flux, then wait for everything to
2367 * settle down and go around again.
2368 */
2369 if (kn_is_other_marker || kn_is_detaching || kn_is_in_flux) {
2370 if (influx) {
2371 influx = 0;
2372 KQ_FLUX_WAKEUP(kq);
2373 }
2374 mutex_exit(&fdp->fd_lock);
2375 if (kn_is_other_marker || kn_is_in_flux) {
2376 KQ_FLUX_WAIT(kq);
2377 mutex_spin_exit(&kq->kq_lock);
2378 } else {
2379 /*
2380 * Detaching but not in-flux? Someone is
2381 * actively trying to finish the job; just
2382 * go around and try again.
2383 */
2384 KASSERT(kn_is_detaching);
2385 mutex_spin_exit(&kq->kq_lock);
2386 preempt_point();
2387 }
2388 goto relock;
2389 }
2390
2391 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2392 if (kn == marker) {
2393 /* it's our marker, stop */
2394 KQ_FLUX_WAKEUP(kq);
2395 if (count == maxevents) {
2396 mutex_exit(&fdp->fd_lock);
2397 goto retry;
2398 }
2399 break;
2400 }
2401 KASSERT((kn->kn_status & KN_BUSY) == 0);
2402
2403 kq_check(kq);
2404 kn->kn_status &= ~KN_QUEUED;
2405 kn->kn_status |= KN_BUSY;
2406 kq_check(kq);
2407 if (kn->kn_status & KN_DISABLED) {
2408 kn->kn_status &= ~KN_BUSY;
2409 kq->kq_count--;
2410 /* don't want disabled events */
2411 continue;
2412 }
2413 if ((kn->kn_flags & EV_ONESHOT) == 0) {
2414 mutex_spin_exit(&kq->kq_lock);
2415 KASSERT(mutex_owned(&fdp->fd_lock));
2416 knote_foplock_enter(kn);
2417 rv = filter_event(kn, 0, false);
2418 knote_foplock_exit(kn);
2419 mutex_spin_enter(&kq->kq_lock);
2420 /* Re-poll if note was re-enqueued. */
2421 if ((kn->kn_status & KN_QUEUED) != 0) {
2422 kn->kn_status &= ~KN_BUSY;
2423 /* Re-enqueue raised kq_count, lower it again */
2424 kq->kq_count--;
2425 influx = 1;
2426 continue;
2427 }
2428 if (rv == 0) {
2429 /*
2430 * non-ONESHOT event that hasn't triggered
2431 * again, so it will remain de-queued.
2432 */
2433 kn->kn_status &= ~(KN_ACTIVE|KN_BUSY);
2434 kq->kq_count--;
2435 influx = 1;
2436 continue;
2437 }
2438 } else {
2439 /*
2440 * Must NOT drop kq_lock until we can do
2441 * the KNOTE_WILLDETACH() below.
2442 */
2443 }
2444 KASSERT(kn->kn_fop != NULL);
2445 touch = (!(kn->kn_fop->f_flags & FILTEROP_ISFD) &&
2446 kn->kn_fop->f_touch != NULL);
2447 /* XXXAD should be got from f_event if !oneshot. */
2448 KASSERT((kn->kn_status & KN_WILLDETACH) == 0);
2449 if (touch) {
2450 (void)filter_touch(kn, kevp, EVENT_PROCESS);
2451 } else {
2452 *kevp = kn->kn_kevent;
2453 }
2454 kevp++;
2455 nkev++;
2456 influx = 1;
2457 if (kn->kn_flags & EV_ONESHOT) {
2458 /* delete ONESHOT events after retrieval */
2459 KNOTE_WILLDETACH(kn);
2460 kn->kn_status &= ~KN_BUSY;
2461 kq->kq_count--;
2462 KASSERT(kn_in_flux(kn) == false);
2463 KASSERT((kn->kn_status & KN_WILLDETACH) != 0);
2464 KASSERT(kn->kn_kevent.udata == curlwp);
2465 mutex_spin_exit(&kq->kq_lock);
2466 knote_detach(kn, fdp, true);
2467 mutex_enter(&fdp->fd_lock);
2468 mutex_spin_enter(&kq->kq_lock);
2469 } else if (kn->kn_flags & EV_CLEAR) {
2470 /* clear state after retrieval */
2471 kn->kn_data = 0;
2472 kn->kn_fflags = 0;
2473 /*
2474 * Manually clear knotes who weren't
2475 * 'touch'ed.
2476 */
2477 if (touch == 0) {
2478 kn->kn_data = 0;
2479 kn->kn_fflags = 0;
2480 }
2481 kn->kn_status &= ~(KN_ACTIVE|KN_BUSY);
2482 kq->kq_count--;
2483 } else if (kn->kn_flags & EV_DISPATCH) {
2484 kn->kn_status |= KN_DISABLED;
2485 kn->kn_status &= ~(KN_ACTIVE|KN_BUSY);
2486 kq->kq_count--;
2487 } else {
2488 /* add event back on list */
2489 kq_check(kq);
2490 kn->kn_status |= KN_QUEUED;
2491 kn->kn_status &= ~KN_BUSY;
2492 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2493 kq_check(kq);
2494 }
2495
2496 if (nkev == kevcnt) {
2497 /* do copyouts in kevcnt chunks */
2498 influx = 0;
2499 KQ_FLUX_WAKEUP(kq);
2500 mutex_spin_exit(&kq->kq_lock);
2501 mutex_exit(&fdp->fd_lock);
2502 error = (*keops->keo_put_events)
2503 (keops->keo_private,
2504 kevbuf, ulistp, nevents, nkev);
2505 mutex_enter(&fdp->fd_lock);
2506 mutex_spin_enter(&kq->kq_lock);
2507 nevents += nkev;
2508 nkev = 0;
2509 kevp = kevbuf;
2510 }
2511 count--;
2512 if (error != 0 || count == 0) {
2513 /* remove marker */
2514 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
2515 break;
2516 }
2517 }
2518 KQ_FLUX_WAKEUP(kq);
2519 mutex_spin_exit(&kq->kq_lock);
2520 mutex_exit(&fdp->fd_lock);
2521
2522 done:
2523 if (nkev != 0) {
2524 /* copyout remaining events */
2525 error = (*keops->keo_put_events)(keops->keo_private,
2526 kevbuf, ulistp, nevents, nkev);
2527 }
2528 *retval = maxevents - count;
2529
2530 return error;
2531 }
2532
2533 /*
2534 * fileops ioctl method for a kqueue descriptor.
2535 *
2536 * Two ioctls are currently supported. They both use struct kfilter_mapping:
2537 * KFILTER_BYNAME find name for filter, and return result in
2538 * name, which is of size len.
2539 * KFILTER_BYFILTER find filter for name. len is ignored.
2540 */
2541 /*ARGSUSED*/
2542 static int
2543 kqueue_ioctl(file_t *fp, u_long com, void *data)
2544 {
2545 struct kfilter_mapping *km;
2546 const struct kfilter *kfilter;
2547 char *name;
2548 int error;
2549
2550 km = data;
2551 error = 0;
2552 name = kmem_alloc(KFILTER_MAXNAME, KM_SLEEP);
2553
2554 switch (com) {
2555 case KFILTER_BYFILTER: /* convert filter -> name */
2556 rw_enter(&kqueue_filter_lock, RW_READER);
2557 kfilter = kfilter_byfilter(km->filter);
2558 if (kfilter != NULL) {
2559 strlcpy(name, kfilter->name, KFILTER_MAXNAME);
2560 rw_exit(&kqueue_filter_lock);
2561 error = copyoutstr(name, km->name, km->len, NULL);
2562 } else {
2563 rw_exit(&kqueue_filter_lock);
2564 error = ENOENT;
2565 }
2566 break;
2567
2568 case KFILTER_BYNAME: /* convert name -> filter */
2569 error = copyinstr(km->name, name, KFILTER_MAXNAME, NULL);
2570 if (error) {
2571 break;
2572 }
2573 rw_enter(&kqueue_filter_lock, RW_READER);
2574 kfilter = kfilter_byname(name);
2575 if (kfilter != NULL)
2576 km->filter = kfilter->filter;
2577 else
2578 error = ENOENT;
2579 rw_exit(&kqueue_filter_lock);
2580 break;
2581
2582 default:
2583 error = ENOTTY;
2584 break;
2585
2586 }
2587 kmem_free(name, KFILTER_MAXNAME);
2588 return (error);
2589 }
2590
2591 /*
2592 * fileops fcntl method for a kqueue descriptor.
2593 */
2594 static int
2595 kqueue_fcntl(file_t *fp, u_int com, void *data)
2596 {
2597
2598 return (ENOTTY);
2599 }
2600
2601 /*
2602 * fileops poll method for a kqueue descriptor.
2603 * Determine if kqueue has events pending.
2604 */
2605 static int
2606 kqueue_poll(file_t *fp, int events)
2607 {
2608 struct kqueue *kq;
2609 int revents;
2610
2611 kq = fp->f_kqueue;
2612
2613 revents = 0;
2614 if (events & (POLLIN | POLLRDNORM)) {
2615 mutex_spin_enter(&kq->kq_lock);
2616 if (KQ_COUNT(kq) != 0) {
2617 revents |= events & (POLLIN | POLLRDNORM);
2618 } else {
2619 selrecord(curlwp, &kq->kq_sel);
2620 }
2621 kq_check(kq);
2622 mutex_spin_exit(&kq->kq_lock);
2623 }
2624
2625 return revents;
2626 }
2627
2628 /*
2629 * fileops stat method for a kqueue descriptor.
2630 * Returns dummy info, with st_size being number of events pending.
2631 */
2632 static int
2633 kqueue_stat(file_t *fp, struct stat *st)
2634 {
2635 struct kqueue *kq;
2636
2637 kq = fp->f_kqueue;
2638
2639 memset(st, 0, sizeof(*st));
2640 st->st_size = KQ_COUNT(kq);
2641 st->st_blksize = sizeof(struct kevent);
2642 st->st_mode = S_IFIFO | S_IRUSR | S_IWUSR;
2643 st->st_blocks = 1;
2644 st->st_uid = kauth_cred_geteuid(fp->f_cred);
2645 st->st_gid = kauth_cred_getegid(fp->f_cred);
2646
2647 return 0;
2648 }
2649
2650 static void
2651 kqueue_doclose(struct kqueue *kq, struct klist *list, int fd)
2652 {
2653 struct knote *kn;
2654 filedesc_t *fdp;
2655
2656 fdp = kq->kq_fdp;
2657
2658 KASSERT(mutex_owned(&fdp->fd_lock));
2659
2660 again:
2661 for (kn = SLIST_FIRST(list); kn != NULL;) {
2662 if (kq != kn->kn_kq) {
2663 kn = SLIST_NEXT(kn, kn_link);
2664 continue;
2665 }
2666 if (knote_detach_quiesce(kn)) {
2667 mutex_enter(&fdp->fd_lock);
2668 goto again;
2669 }
2670 knote_detach(kn, fdp, true);
2671 mutex_enter(&fdp->fd_lock);
2672 kn = SLIST_FIRST(list);
2673 }
2674 }
2675
2676 /*
2677 * fileops close method for a kqueue descriptor.
2678 */
2679 static int
2680 kqueue_close(file_t *fp)
2681 {
2682 struct kqueue *kq;
2683 filedesc_t *fdp;
2684 fdfile_t *ff;
2685 int i;
2686
2687 kq = fp->f_kqueue;
2688 fp->f_kqueue = NULL;
2689 fp->f_type = 0;
2690 fdp = curlwp->l_fd;
2691
2692 KASSERT(kq->kq_fdp == fdp);
2693
2694 mutex_enter(&fdp->fd_lock);
2695
2696 /*
2697 * We're doing to drop the fd_lock multiple times while
2698 * we detach knotes. During this time, attempts to register
2699 * knotes via the back door (e.g. knote_proc_fork_track())
2700 * need to fail, lest they sneak in to attach a knote after
2701 * we've already drained the list it's destined for.
2702 *
2703 * We must acquire kq_lock here to set KQ_CLOSING (to serialize
2704 * with other code paths that modify kq_count without holding
2705 * the fd_lock), but once this bit is set, it's only safe to
2706 * test it while holding the fd_lock, and holding kq_lock while
2707 * doing so is not necessary.
2708 */
2709 mutex_enter(&kq->kq_lock);
2710 kq->kq_count |= KQ_CLOSING;
2711 mutex_exit(&kq->kq_lock);
2712
2713 for (i = 0; i <= fdp->fd_lastkqfile; i++) {
2714 if ((ff = fdp->fd_dt->dt_ff[i]) == NULL)
2715 continue;
2716 kqueue_doclose(kq, (struct klist *)&ff->ff_knlist, i);
2717 }
2718 if (fdp->fd_knhashmask != 0) {
2719 for (i = 0; i < fdp->fd_knhashmask + 1; i++) {
2720 kqueue_doclose(kq, &fdp->fd_knhash[i], -1);
2721 }
2722 }
2723
2724 mutex_exit(&fdp->fd_lock);
2725
2726 #if defined(DEBUG)
2727 mutex_enter(&kq->kq_lock);
2728 kq_check(kq);
2729 mutex_exit(&kq->kq_lock);
2730 #endif /* DEBUG */
2731 KASSERT(TAILQ_EMPTY(&kq->kq_head));
2732 KASSERT(KQ_COUNT(kq) == 0);
2733 mutex_destroy(&kq->kq_lock);
2734 cv_destroy(&kq->kq_cv);
2735 seldestroy(&kq->kq_sel);
2736 kmem_free(kq, sizeof(*kq));
2737
2738 return (0);
2739 }
2740
2741 /*
2742 * struct fileops kqfilter method for a kqueue descriptor.
2743 * Event triggered when monitored kqueue changes.
2744 */
2745 static int
2746 kqueue_kqfilter(file_t *fp, struct knote *kn)
2747 {
2748 struct kqueue *kq;
2749
2750 kq = ((file_t *)kn->kn_obj)->f_kqueue;
2751
2752 KASSERT(fp == kn->kn_obj);
2753
2754 if (kn->kn_filter != EVFILT_READ)
2755 return EINVAL;
2756
2757 kn->kn_fop = &kqread_filtops;
2758 mutex_enter(&kq->kq_lock);
2759 selrecord_knote(&kq->kq_sel, kn);
2760 mutex_exit(&kq->kq_lock);
2761
2762 return 0;
2763 }
2764
2765
2766 /*
2767 * Walk down a list of knotes, activating them if their event has
2768 * triggered. The caller's object lock (e.g. device driver lock)
2769 * must be held.
2770 */
2771 void
2772 knote(struct klist *list, long hint)
2773 {
2774 struct knote *kn, *tmpkn;
2775
2776 SLIST_FOREACH_SAFE(kn, list, kn_selnext, tmpkn) {
2777 /*
2778 * We assume here that the backing object's lock is
2779 * already held if we're traversing the klist, and
2780 * so acquiring the knote foplock would create a
2781 * deadlock scenario. But we also know that the klist
2782 * won't disappear on us while we're here, so not
2783 * acquiring it is safe.
2784 */
2785 if (filter_event(kn, hint, true)) {
2786 knote_activate(kn);
2787 }
2788 }
2789 }
2790
2791 /*
2792 * Remove all knotes referencing a specified fd
2793 */
2794 void
2795 knote_fdclose(int fd)
2796 {
2797 struct klist *list;
2798 struct knote *kn;
2799 filedesc_t *fdp;
2800
2801 again:
2802 fdp = curlwp->l_fd;
2803 mutex_enter(&fdp->fd_lock);
2804 list = (struct klist *)&fdp->fd_dt->dt_ff[fd]->ff_knlist;
2805 while ((kn = SLIST_FIRST(list)) != NULL) {
2806 if (knote_detach_quiesce(kn)) {
2807 goto again;
2808 }
2809 knote_detach(kn, fdp, true);
2810 mutex_enter(&fdp->fd_lock);
2811 }
2812 mutex_exit(&fdp->fd_lock);
2813 }
2814
2815 /*
2816 * Drop knote. Called with fdp->fd_lock held, and will drop before
2817 * returning.
2818 */
2819 static void
2820 knote_detach(struct knote *kn, filedesc_t *fdp, bool dofop)
2821 {
2822 struct klist *list;
2823 struct kqueue *kq;
2824
2825 kq = kn->kn_kq;
2826
2827 KASSERT((kn->kn_status & KN_MARKER) == 0);
2828 KASSERT((kn->kn_status & KN_WILLDETACH) != 0);
2829 KASSERT(kn->kn_fop != NULL);
2830 KASSERT(mutex_owned(&fdp->fd_lock));
2831
2832 /* Remove from monitored object. */
2833 if (dofop) {
2834 knote_foplock_enter(kn);
2835 filter_detach(kn);
2836 knote_foplock_exit(kn);
2837 }
2838
2839 /* Remove from descriptor table. */
2840 if (kn->kn_fop->f_flags & FILTEROP_ISFD)
2841 list = (struct klist *)&fdp->fd_dt->dt_ff[kn->kn_id]->ff_knlist;
2842 else
2843 list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
2844
2845 SLIST_REMOVE(list, kn, knote, kn_link);
2846
2847 /* Remove from kqueue. */
2848 again:
2849 mutex_spin_enter(&kq->kq_lock);
2850 KASSERT(kn_in_flux(kn) == false);
2851 if ((kn->kn_status & KN_QUEUED) != 0) {
2852 kq_check(kq);
2853 KASSERT(KQ_COUNT(kq) != 0);
2854 kq->kq_count--;
2855 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2856 kn->kn_status &= ~KN_QUEUED;
2857 kq_check(kq);
2858 } else if (kn->kn_status & KN_BUSY) {
2859 mutex_spin_exit(&kq->kq_lock);
2860 goto again;
2861 }
2862 mutex_spin_exit(&kq->kq_lock);
2863
2864 mutex_exit(&fdp->fd_lock);
2865 if (kn->kn_fop->f_flags & FILTEROP_ISFD)
2866 fd_putfile(kn->kn_id);
2867 atomic_dec_uint(&kn->kn_kfilter->refcnt);
2868 knote_free(kn);
2869 }
2870
2871 /*
2872 * Queue new event for knote.
2873 */
2874 static void
2875 knote_enqueue(struct knote *kn)
2876 {
2877 struct kqueue *kq;
2878
2879 KASSERT((kn->kn_status & KN_MARKER) == 0);
2880
2881 kq = kn->kn_kq;
2882
2883 mutex_spin_enter(&kq->kq_lock);
2884 if (__predict_false(kn->kn_status & KN_WILLDETACH)) {
2885 /* Don't bother enqueueing a dying knote. */
2886 goto out;
2887 }
2888 if ((kn->kn_status & KN_DISABLED) != 0) {
2889 kn->kn_status &= ~KN_DISABLED;
2890 }
2891 if ((kn->kn_status & (KN_ACTIVE | KN_QUEUED)) == KN_ACTIVE) {
2892 kq_check(kq);
2893 kn->kn_status |= KN_QUEUED;
2894 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2895 KASSERT(KQ_COUNT(kq) < KQ_MAXCOUNT);
2896 kq->kq_count++;
2897 kq_check(kq);
2898 cv_broadcast(&kq->kq_cv);
2899 selnotify(&kq->kq_sel, 0, NOTE_SUBMIT);
2900 }
2901 out:
2902 mutex_spin_exit(&kq->kq_lock);
2903 }
2904 /*
2905 * Queue new event for knote.
2906 */
2907 static void
2908 knote_activate_locked(struct knote *kn)
2909 {
2910 struct kqueue *kq;
2911
2912 KASSERT((kn->kn_status & KN_MARKER) == 0);
2913
2914 kq = kn->kn_kq;
2915
2916 if (__predict_false(kn->kn_status & KN_WILLDETACH)) {
2917 /* Don't bother enqueueing a dying knote. */
2918 return;
2919 }
2920 kn->kn_status |= KN_ACTIVE;
2921 if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) {
2922 kq_check(kq);
2923 kn->kn_status |= KN_QUEUED;
2924 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2925 KASSERT(KQ_COUNT(kq) < KQ_MAXCOUNT);
2926 kq->kq_count++;
2927 kq_check(kq);
2928 cv_broadcast(&kq->kq_cv);
2929 selnotify(&kq->kq_sel, 0, NOTE_SUBMIT);
2930 }
2931 }
2932
2933 static void
2934 knote_activate(struct knote *kn)
2935 {
2936 struct kqueue *kq = kn->kn_kq;
2937
2938 mutex_spin_enter(&kq->kq_lock);
2939 knote_activate_locked(kn);
2940 mutex_spin_exit(&kq->kq_lock);
2941 }
2942
2943 static void
2944 knote_deactivate_locked(struct knote *kn)
2945 {
2946 struct kqueue *kq = kn->kn_kq;
2947
2948 if (kn->kn_status & KN_QUEUED) {
2949 kq_check(kq);
2950 kn->kn_status &= ~KN_QUEUED;
2951 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2952 KASSERT(KQ_COUNT(kq) > 0);
2953 kq->kq_count--;
2954 kq_check(kq);
2955 }
2956 kn->kn_status &= ~KN_ACTIVE;
2957 }
2958
2959 /*
2960 * Set EV_EOF on the specified knote. Also allows additional
2961 * EV_* flags to be set (e.g. EV_ONESHOT).
2962 */
2963 void
2964 knote_set_eof(struct knote *kn, uint32_t flags)
2965 {
2966 struct kqueue *kq = kn->kn_kq;
2967
2968 mutex_spin_enter(&kq->kq_lock);
2969 kn->kn_flags |= EV_EOF | flags;
2970 mutex_spin_exit(&kq->kq_lock);
2971 }
2972
2973 /*
2974 * Clear EV_EOF on the specified knote.
2975 */
2976 void
2977 knote_clear_eof(struct knote *kn)
2978 {
2979 struct kqueue *kq = kn->kn_kq;
2980
2981 mutex_spin_enter(&kq->kq_lock);
2982 kn->kn_flags &= ~EV_EOF;
2983 mutex_spin_exit(&kq->kq_lock);
2984 }
2985
2986 /*
2987 * Initialize a klist.
2988 */
2989 void
2990 klist_init(struct klist *list)
2991 {
2992 SLIST_INIT(list);
2993 }
2994
2995 /*
2996 * Finalize a klist.
2997 */
2998 void
2999 klist_fini(struct klist *list)
3000 {
3001 struct knote *kn;
3002
3003 /*
3004 * Neuter all existing knotes on the klist because the list is
3005 * being destroyed. The caller has guaranteed that no additional
3006 * knotes will be added to the list, that the backing object's
3007 * locks are not held (otherwise there is a locking order issue
3008 * with acquiring the knote foplock ), and that we can traverse
3009 * the list safely in this state.
3010 */
3011 SLIST_FOREACH(kn, list, kn_selnext) {
3012 knote_foplock_enter(kn);
3013 KASSERT(kn->kn_fop != NULL);
3014 if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
3015 kn->kn_fop = &nop_fd_filtops;
3016 } else {
3017 kn->kn_fop = &nop_filtops;
3018 }
3019 knote_foplock_exit(kn);
3020 }
3021 }
3022
3023 /*
3024 * Insert a knote into a klist.
3025 */
3026 void
3027 klist_insert(struct klist *list, struct knote *kn)
3028 {
3029 SLIST_INSERT_HEAD(list, kn, kn_selnext);
3030 }
3031
3032 /*
3033 * Remove a knote from a klist. Returns true if the last
3034 * knote was removed and the list is now empty.
3035 */
3036 bool
3037 klist_remove(struct klist *list, struct knote *kn)
3038 {
3039 SLIST_REMOVE(list, kn, knote, kn_selnext);
3040 return SLIST_EMPTY(list);
3041 }
3042