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