xref: /freebsd/sys/kern/kern_event.c (revision d912068ad826e457f0c0203d1cad02df81c35bbc)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon@FreeBSD.org>
5  * Copyright 2004 John-Mark Gurney <jmg@FreeBSD.org>
6  * Copyright (c) 2009 Apple, Inc.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include "opt_ktrace.h"
35 #include "opt_kqueue.h"
36 
37 #ifdef COMPAT_FREEBSD11
38 #define	_WANT_FREEBSD11_KEVENT
39 #endif
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/capsicum.h>
44 #include <sys/kernel.h>
45 #include <sys/limits.h>
46 #include <sys/lock.h>
47 #include <sys/mutex.h>
48 #include <sys/rwlock.h>
49 #include <sys/proc.h>
50 #include <sys/malloc.h>
51 #include <sys/unistd.h>
52 #include <sys/file.h>
53 #include <sys/filedesc.h>
54 #include <sys/filio.h>
55 #include <sys/fcntl.h>
56 #include <sys/kthread.h>
57 #include <sys/selinfo.h>
58 #include <sys/queue.h>
59 #include <sys/event.h>
60 #include <sys/eventvar.h>
61 #include <sys/poll.h>
62 #include <sys/protosw.h>
63 #include <sys/resourcevar.h>
64 #include <sys/sigio.h>
65 #include <sys/signalvar.h>
66 #include <sys/socket.h>
67 #include <sys/socketvar.h>
68 #include <sys/stat.h>
69 #include <sys/sysctl.h>
70 #include <sys/sysproto.h>
71 #include <sys/syscallsubr.h>
72 #include <sys/taskqueue.h>
73 #include <sys/uio.h>
74 #include <sys/user.h>
75 #ifdef KTRACE
76 #include <sys/ktrace.h>
77 #endif
78 #include <machine/atomic.h>
79 
80 #include <vm/uma.h>
81 
82 static MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
83 
84 /*
85  * This lock is used if multiple kq locks are required.  This possibly
86  * should be made into a per proc lock.
87  */
88 static struct mtx	kq_global;
89 MTX_SYSINIT(kq_global, &kq_global, "kqueue order", MTX_DEF);
90 #define KQ_GLOBAL_LOCK(lck, haslck)	do {	\
91 	if (!haslck)				\
92 		mtx_lock(lck);			\
93 	haslck = 1;				\
94 } while (0)
95 #define KQ_GLOBAL_UNLOCK(lck, haslck)	do {	\
96 	if (haslck)				\
97 		mtx_unlock(lck);			\
98 	haslck = 0;				\
99 } while (0)
100 
101 TASKQUEUE_DEFINE_THREAD(kqueue_ctx);
102 
103 static int	kevent_copyout(void *arg, struct kevent *kevp, int count);
104 static int	kevent_copyin(void *arg, struct kevent *kevp, int count);
105 static int	kqueue_register(struct kqueue *kq, struct kevent *kev,
106 		    struct thread *td, int mflag);
107 static int	kqueue_acquire(struct file *fp, struct kqueue **kqp);
108 static void	kqueue_release(struct kqueue *kq, int locked);
109 static void	kqueue_destroy(struct kqueue *kq);
110 static void	kqueue_drain(struct kqueue *kq, struct thread *td);
111 static int	kqueue_expand(struct kqueue *kq, struct filterops *fops,
112 		    uintptr_t ident, int mflag);
113 static void	kqueue_task(void *arg, int pending);
114 static int	kqueue_scan(struct kqueue *kq, int maxevents,
115 		    struct kevent_copyops *k_ops,
116 		    const struct timespec *timeout,
117 		    struct kevent *keva, struct thread *td);
118 static void 	kqueue_wakeup(struct kqueue *kq);
119 static struct filterops *kqueue_fo_find(int filt);
120 static void	kqueue_fo_release(int filt);
121 struct g_kevent_args;
122 static int	kern_kevent_generic(struct thread *td,
123 		    struct g_kevent_args *uap,
124 		    struct kevent_copyops *k_ops, const char *struct_name);
125 
126 static fo_ioctl_t	kqueue_ioctl;
127 static fo_poll_t	kqueue_poll;
128 static fo_kqfilter_t	kqueue_kqfilter;
129 static fo_stat_t	kqueue_stat;
130 static fo_close_t	kqueue_close;
131 static fo_fill_kinfo_t	kqueue_fill_kinfo;
132 
133 static struct fileops kqueueops = {
134 	.fo_read = invfo_rdwr,
135 	.fo_write = invfo_rdwr,
136 	.fo_truncate = invfo_truncate,
137 	.fo_ioctl = kqueue_ioctl,
138 	.fo_poll = kqueue_poll,
139 	.fo_kqfilter = kqueue_kqfilter,
140 	.fo_stat = kqueue_stat,
141 	.fo_close = kqueue_close,
142 	.fo_chmod = invfo_chmod,
143 	.fo_chown = invfo_chown,
144 	.fo_sendfile = invfo_sendfile,
145 	.fo_fill_kinfo = kqueue_fill_kinfo,
146 };
147 
148 static int 	knote_attach(struct knote *kn, struct kqueue *kq);
149 static void 	knote_drop(struct knote *kn, struct thread *td);
150 static void 	knote_drop_detached(struct knote *kn, struct thread *td);
151 static void 	knote_enqueue(struct knote *kn);
152 static void 	knote_dequeue(struct knote *kn);
153 static void 	knote_init(void);
154 static struct 	knote *knote_alloc(int mflag);
155 static void 	knote_free(struct knote *kn);
156 
157 static void	filt_kqdetach(struct knote *kn);
158 static int	filt_kqueue(struct knote *kn, long hint);
159 static int	filt_procattach(struct knote *kn);
160 static void	filt_procdetach(struct knote *kn);
161 static int	filt_proc(struct knote *kn, long hint);
162 static int	filt_fileattach(struct knote *kn);
163 static void	filt_timerexpire(void *knx);
164 static void	filt_timerexpire_l(struct knote *kn, bool proc_locked);
165 static int	filt_timerattach(struct knote *kn);
166 static void	filt_timerdetach(struct knote *kn);
167 static void	filt_timerstart(struct knote *kn, sbintime_t to);
168 static void	filt_timertouch(struct knote *kn, struct kevent *kev,
169 		    u_long type);
170 static int	filt_timervalidate(struct knote *kn, sbintime_t *to);
171 static int	filt_timer(struct knote *kn, long hint);
172 static int	filt_userattach(struct knote *kn);
173 static void	filt_userdetach(struct knote *kn);
174 static int	filt_user(struct knote *kn, long hint);
175 static void	filt_usertouch(struct knote *kn, struct kevent *kev,
176 		    u_long type);
177 
178 static struct filterops file_filtops = {
179 	.f_isfd = 1,
180 	.f_attach = filt_fileattach,
181 };
182 static struct filterops kqread_filtops = {
183 	.f_isfd = 1,
184 	.f_detach = filt_kqdetach,
185 	.f_event = filt_kqueue,
186 };
187 /* XXX - move to kern_proc.c?  */
188 static struct filterops proc_filtops = {
189 	.f_isfd = 0,
190 	.f_attach = filt_procattach,
191 	.f_detach = filt_procdetach,
192 	.f_event = filt_proc,
193 };
194 static struct filterops timer_filtops = {
195 	.f_isfd = 0,
196 	.f_attach = filt_timerattach,
197 	.f_detach = filt_timerdetach,
198 	.f_event = filt_timer,
199 	.f_touch = filt_timertouch,
200 };
201 static struct filterops user_filtops = {
202 	.f_attach = filt_userattach,
203 	.f_detach = filt_userdetach,
204 	.f_event = filt_user,
205 	.f_touch = filt_usertouch,
206 };
207 
208 static uma_zone_t	knote_zone;
209 static unsigned int	kq_ncallouts = 0;
210 static unsigned int 	kq_calloutmax = 4 * 1024;
211 SYSCTL_UINT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
212     &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
213 
214 /* XXX - ensure not influx ? */
215 #define KNOTE_ACTIVATE(kn, islock) do { 				\
216 	if ((islock))							\
217 		mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED);		\
218 	else								\
219 		KQ_LOCK((kn)->kn_kq);					\
220 	(kn)->kn_status |= KN_ACTIVE;					\
221 	if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0)		\
222 		knote_enqueue((kn));					\
223 	if (!(islock))							\
224 		KQ_UNLOCK((kn)->kn_kq);					\
225 } while (0)
226 #define KQ_LOCK(kq) do {						\
227 	mtx_lock(&(kq)->kq_lock);					\
228 } while (0)
229 #define KQ_FLUX_WAKEUP(kq) do {						\
230 	if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) {		\
231 		(kq)->kq_state &= ~KQ_FLUXWAIT;				\
232 		wakeup((kq));						\
233 	}								\
234 } while (0)
235 #define KQ_UNLOCK_FLUX(kq) do {						\
236 	KQ_FLUX_WAKEUP(kq);						\
237 	mtx_unlock(&(kq)->kq_lock);					\
238 } while (0)
239 #define KQ_UNLOCK(kq) do {						\
240 	mtx_unlock(&(kq)->kq_lock);					\
241 } while (0)
242 #define KQ_OWNED(kq) do {						\
243 	mtx_assert(&(kq)->kq_lock, MA_OWNED);				\
244 } while (0)
245 #define KQ_NOTOWNED(kq) do {						\
246 	mtx_assert(&(kq)->kq_lock, MA_NOTOWNED);			\
247 } while (0)
248 
249 static struct knlist *
250 kn_list_lock(struct knote *kn)
251 {
252 	struct knlist *knl;
253 
254 	knl = kn->kn_knlist;
255 	if (knl != NULL)
256 		knl->kl_lock(knl->kl_lockarg);
257 	return (knl);
258 }
259 
260 static void
261 kn_list_unlock(struct knlist *knl)
262 {
263 	bool do_free;
264 
265 	if (knl == NULL)
266 		return;
267 	do_free = knl->kl_autodestroy && knlist_empty(knl);
268 	knl->kl_unlock(knl->kl_lockarg);
269 	if (do_free) {
270 		knlist_destroy(knl);
271 		free(knl, M_KQUEUE);
272 	}
273 }
274 
275 static bool
276 kn_in_flux(struct knote *kn)
277 {
278 
279 	return (kn->kn_influx > 0);
280 }
281 
282 static void
283 kn_enter_flux(struct knote *kn)
284 {
285 
286 	KQ_OWNED(kn->kn_kq);
287 	MPASS(kn->kn_influx < INT_MAX);
288 	kn->kn_influx++;
289 }
290 
291 static bool
292 kn_leave_flux(struct knote *kn)
293 {
294 
295 	KQ_OWNED(kn->kn_kq);
296 	MPASS(kn->kn_influx > 0);
297 	kn->kn_influx--;
298 	return (kn->kn_influx == 0);
299 }
300 
301 #define	KNL_ASSERT_LOCK(knl, islocked) do {				\
302 	if (islocked)							\
303 		KNL_ASSERT_LOCKED(knl);				\
304 	else								\
305 		KNL_ASSERT_UNLOCKED(knl);				\
306 } while (0)
307 #ifdef INVARIANTS
308 #define	KNL_ASSERT_LOCKED(knl) do {					\
309 	knl->kl_assert_lock((knl)->kl_lockarg, LA_LOCKED);		\
310 } while (0)
311 #define	KNL_ASSERT_UNLOCKED(knl) do {					\
312 	knl->kl_assert_lock((knl)->kl_lockarg, LA_UNLOCKED);		\
313 } while (0)
314 #else /* !INVARIANTS */
315 #define	KNL_ASSERT_LOCKED(knl) do {} while (0)
316 #define	KNL_ASSERT_UNLOCKED(knl) do {} while (0)
317 #endif /* INVARIANTS */
318 
319 #ifndef	KN_HASHSIZE
320 #define	KN_HASHSIZE		64		/* XXX should be tunable */
321 #endif
322 
323 #define KN_HASH(val, mask)	(((val) ^ (val >> 8)) & (mask))
324 
325 static int
326 filt_nullattach(struct knote *kn)
327 {
328 
329 	return (ENXIO);
330 };
331 
332 struct filterops null_filtops = {
333 	.f_isfd = 0,
334 	.f_attach = filt_nullattach,
335 };
336 
337 /* XXX - make SYSINIT to add these, and move into respective modules. */
338 extern struct filterops sig_filtops;
339 extern struct filterops fs_filtops;
340 
341 /*
342  * Table for for all system-defined filters.
343  */
344 static struct mtx	filterops_lock;
345 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops",
346 	MTX_DEF);
347 static struct {
348 	struct filterops *for_fop;
349 	int for_nolock;
350 	int for_refcnt;
351 } sysfilt_ops[EVFILT_SYSCOUNT] = {
352 	{ &file_filtops, 1 },			/* EVFILT_READ */
353 	{ &file_filtops, 1 },			/* EVFILT_WRITE */
354 	{ &null_filtops },			/* EVFILT_AIO */
355 	{ &file_filtops, 1 },			/* EVFILT_VNODE */
356 	{ &proc_filtops, 1 },			/* EVFILT_PROC */
357 	{ &sig_filtops, 1 },			/* EVFILT_SIGNAL */
358 	{ &timer_filtops, 1 },			/* EVFILT_TIMER */
359 	{ &file_filtops, 1 },			/* EVFILT_PROCDESC */
360 	{ &fs_filtops, 1 },			/* EVFILT_FS */
361 	{ &null_filtops },			/* EVFILT_LIO */
362 	{ &user_filtops, 1 },			/* EVFILT_USER */
363 	{ &null_filtops },			/* EVFILT_SENDFILE */
364 	{ &file_filtops, 1 },                   /* EVFILT_EMPTY */
365 };
366 
367 /*
368  * Simple redirection for all cdevsw style objects to call their fo_kqfilter
369  * method.
370  */
371 static int
372 filt_fileattach(struct knote *kn)
373 {
374 
375 	return (fo_kqfilter(kn->kn_fp, kn));
376 }
377 
378 /*ARGSUSED*/
379 static int
380 kqueue_kqfilter(struct file *fp, struct knote *kn)
381 {
382 	struct kqueue *kq = kn->kn_fp->f_data;
383 
384 	if (kn->kn_filter != EVFILT_READ)
385 		return (EINVAL);
386 
387 	kn->kn_status |= KN_KQUEUE;
388 	kn->kn_fop = &kqread_filtops;
389 	knlist_add(&kq->kq_sel.si_note, kn, 0);
390 
391 	return (0);
392 }
393 
394 static void
395 filt_kqdetach(struct knote *kn)
396 {
397 	struct kqueue *kq = kn->kn_fp->f_data;
398 
399 	knlist_remove(&kq->kq_sel.si_note, kn, 0);
400 }
401 
402 /*ARGSUSED*/
403 static int
404 filt_kqueue(struct knote *kn, long hint)
405 {
406 	struct kqueue *kq = kn->kn_fp->f_data;
407 
408 	kn->kn_data = kq->kq_count;
409 	return (kn->kn_data > 0);
410 }
411 
412 /* XXX - move to kern_proc.c?  */
413 static int
414 filt_procattach(struct knote *kn)
415 {
416 	struct proc *p;
417 	int error;
418 	bool exiting, immediate;
419 
420 	exiting = immediate = false;
421 	if (kn->kn_sfflags & NOTE_EXIT)
422 		p = pfind_any(kn->kn_id);
423 	else
424 		p = pfind(kn->kn_id);
425 	if (p == NULL)
426 		return (ESRCH);
427 	if (p->p_flag & P_WEXIT)
428 		exiting = true;
429 
430 	if ((error = p_cansee(curthread, p))) {
431 		PROC_UNLOCK(p);
432 		return (error);
433 	}
434 
435 	kn->kn_ptr.p_proc = p;
436 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
437 
438 	/*
439 	 * Internal flag indicating registration done by kernel for the
440 	 * purposes of getting a NOTE_CHILD notification.
441 	 */
442 	if (kn->kn_flags & EV_FLAG2) {
443 		kn->kn_flags &= ~EV_FLAG2;
444 		kn->kn_data = kn->kn_sdata;		/* ppid */
445 		kn->kn_fflags = NOTE_CHILD;
446 		kn->kn_sfflags &= ~(NOTE_EXIT | NOTE_EXEC | NOTE_FORK);
447 		immediate = true; /* Force immediate activation of child note. */
448 	}
449 	/*
450 	 * Internal flag indicating registration done by kernel (for other than
451 	 * NOTE_CHILD).
452 	 */
453 	if (kn->kn_flags & EV_FLAG1) {
454 		kn->kn_flags &= ~EV_FLAG1;
455 	}
456 
457 	knlist_add(p->p_klist, kn, 1);
458 
459 	/*
460 	 * Immediately activate any child notes or, in the case of a zombie
461 	 * target process, exit notes.  The latter is necessary to handle the
462 	 * case where the target process, e.g. a child, dies before the kevent
463 	 * is registered.
464 	 */
465 	if (immediate || (exiting && filt_proc(kn, NOTE_EXIT)))
466 		KNOTE_ACTIVATE(kn, 0);
467 
468 	PROC_UNLOCK(p);
469 
470 	return (0);
471 }
472 
473 /*
474  * The knote may be attached to a different process, which may exit,
475  * leaving nothing for the knote to be attached to.  So when the process
476  * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
477  * it will be deleted when read out.  However, as part of the knote deletion,
478  * this routine is called, so a check is needed to avoid actually performing
479  * a detach, because the original process does not exist any more.
480  */
481 /* XXX - move to kern_proc.c?  */
482 static void
483 filt_procdetach(struct knote *kn)
484 {
485 
486 	knlist_remove(kn->kn_knlist, kn, 0);
487 	kn->kn_ptr.p_proc = NULL;
488 }
489 
490 /* XXX - move to kern_proc.c?  */
491 static int
492 filt_proc(struct knote *kn, long hint)
493 {
494 	struct proc *p;
495 	u_int event;
496 
497 	p = kn->kn_ptr.p_proc;
498 	if (p == NULL) /* already activated, from attach filter */
499 		return (0);
500 
501 	/* Mask off extra data. */
502 	event = (u_int)hint & NOTE_PCTRLMASK;
503 
504 	/* If the user is interested in this event, record it. */
505 	if (kn->kn_sfflags & event)
506 		kn->kn_fflags |= event;
507 
508 	/* Process is gone, so flag the event as finished. */
509 	if (event == NOTE_EXIT) {
510 		kn->kn_flags |= EV_EOF | EV_ONESHOT;
511 		kn->kn_ptr.p_proc = NULL;
512 		if (kn->kn_fflags & NOTE_EXIT)
513 			kn->kn_data = KW_EXITCODE(p->p_xexit, p->p_xsig);
514 		if (kn->kn_fflags == 0)
515 			kn->kn_flags |= EV_DROP;
516 		return (1);
517 	}
518 
519 	return (kn->kn_fflags != 0);
520 }
521 
522 /*
523  * Called when the process forked. It mostly does the same as the
524  * knote(), activating all knotes registered to be activated when the
525  * process forked. Additionally, for each knote attached to the
526  * parent, check whether user wants to track the new process. If so
527  * attach a new knote to it, and immediately report an event with the
528  * child's pid.
529  */
530 void
531 knote_fork(struct knlist *list, int pid)
532 {
533 	struct kqueue *kq;
534 	struct knote *kn;
535 	struct kevent kev;
536 	int error;
537 
538 	MPASS(list != NULL);
539 	KNL_ASSERT_LOCKED(list);
540 	if (SLIST_EMPTY(&list->kl_list))
541 		return;
542 
543 	memset(&kev, 0, sizeof(kev));
544 	SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
545 		kq = kn->kn_kq;
546 		KQ_LOCK(kq);
547 		if (kn_in_flux(kn) && (kn->kn_status & KN_SCAN) == 0) {
548 			KQ_UNLOCK(kq);
549 			continue;
550 		}
551 
552 		/*
553 		 * The same as knote(), activate the event.
554 		 */
555 		if ((kn->kn_sfflags & NOTE_TRACK) == 0) {
556 			if (kn->kn_fop->f_event(kn, NOTE_FORK))
557 				KNOTE_ACTIVATE(kn, 1);
558 			KQ_UNLOCK(kq);
559 			continue;
560 		}
561 
562 		/*
563 		 * The NOTE_TRACK case. In addition to the activation
564 		 * of the event, we need to register new events to
565 		 * track the child. Drop the locks in preparation for
566 		 * the call to kqueue_register().
567 		 */
568 		kn_enter_flux(kn);
569 		KQ_UNLOCK(kq);
570 		list->kl_unlock(list->kl_lockarg);
571 
572 		/*
573 		 * Activate existing knote and register tracking knotes with
574 		 * new process.
575 		 *
576 		 * First register a knote to get just the child notice. This
577 		 * must be a separate note from a potential NOTE_EXIT
578 		 * notification since both NOTE_CHILD and NOTE_EXIT are defined
579 		 * to use the data field (in conflicting ways).
580 		 */
581 		kev.ident = pid;
582 		kev.filter = kn->kn_filter;
583 		kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_ONESHOT |
584 		    EV_FLAG2;
585 		kev.fflags = kn->kn_sfflags;
586 		kev.data = kn->kn_id;		/* parent */
587 		kev.udata = kn->kn_kevent.udata;/* preserve udata */
588 		error = kqueue_register(kq, &kev, NULL, M_NOWAIT);
589 		if (error)
590 			kn->kn_fflags |= NOTE_TRACKERR;
591 
592 		/*
593 		 * Then register another knote to track other potential events
594 		 * from the new process.
595 		 */
596 		kev.ident = pid;
597 		kev.filter = kn->kn_filter;
598 		kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
599 		kev.fflags = kn->kn_sfflags;
600 		kev.data = kn->kn_id;		/* parent */
601 		kev.udata = kn->kn_kevent.udata;/* preserve udata */
602 		error = kqueue_register(kq, &kev, NULL, M_NOWAIT);
603 		if (error)
604 			kn->kn_fflags |= NOTE_TRACKERR;
605 		if (kn->kn_fop->f_event(kn, NOTE_FORK))
606 			KNOTE_ACTIVATE(kn, 0);
607 		list->kl_lock(list->kl_lockarg);
608 		KQ_LOCK(kq);
609 		kn_leave_flux(kn);
610 		KQ_UNLOCK_FLUX(kq);
611 	}
612 }
613 
614 /*
615  * XXX: EVFILT_TIMER should perhaps live in kern_time.c beside the
616  * interval timer support code.
617  */
618 
619 #define NOTE_TIMER_PRECMASK						\
620     (NOTE_SECONDS | NOTE_MSECONDS | NOTE_USECONDS | NOTE_NSECONDS)
621 
622 static sbintime_t
623 timer2sbintime(int64_t data, int flags)
624 {
625 	int64_t secs;
626 
627         /*
628          * Macros for converting to the fractional second portion of an
629          * sbintime_t using 64bit multiplication to improve precision.
630          */
631 #define NS_TO_SBT(ns) (((ns) * (((uint64_t)1 << 63) / 500000000)) >> 32)
632 #define US_TO_SBT(us) (((us) * (((uint64_t)1 << 63) / 500000)) >> 32)
633 #define MS_TO_SBT(ms) (((ms) * (((uint64_t)1 << 63) / 500)) >> 32)
634 	switch (flags & NOTE_TIMER_PRECMASK) {
635 	case NOTE_SECONDS:
636 #ifdef __LP64__
637 		if (data > (SBT_MAX / SBT_1S))
638 			return (SBT_MAX);
639 #endif
640 		return ((sbintime_t)data << 32);
641 	case NOTE_MSECONDS: /* FALLTHROUGH */
642 	case 0:
643 		if (data >= 1000) {
644 			secs = data / 1000;
645 #ifdef __LP64__
646 			if (secs > (SBT_MAX / SBT_1S))
647 				return (SBT_MAX);
648 #endif
649 			return (secs << 32 | MS_TO_SBT(data % 1000));
650 		}
651 		return (MS_TO_SBT(data));
652 	case NOTE_USECONDS:
653 		if (data >= 1000000) {
654 			secs = data / 1000000;
655 #ifdef __LP64__
656 			if (secs > (SBT_MAX / SBT_1S))
657 				return (SBT_MAX);
658 #endif
659 			return (secs << 32 | US_TO_SBT(data % 1000000));
660 		}
661 		return (US_TO_SBT(data));
662 	case NOTE_NSECONDS:
663 		if (data >= 1000000000) {
664 			secs = data / 1000000000;
665 #ifdef __LP64__
666 			if (secs > (SBT_MAX / SBT_1S))
667 				return (SBT_MAX);
668 #endif
669 			return (secs << 32 | NS_TO_SBT(data % 1000000000));
670 		}
671 		return (NS_TO_SBT(data));
672 	default:
673 		break;
674 	}
675 	return (-1);
676 }
677 
678 struct kq_timer_cb_data {
679 	struct callout c;
680 	struct proc *p;
681 	struct knote *kn;
682 	int cpuid;
683 	int flags;
684 	TAILQ_ENTRY(kq_timer_cb_data) link;
685 	sbintime_t next;	/* next timer event fires at */
686 	sbintime_t to;		/* precalculated timer period, 0 for abs */
687 };
688 
689 #define	KQ_TIMER_CB_ENQUEUED	0x01
690 
691 static void
692 kqtimer_sched_callout(struct kq_timer_cb_data *kc)
693 {
694 	callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kc->kn,
695 	    kc->cpuid, C_ABSOLUTE);
696 }
697 
698 void
699 kqtimer_proc_continue(struct proc *p)
700 {
701 	struct kq_timer_cb_data *kc, *kc1;
702 	struct bintime bt;
703 	sbintime_t now;
704 
705 	PROC_LOCK_ASSERT(p, MA_OWNED);
706 
707 	getboottimebin(&bt);
708 	now = bttosbt(bt);
709 
710 	TAILQ_FOREACH_SAFE(kc, &p->p_kqtim_stop, link, kc1) {
711 		TAILQ_REMOVE(&p->p_kqtim_stop, kc, link);
712 		kc->flags &= ~KQ_TIMER_CB_ENQUEUED;
713 		if (kc->next <= now)
714 			filt_timerexpire_l(kc->kn, true);
715 		else
716 			kqtimer_sched_callout(kc);
717 	}
718 }
719 
720 static void
721 filt_timerexpire_l(struct knote *kn, bool proc_locked)
722 {
723 	struct kq_timer_cb_data *kc;
724 	struct proc *p;
725 	uint64_t delta;
726 	sbintime_t now;
727 
728 	kc = kn->kn_ptr.p_v;
729 
730 	if ((kn->kn_flags & EV_ONESHOT) != 0 || kc->to == 0) {
731 		kn->kn_data++;
732 		KNOTE_ACTIVATE(kn, 0);
733 		return;
734 	}
735 
736 	now = sbinuptime();
737 	if (now >= kc->next) {
738 		delta = (now - kc->next) / kc->to;
739 		if (delta == 0)
740 			delta = 1;
741 		kn->kn_data += delta;
742 		kc->next += (delta + 1) * kc->to;
743 		if (now >= kc->next)	/* overflow */
744 			kc->next = now + kc->to;
745 		KNOTE_ACTIVATE(kn, 0);	/* XXX - handle locking */
746 	}
747 
748 	/*
749 	 * Initial check for stopped kc->p is racy.  It is fine to
750 	 * miss the set of the stop flags, at worst we would schedule
751 	 * one more callout.  On the other hand, it is not fine to not
752 	 * schedule when we we missed clearing of the flags, we
753 	 * recheck them under the lock and observe consistent state.
754 	 */
755 	p = kc->p;
756 	if (P_SHOULDSTOP(p) || P_KILLED(p)) {
757 		if (!proc_locked)
758 			PROC_LOCK(p);
759 		if (P_SHOULDSTOP(p) || P_KILLED(p)) {
760 			if ((kc->flags & KQ_TIMER_CB_ENQUEUED) == 0) {
761 				kc->flags |= KQ_TIMER_CB_ENQUEUED;
762 				TAILQ_INSERT_TAIL(&p->p_kqtim_stop, kc, link);
763 			}
764 			if (!proc_locked)
765 				PROC_UNLOCK(p);
766 			return;
767 		}
768 		if (!proc_locked)
769 			PROC_UNLOCK(p);
770 	}
771 	kqtimer_sched_callout(kc);
772 }
773 
774 static void
775 filt_timerexpire(void *knx)
776 {
777 	filt_timerexpire_l(knx, false);
778 }
779 
780 /*
781  * data contains amount of time to sleep
782  */
783 static int
784 filt_timervalidate(struct knote *kn, sbintime_t *to)
785 {
786 	struct bintime bt;
787 	sbintime_t sbt;
788 
789 	if (kn->kn_sdata < 0)
790 		return (EINVAL);
791 	if (kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
792 		kn->kn_sdata = 1;
793 	/*
794 	 * The only fflags values supported are the timer unit
795 	 * (precision) and the absolute time indicator.
796 	 */
797 	if ((kn->kn_sfflags & ~(NOTE_TIMER_PRECMASK | NOTE_ABSTIME)) != 0)
798 		return (EINVAL);
799 
800 	*to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
801 	if ((kn->kn_sfflags & NOTE_ABSTIME) != 0) {
802 		getboottimebin(&bt);
803 		sbt = bttosbt(bt);
804 		*to -= sbt;
805 	}
806 	if (*to < 0)
807 		return (EINVAL);
808 	return (0);
809 }
810 
811 static int
812 filt_timerattach(struct knote *kn)
813 {
814 	struct kq_timer_cb_data *kc;
815 	sbintime_t to;
816 	unsigned int ncallouts;
817 	int error;
818 
819 	error = filt_timervalidate(kn, &to);
820 	if (error != 0)
821 		return (error);
822 
823 	do {
824 		ncallouts = kq_ncallouts;
825 		if (ncallouts >= kq_calloutmax)
826 			return (ENOMEM);
827 	} while (!atomic_cmpset_int(&kq_ncallouts, ncallouts, ncallouts + 1));
828 
829 	if ((kn->kn_sfflags & NOTE_ABSTIME) == 0)
830 		kn->kn_flags |= EV_CLEAR;	/* automatically set */
831 	kn->kn_status &= ~KN_DETACHED;		/* knlist_add clears it */
832 	kn->kn_ptr.p_v = kc = malloc(sizeof(*kc), M_KQUEUE, M_WAITOK);
833 	kc->kn = kn;
834 	kc->p = curproc;
835 	kc->cpuid = PCPU_GET(cpuid);
836 	kc->flags = 0;
837 	callout_init(&kc->c, 1);
838 	filt_timerstart(kn, to);
839 
840 	return (0);
841 }
842 
843 static void
844 filt_timerstart(struct knote *kn, sbintime_t to)
845 {
846 	struct kq_timer_cb_data *kc;
847 
848 	kc = kn->kn_ptr.p_v;
849 	if ((kn->kn_sfflags & NOTE_ABSTIME) != 0) {
850 		kc->next = to;
851 		kc->to = 0;
852 	} else {
853 		kc->next = to + sbinuptime();
854 		kc->to = to;
855 	}
856 	kqtimer_sched_callout(kc);
857 }
858 
859 static void
860 filt_timerdetach(struct knote *kn)
861 {
862 	struct kq_timer_cb_data *kc;
863 	unsigned int old __unused;
864 
865 	kc = kn->kn_ptr.p_v;
866 	callout_drain(&kc->c);
867 	if ((kc->flags & KQ_TIMER_CB_ENQUEUED) != 0) {
868 		PROC_LOCK(kc->p);
869 		TAILQ_REMOVE(&kc->p->p_kqtim_stop, kc, link);
870 		PROC_UNLOCK(kc->p);
871 	}
872 	free(kc, M_KQUEUE);
873 	old = atomic_fetchadd_int(&kq_ncallouts, -1);
874 	KASSERT(old > 0, ("Number of callouts cannot become negative"));
875 	kn->kn_status |= KN_DETACHED;	/* knlist_remove sets it */
876 }
877 
878 static void
879 filt_timertouch(struct knote *kn, struct kevent *kev, u_long type)
880 {
881 	struct kq_timer_cb_data *kc;
882 	struct kqueue *kq;
883 	sbintime_t to;
884 	int error;
885 
886 	switch (type) {
887 	case EVENT_REGISTER:
888 		/* Handle re-added timers that update data/fflags */
889 		if (kev->flags & EV_ADD) {
890 			kc = kn->kn_ptr.p_v;
891 
892 			/* Drain any existing callout. */
893 			callout_drain(&kc->c);
894 
895 			/* Throw away any existing undelivered record
896 			 * of the timer expiration. This is done under
897 			 * the presumption that if a process is
898 			 * re-adding this timer with new parameters,
899 			 * it is no longer interested in what may have
900 			 * happened under the old parameters. If it is
901 			 * interested, it can wait for the expiration,
902 			 * delete the old timer definition, and then
903 			 * add the new one.
904 			 *
905 			 * This has to be done while the kq is locked:
906 			 *   - if enqueued, dequeue
907 			 *   - make it no longer active
908 			 *   - clear the count of expiration events
909 			 */
910 			kq = kn->kn_kq;
911 			KQ_LOCK(kq);
912 			if (kn->kn_status & KN_QUEUED)
913 				knote_dequeue(kn);
914 
915 			kn->kn_status &= ~KN_ACTIVE;
916 			kn->kn_data = 0;
917 			KQ_UNLOCK(kq);
918 
919 			/* Reschedule timer based on new data/fflags */
920 			kn->kn_sfflags = kev->fflags;
921 			kn->kn_sdata = kev->data;
922 			error = filt_timervalidate(kn, &to);
923 			if (error != 0) {
924 			  	kn->kn_flags |= EV_ERROR;
925 				kn->kn_data = error;
926 			} else
927 			  	filt_timerstart(kn, to);
928 		}
929 		break;
930 
931         case EVENT_PROCESS:
932 		*kev = kn->kn_kevent;
933 		if (kn->kn_flags & EV_CLEAR) {
934 			kn->kn_data = 0;
935 			kn->kn_fflags = 0;
936 		}
937 		break;
938 
939 	default:
940 		panic("filt_timertouch() - invalid type (%ld)", type);
941 		break;
942 	}
943 }
944 
945 static int
946 filt_timer(struct knote *kn, long hint)
947 {
948 
949 	return (kn->kn_data != 0);
950 }
951 
952 static int
953 filt_userattach(struct knote *kn)
954 {
955 
956 	/*
957 	 * EVFILT_USER knotes are not attached to anything in the kernel.
958 	 */
959 	kn->kn_hook = NULL;
960 	if (kn->kn_fflags & NOTE_TRIGGER)
961 		kn->kn_hookid = 1;
962 	else
963 		kn->kn_hookid = 0;
964 	return (0);
965 }
966 
967 static void
968 filt_userdetach(__unused struct knote *kn)
969 {
970 
971 	/*
972 	 * EVFILT_USER knotes are not attached to anything in the kernel.
973 	 */
974 }
975 
976 static int
977 filt_user(struct knote *kn, __unused long hint)
978 {
979 
980 	return (kn->kn_hookid);
981 }
982 
983 static void
984 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
985 {
986 	u_int ffctrl;
987 
988 	switch (type) {
989 	case EVENT_REGISTER:
990 		if (kev->fflags & NOTE_TRIGGER)
991 			kn->kn_hookid = 1;
992 
993 		ffctrl = kev->fflags & NOTE_FFCTRLMASK;
994 		kev->fflags &= NOTE_FFLAGSMASK;
995 		switch (ffctrl) {
996 		case NOTE_FFNOP:
997 			break;
998 
999 		case NOTE_FFAND:
1000 			kn->kn_sfflags &= kev->fflags;
1001 			break;
1002 
1003 		case NOTE_FFOR:
1004 			kn->kn_sfflags |= kev->fflags;
1005 			break;
1006 
1007 		case NOTE_FFCOPY:
1008 			kn->kn_sfflags = kev->fflags;
1009 			break;
1010 
1011 		default:
1012 			/* XXX Return error? */
1013 			break;
1014 		}
1015 		kn->kn_sdata = kev->data;
1016 		if (kev->flags & EV_CLEAR) {
1017 			kn->kn_hookid = 0;
1018 			kn->kn_data = 0;
1019 			kn->kn_fflags = 0;
1020 		}
1021 		break;
1022 
1023         case EVENT_PROCESS:
1024 		*kev = kn->kn_kevent;
1025 		kev->fflags = kn->kn_sfflags;
1026 		kev->data = kn->kn_sdata;
1027 		if (kn->kn_flags & EV_CLEAR) {
1028 			kn->kn_hookid = 0;
1029 			kn->kn_data = 0;
1030 			kn->kn_fflags = 0;
1031 		}
1032 		break;
1033 
1034 	default:
1035 		panic("filt_usertouch() - invalid type (%ld)", type);
1036 		break;
1037 	}
1038 }
1039 
1040 int
1041 sys_kqueue(struct thread *td, struct kqueue_args *uap)
1042 {
1043 
1044 	return (kern_kqueue(td, 0, NULL));
1045 }
1046 
1047 static void
1048 kqueue_init(struct kqueue *kq)
1049 {
1050 
1051 	mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF | MTX_DUPOK);
1052 	TAILQ_INIT(&kq->kq_head);
1053 	knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
1054 	TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
1055 }
1056 
1057 int
1058 kern_kqueue(struct thread *td, int flags, struct filecaps *fcaps)
1059 {
1060 	struct filedesc *fdp;
1061 	struct kqueue *kq;
1062 	struct file *fp;
1063 	struct ucred *cred;
1064 	int fd, error;
1065 
1066 	fdp = td->td_proc->p_fd;
1067 	cred = td->td_ucred;
1068 	if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_KQUEUES)))
1069 		return (ENOMEM);
1070 
1071 	error = falloc_caps(td, &fp, &fd, flags, fcaps);
1072 	if (error != 0) {
1073 		chgkqcnt(cred->cr_ruidinfo, -1, 0);
1074 		return (error);
1075 	}
1076 
1077 	/* An extra reference on `fp' has been held for us by falloc(). */
1078 	kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
1079 	kqueue_init(kq);
1080 	kq->kq_fdp = fdp;
1081 	kq->kq_cred = crhold(cred);
1082 
1083 	FILEDESC_XLOCK(fdp);
1084 	TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
1085 	FILEDESC_XUNLOCK(fdp);
1086 
1087 	finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
1088 	fdrop(fp, td);
1089 
1090 	td->td_retval[0] = fd;
1091 	return (0);
1092 }
1093 
1094 struct g_kevent_args {
1095 	int	fd;
1096 	void	*changelist;
1097 	int	nchanges;
1098 	void	*eventlist;
1099 	int	nevents;
1100 	const struct timespec *timeout;
1101 };
1102 
1103 int
1104 sys_kevent(struct thread *td, struct kevent_args *uap)
1105 {
1106 	struct kevent_copyops k_ops = {
1107 		.arg = uap,
1108 		.k_copyout = kevent_copyout,
1109 		.k_copyin = kevent_copyin,
1110 		.kevent_size = sizeof(struct kevent),
1111 	};
1112 	struct g_kevent_args gk_args = {
1113 		.fd = uap->fd,
1114 		.changelist = uap->changelist,
1115 		.nchanges = uap->nchanges,
1116 		.eventlist = uap->eventlist,
1117 		.nevents = uap->nevents,
1118 		.timeout = uap->timeout,
1119 	};
1120 
1121 	return (kern_kevent_generic(td, &gk_args, &k_ops, "kevent"));
1122 }
1123 
1124 static int
1125 kern_kevent_generic(struct thread *td, struct g_kevent_args *uap,
1126     struct kevent_copyops *k_ops, const char *struct_name)
1127 {
1128 	struct timespec ts, *tsp;
1129 #ifdef KTRACE
1130 	struct kevent *eventlist = uap->eventlist;
1131 #endif
1132 	int error;
1133 
1134 	if (uap->timeout != NULL) {
1135 		error = copyin(uap->timeout, &ts, sizeof(ts));
1136 		if (error)
1137 			return (error);
1138 		tsp = &ts;
1139 	} else
1140 		tsp = NULL;
1141 
1142 #ifdef KTRACE
1143 	if (KTRPOINT(td, KTR_STRUCT_ARRAY))
1144 		ktrstructarray(struct_name, UIO_USERSPACE, uap->changelist,
1145 		    uap->nchanges, k_ops->kevent_size);
1146 #endif
1147 
1148 	error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
1149 	    k_ops, tsp);
1150 
1151 #ifdef KTRACE
1152 	if (error == 0 && KTRPOINT(td, KTR_STRUCT_ARRAY))
1153 		ktrstructarray(struct_name, UIO_USERSPACE, eventlist,
1154 		    td->td_retval[0], k_ops->kevent_size);
1155 #endif
1156 
1157 	return (error);
1158 }
1159 
1160 /*
1161  * Copy 'count' items into the destination list pointed to by uap->eventlist.
1162  */
1163 static int
1164 kevent_copyout(void *arg, struct kevent *kevp, int count)
1165 {
1166 	struct kevent_args *uap;
1167 	int error;
1168 
1169 	KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1170 	uap = (struct kevent_args *)arg;
1171 
1172 	error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
1173 	if (error == 0)
1174 		uap->eventlist += count;
1175 	return (error);
1176 }
1177 
1178 /*
1179  * Copy 'count' items from the list pointed to by uap->changelist.
1180  */
1181 static int
1182 kevent_copyin(void *arg, struct kevent *kevp, int count)
1183 {
1184 	struct kevent_args *uap;
1185 	int error;
1186 
1187 	KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1188 	uap = (struct kevent_args *)arg;
1189 
1190 	error = copyin(uap->changelist, kevp, count * sizeof *kevp);
1191 	if (error == 0)
1192 		uap->changelist += count;
1193 	return (error);
1194 }
1195 
1196 #ifdef COMPAT_FREEBSD11
1197 static int
1198 kevent11_copyout(void *arg, struct kevent *kevp, int count)
1199 {
1200 	struct freebsd11_kevent_args *uap;
1201 	struct kevent_freebsd11 kev11;
1202 	int error, i;
1203 
1204 	KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1205 	uap = (struct freebsd11_kevent_args *)arg;
1206 
1207 	for (i = 0; i < count; i++) {
1208 		kev11.ident = kevp->ident;
1209 		kev11.filter = kevp->filter;
1210 		kev11.flags = kevp->flags;
1211 		kev11.fflags = kevp->fflags;
1212 		kev11.data = kevp->data;
1213 		kev11.udata = kevp->udata;
1214 		error = copyout(&kev11, uap->eventlist, sizeof(kev11));
1215 		if (error != 0)
1216 			break;
1217 		uap->eventlist++;
1218 		kevp++;
1219 	}
1220 	return (error);
1221 }
1222 
1223 /*
1224  * Copy 'count' items from the list pointed to by uap->changelist.
1225  */
1226 static int
1227 kevent11_copyin(void *arg, struct kevent *kevp, int count)
1228 {
1229 	struct freebsd11_kevent_args *uap;
1230 	struct kevent_freebsd11 kev11;
1231 	int error, i;
1232 
1233 	KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1234 	uap = (struct freebsd11_kevent_args *)arg;
1235 
1236 	for (i = 0; i < count; i++) {
1237 		error = copyin(uap->changelist, &kev11, sizeof(kev11));
1238 		if (error != 0)
1239 			break;
1240 		kevp->ident = kev11.ident;
1241 		kevp->filter = kev11.filter;
1242 		kevp->flags = kev11.flags;
1243 		kevp->fflags = kev11.fflags;
1244 		kevp->data = (uintptr_t)kev11.data;
1245 		kevp->udata = kev11.udata;
1246 		bzero(&kevp->ext, sizeof(kevp->ext));
1247 		uap->changelist++;
1248 		kevp++;
1249 	}
1250 	return (error);
1251 }
1252 
1253 int
1254 freebsd11_kevent(struct thread *td, struct freebsd11_kevent_args *uap)
1255 {
1256 	struct kevent_copyops k_ops = {
1257 		.arg = uap,
1258 		.k_copyout = kevent11_copyout,
1259 		.k_copyin = kevent11_copyin,
1260 		.kevent_size = sizeof(struct kevent_freebsd11),
1261 	};
1262 	struct g_kevent_args gk_args = {
1263 		.fd = uap->fd,
1264 		.changelist = uap->changelist,
1265 		.nchanges = uap->nchanges,
1266 		.eventlist = uap->eventlist,
1267 		.nevents = uap->nevents,
1268 		.timeout = uap->timeout,
1269 	};
1270 
1271 	return (kern_kevent_generic(td, &gk_args, &k_ops, "kevent_freebsd11"));
1272 }
1273 #endif
1274 
1275 int
1276 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
1277     struct kevent_copyops *k_ops, const struct timespec *timeout)
1278 {
1279 	cap_rights_t rights;
1280 	struct file *fp;
1281 	int error;
1282 
1283 	cap_rights_init_zero(&rights);
1284 	if (nchanges > 0)
1285 		cap_rights_set_one(&rights, CAP_KQUEUE_CHANGE);
1286 	if (nevents > 0)
1287 		cap_rights_set_one(&rights, CAP_KQUEUE_EVENT);
1288 	error = fget(td, fd, &rights, &fp);
1289 	if (error != 0)
1290 		return (error);
1291 
1292 	error = kern_kevent_fp(td, fp, nchanges, nevents, k_ops, timeout);
1293 	fdrop(fp, td);
1294 
1295 	return (error);
1296 }
1297 
1298 static int
1299 kqueue_kevent(struct kqueue *kq, struct thread *td, int nchanges, int nevents,
1300     struct kevent_copyops *k_ops, const struct timespec *timeout)
1301 {
1302 	struct kevent keva[KQ_NEVENTS];
1303 	struct kevent *kevp, *changes;
1304 	int i, n, nerrors, error;
1305 
1306 	if (nchanges < 0)
1307 		return (EINVAL);
1308 
1309 	nerrors = 0;
1310 	while (nchanges > 0) {
1311 		n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
1312 		error = k_ops->k_copyin(k_ops->arg, keva, n);
1313 		if (error)
1314 			return (error);
1315 		changes = keva;
1316 		for (i = 0; i < n; i++) {
1317 			kevp = &changes[i];
1318 			if (!kevp->filter)
1319 				continue;
1320 			kevp->flags &= ~EV_SYSFLAGS;
1321 			error = kqueue_register(kq, kevp, td, M_WAITOK);
1322 			if (error || (kevp->flags & EV_RECEIPT)) {
1323 				if (nevents == 0)
1324 					return (error);
1325 				kevp->flags = EV_ERROR;
1326 				kevp->data = error;
1327 				(void)k_ops->k_copyout(k_ops->arg, kevp, 1);
1328 				nevents--;
1329 				nerrors++;
1330 			}
1331 		}
1332 		nchanges -= n;
1333 	}
1334 	if (nerrors) {
1335 		td->td_retval[0] = nerrors;
1336 		return (0);
1337 	}
1338 
1339 	return (kqueue_scan(kq, nevents, k_ops, timeout, keva, td));
1340 }
1341 
1342 int
1343 kern_kevent_fp(struct thread *td, struct file *fp, int nchanges, int nevents,
1344     struct kevent_copyops *k_ops, const struct timespec *timeout)
1345 {
1346 	struct kqueue *kq;
1347 	int error;
1348 
1349 	error = kqueue_acquire(fp, &kq);
1350 	if (error != 0)
1351 		return (error);
1352 	error = kqueue_kevent(kq, td, nchanges, nevents, k_ops, timeout);
1353 	kqueue_release(kq, 0);
1354 	return (error);
1355 }
1356 
1357 /*
1358  * Performs a kevent() call on a temporarily created kqueue. This can be
1359  * used to perform one-shot polling, similar to poll() and select().
1360  */
1361 int
1362 kern_kevent_anonymous(struct thread *td, int nevents,
1363     struct kevent_copyops *k_ops)
1364 {
1365 	struct kqueue kq = {};
1366 	int error;
1367 
1368 	kqueue_init(&kq);
1369 	kq.kq_refcnt = 1;
1370 	error = kqueue_kevent(&kq, td, nevents, nevents, k_ops, NULL);
1371 	kqueue_drain(&kq, td);
1372 	kqueue_destroy(&kq);
1373 	return (error);
1374 }
1375 
1376 int
1377 kqueue_add_filteropts(int filt, struct filterops *filtops)
1378 {
1379 	int error;
1380 
1381 	error = 0;
1382 	if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
1383 		printf(
1384 "trying to add a filterop that is out of range: %d is beyond %d\n",
1385 		    ~filt, EVFILT_SYSCOUNT);
1386 		return EINVAL;
1387 	}
1388 	mtx_lock(&filterops_lock);
1389 	if (sysfilt_ops[~filt].for_fop != &null_filtops &&
1390 	    sysfilt_ops[~filt].for_fop != NULL)
1391 		error = EEXIST;
1392 	else {
1393 		sysfilt_ops[~filt].for_fop = filtops;
1394 		sysfilt_ops[~filt].for_refcnt = 0;
1395 	}
1396 	mtx_unlock(&filterops_lock);
1397 
1398 	return (error);
1399 }
1400 
1401 int
1402 kqueue_del_filteropts(int filt)
1403 {
1404 	int error;
1405 
1406 	error = 0;
1407 	if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1408 		return EINVAL;
1409 
1410 	mtx_lock(&filterops_lock);
1411 	if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1412 	    sysfilt_ops[~filt].for_fop == NULL)
1413 		error = EINVAL;
1414 	else if (sysfilt_ops[~filt].for_refcnt != 0)
1415 		error = EBUSY;
1416 	else {
1417 		sysfilt_ops[~filt].for_fop = &null_filtops;
1418 		sysfilt_ops[~filt].for_refcnt = 0;
1419 	}
1420 	mtx_unlock(&filterops_lock);
1421 
1422 	return error;
1423 }
1424 
1425 static struct filterops *
1426 kqueue_fo_find(int filt)
1427 {
1428 
1429 	if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1430 		return NULL;
1431 
1432 	if (sysfilt_ops[~filt].for_nolock)
1433 		return sysfilt_ops[~filt].for_fop;
1434 
1435 	mtx_lock(&filterops_lock);
1436 	sysfilt_ops[~filt].for_refcnt++;
1437 	if (sysfilt_ops[~filt].for_fop == NULL)
1438 		sysfilt_ops[~filt].for_fop = &null_filtops;
1439 	mtx_unlock(&filterops_lock);
1440 
1441 	return sysfilt_ops[~filt].for_fop;
1442 }
1443 
1444 static void
1445 kqueue_fo_release(int filt)
1446 {
1447 
1448 	if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1449 		return;
1450 
1451 	if (sysfilt_ops[~filt].for_nolock)
1452 		return;
1453 
1454 	mtx_lock(&filterops_lock);
1455 	KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1456 	    ("filter object refcount not valid on release"));
1457 	sysfilt_ops[~filt].for_refcnt--;
1458 	mtx_unlock(&filterops_lock);
1459 }
1460 
1461 /*
1462  * A ref to kq (obtained via kqueue_acquire) must be held.
1463  */
1464 static int
1465 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td,
1466     int mflag)
1467 {
1468 	struct filterops *fops;
1469 	struct file *fp;
1470 	struct knote *kn, *tkn;
1471 	struct knlist *knl;
1472 	int error, filt, event;
1473 	int haskqglobal, filedesc_unlock;
1474 
1475 	if ((kev->flags & (EV_ENABLE | EV_DISABLE)) == (EV_ENABLE | EV_DISABLE))
1476 		return (EINVAL);
1477 
1478 	fp = NULL;
1479 	kn = NULL;
1480 	knl = NULL;
1481 	error = 0;
1482 	haskqglobal = 0;
1483 	filedesc_unlock = 0;
1484 
1485 	filt = kev->filter;
1486 	fops = kqueue_fo_find(filt);
1487 	if (fops == NULL)
1488 		return EINVAL;
1489 
1490 	if (kev->flags & EV_ADD) {
1491 		/*
1492 		 * Prevent waiting with locks.  Non-sleepable
1493 		 * allocation failures are handled in the loop, only
1494 		 * if the spare knote appears to be actually required.
1495 		 */
1496 		tkn = knote_alloc(mflag);
1497 	} else {
1498 		tkn = NULL;
1499 	}
1500 
1501 findkn:
1502 	if (fops->f_isfd) {
1503 		KASSERT(td != NULL, ("td is NULL"));
1504 		if (kev->ident > INT_MAX)
1505 			error = EBADF;
1506 		else
1507 			error = fget(td, kev->ident, &cap_event_rights, &fp);
1508 		if (error)
1509 			goto done;
1510 
1511 		if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1512 		    kev->ident, M_NOWAIT) != 0) {
1513 			/* try again */
1514 			fdrop(fp, td);
1515 			fp = NULL;
1516 			error = kqueue_expand(kq, fops, kev->ident, mflag);
1517 			if (error)
1518 				goto done;
1519 			goto findkn;
1520 		}
1521 
1522 		if (fp->f_type == DTYPE_KQUEUE) {
1523 			/*
1524 			 * If we add some intelligence about what we are doing,
1525 			 * we should be able to support events on ourselves.
1526 			 * We need to know when we are doing this to prevent
1527 			 * getting both the knlist lock and the kq lock since
1528 			 * they are the same thing.
1529 			 */
1530 			if (fp->f_data == kq) {
1531 				error = EINVAL;
1532 				goto done;
1533 			}
1534 
1535 			/*
1536 			 * Pre-lock the filedesc before the global
1537 			 * lock mutex, see the comment in
1538 			 * kqueue_close().
1539 			 */
1540 			FILEDESC_XLOCK(td->td_proc->p_fd);
1541 			filedesc_unlock = 1;
1542 			KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1543 		}
1544 
1545 		KQ_LOCK(kq);
1546 		if (kev->ident < kq->kq_knlistsize) {
1547 			SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1548 				if (kev->filter == kn->kn_filter)
1549 					break;
1550 		}
1551 	} else {
1552 		if ((kev->flags & EV_ADD) == EV_ADD) {
1553 			error = kqueue_expand(kq, fops, kev->ident, mflag);
1554 			if (error != 0)
1555 				goto done;
1556 		}
1557 
1558 		KQ_LOCK(kq);
1559 
1560 		/*
1561 		 * If possible, find an existing knote to use for this kevent.
1562 		 */
1563 		if (kev->filter == EVFILT_PROC &&
1564 		    (kev->flags & (EV_FLAG1 | EV_FLAG2)) != 0) {
1565 			/* This is an internal creation of a process tracking
1566 			 * note. Don't attempt to coalesce this with an
1567 			 * existing note.
1568 			 */
1569 			;
1570 		} else if (kq->kq_knhashmask != 0) {
1571 			struct klist *list;
1572 
1573 			list = &kq->kq_knhash[
1574 			    KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1575 			SLIST_FOREACH(kn, list, kn_link)
1576 				if (kev->ident == kn->kn_id &&
1577 				    kev->filter == kn->kn_filter)
1578 					break;
1579 		}
1580 	}
1581 
1582 	/* knote is in the process of changing, wait for it to stabilize. */
1583 	if (kn != NULL && kn_in_flux(kn)) {
1584 		KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1585 		if (filedesc_unlock) {
1586 			FILEDESC_XUNLOCK(td->td_proc->p_fd);
1587 			filedesc_unlock = 0;
1588 		}
1589 		kq->kq_state |= KQ_FLUXWAIT;
1590 		msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1591 		if (fp != NULL) {
1592 			fdrop(fp, td);
1593 			fp = NULL;
1594 		}
1595 		goto findkn;
1596 	}
1597 
1598 	/*
1599 	 * kn now contains the matching knote, or NULL if no match
1600 	 */
1601 	if (kn == NULL) {
1602 		if (kev->flags & EV_ADD) {
1603 			kn = tkn;
1604 			tkn = NULL;
1605 			if (kn == NULL) {
1606 				KQ_UNLOCK(kq);
1607 				error = ENOMEM;
1608 				goto done;
1609 			}
1610 			kn->kn_fp = fp;
1611 			kn->kn_kq = kq;
1612 			kn->kn_fop = fops;
1613 			/*
1614 			 * apply reference counts to knote structure, and
1615 			 * do not release it at the end of this routine.
1616 			 */
1617 			fops = NULL;
1618 			fp = NULL;
1619 
1620 			kn->kn_sfflags = kev->fflags;
1621 			kn->kn_sdata = kev->data;
1622 			kev->fflags = 0;
1623 			kev->data = 0;
1624 			kn->kn_kevent = *kev;
1625 			kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1626 			    EV_ENABLE | EV_DISABLE | EV_FORCEONESHOT);
1627 			kn->kn_status = KN_DETACHED;
1628 			if ((kev->flags & EV_DISABLE) != 0)
1629 				kn->kn_status |= KN_DISABLED;
1630 			kn_enter_flux(kn);
1631 
1632 			error = knote_attach(kn, kq);
1633 			KQ_UNLOCK(kq);
1634 			if (error != 0) {
1635 				tkn = kn;
1636 				goto done;
1637 			}
1638 
1639 			if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1640 				knote_drop_detached(kn, td);
1641 				goto done;
1642 			}
1643 			knl = kn_list_lock(kn);
1644 			goto done_ev_add;
1645 		} else {
1646 			/* No matching knote and the EV_ADD flag is not set. */
1647 			KQ_UNLOCK(kq);
1648 			error = ENOENT;
1649 			goto done;
1650 		}
1651 	}
1652 
1653 	if (kev->flags & EV_DELETE) {
1654 		kn_enter_flux(kn);
1655 		KQ_UNLOCK(kq);
1656 		knote_drop(kn, td);
1657 		goto done;
1658 	}
1659 
1660 	if (kev->flags & EV_FORCEONESHOT) {
1661 		kn->kn_flags |= EV_ONESHOT;
1662 		KNOTE_ACTIVATE(kn, 1);
1663 	}
1664 
1665 	if ((kev->flags & EV_ENABLE) != 0)
1666 		kn->kn_status &= ~KN_DISABLED;
1667 	else if ((kev->flags & EV_DISABLE) != 0)
1668 		kn->kn_status |= KN_DISABLED;
1669 
1670 	/*
1671 	 * The user may change some filter values after the initial EV_ADD,
1672 	 * but doing so will not reset any filter which has already been
1673 	 * triggered.
1674 	 */
1675 	kn->kn_status |= KN_SCAN;
1676 	kn_enter_flux(kn);
1677 	KQ_UNLOCK(kq);
1678 	knl = kn_list_lock(kn);
1679 	kn->kn_kevent.udata = kev->udata;
1680 	if (!fops->f_isfd && fops->f_touch != NULL) {
1681 		fops->f_touch(kn, kev, EVENT_REGISTER);
1682 	} else {
1683 		kn->kn_sfflags = kev->fflags;
1684 		kn->kn_sdata = kev->data;
1685 	}
1686 
1687 done_ev_add:
1688 	/*
1689 	 * We can get here with kn->kn_knlist == NULL.  This can happen when
1690 	 * the initial attach event decides that the event is "completed"
1691 	 * already, e.g., filt_procattach() is called on a zombie process.  It
1692 	 * will call filt_proc() which will remove it from the list, and NULL
1693 	 * kn_knlist.
1694 	 *
1695 	 * KN_DISABLED will be stable while the knote is in flux, so the
1696 	 * unlocked read will not race with an update.
1697 	 */
1698 	if ((kn->kn_status & KN_DISABLED) == 0)
1699 		event = kn->kn_fop->f_event(kn, 0);
1700 	else
1701 		event = 0;
1702 
1703 	KQ_LOCK(kq);
1704 	if (event)
1705 		kn->kn_status |= KN_ACTIVE;
1706 	if ((kn->kn_status & (KN_ACTIVE | KN_DISABLED | KN_QUEUED)) ==
1707 	    KN_ACTIVE)
1708 		knote_enqueue(kn);
1709 	kn->kn_status &= ~KN_SCAN;
1710 	kn_leave_flux(kn);
1711 	kn_list_unlock(knl);
1712 	KQ_UNLOCK_FLUX(kq);
1713 
1714 done:
1715 	KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1716 	if (filedesc_unlock)
1717 		FILEDESC_XUNLOCK(td->td_proc->p_fd);
1718 	if (fp != NULL)
1719 		fdrop(fp, td);
1720 	knote_free(tkn);
1721 	if (fops != NULL)
1722 		kqueue_fo_release(filt);
1723 	return (error);
1724 }
1725 
1726 static int
1727 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1728 {
1729 	int error;
1730 	struct kqueue *kq;
1731 
1732 	error = 0;
1733 
1734 	kq = fp->f_data;
1735 	if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1736 		return (EBADF);
1737 	*kqp = kq;
1738 	KQ_LOCK(kq);
1739 	if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1740 		KQ_UNLOCK(kq);
1741 		return (EBADF);
1742 	}
1743 	kq->kq_refcnt++;
1744 	KQ_UNLOCK(kq);
1745 
1746 	return error;
1747 }
1748 
1749 static void
1750 kqueue_release(struct kqueue *kq, int locked)
1751 {
1752 	if (locked)
1753 		KQ_OWNED(kq);
1754 	else
1755 		KQ_LOCK(kq);
1756 	kq->kq_refcnt--;
1757 	if (kq->kq_refcnt == 1)
1758 		wakeup(&kq->kq_refcnt);
1759 	if (!locked)
1760 		KQ_UNLOCK(kq);
1761 }
1762 
1763 static void
1764 kqueue_schedtask(struct kqueue *kq)
1765 {
1766 
1767 	KQ_OWNED(kq);
1768 	KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1769 	    ("scheduling kqueue task while draining"));
1770 
1771 	if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1772 		taskqueue_enqueue(taskqueue_kqueue_ctx, &kq->kq_task);
1773 		kq->kq_state |= KQ_TASKSCHED;
1774 	}
1775 }
1776 
1777 /*
1778  * Expand the kq to make sure we have storage for fops/ident pair.
1779  *
1780  * Return 0 on success (or no work necessary), return errno on failure.
1781  */
1782 static int
1783 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1784     int mflag)
1785 {
1786 	struct klist *list, *tmp_knhash, *to_free;
1787 	u_long tmp_knhashmask;
1788 	int error, fd, size;
1789 
1790 	KQ_NOTOWNED(kq);
1791 
1792 	error = 0;
1793 	to_free = NULL;
1794 	if (fops->f_isfd) {
1795 		fd = ident;
1796 		if (kq->kq_knlistsize <= fd) {
1797 			size = kq->kq_knlistsize;
1798 			while (size <= fd)
1799 				size += KQEXTENT;
1800 			list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1801 			if (list == NULL)
1802 				return ENOMEM;
1803 			KQ_LOCK(kq);
1804 			if ((kq->kq_state & KQ_CLOSING) != 0) {
1805 				to_free = list;
1806 				error = EBADF;
1807 			} else if (kq->kq_knlistsize > fd) {
1808 				to_free = list;
1809 			} else {
1810 				if (kq->kq_knlist != NULL) {
1811 					bcopy(kq->kq_knlist, list,
1812 					    kq->kq_knlistsize * sizeof(*list));
1813 					to_free = kq->kq_knlist;
1814 					kq->kq_knlist = NULL;
1815 				}
1816 				bzero((caddr_t)list +
1817 				    kq->kq_knlistsize * sizeof(*list),
1818 				    (size - kq->kq_knlistsize) * sizeof(*list));
1819 				kq->kq_knlistsize = size;
1820 				kq->kq_knlist = list;
1821 			}
1822 			KQ_UNLOCK(kq);
1823 		}
1824 	} else {
1825 		if (kq->kq_knhashmask == 0) {
1826 			tmp_knhash = hashinit_flags(KN_HASHSIZE, M_KQUEUE,
1827 			    &tmp_knhashmask, (mflag & M_WAITOK) != 0 ?
1828 			    HASH_WAITOK : HASH_NOWAIT);
1829 			if (tmp_knhash == NULL)
1830 				return (ENOMEM);
1831 			KQ_LOCK(kq);
1832 			if ((kq->kq_state & KQ_CLOSING) != 0) {
1833 				to_free = tmp_knhash;
1834 				error = EBADF;
1835 			} else if (kq->kq_knhashmask == 0) {
1836 				kq->kq_knhash = tmp_knhash;
1837 				kq->kq_knhashmask = tmp_knhashmask;
1838 			} else {
1839 				to_free = tmp_knhash;
1840 			}
1841 			KQ_UNLOCK(kq);
1842 		}
1843 	}
1844 	free(to_free, M_KQUEUE);
1845 
1846 	KQ_NOTOWNED(kq);
1847 	return (error);
1848 }
1849 
1850 static void
1851 kqueue_task(void *arg, int pending)
1852 {
1853 	struct kqueue *kq;
1854 	int haskqglobal;
1855 
1856 	haskqglobal = 0;
1857 	kq = arg;
1858 
1859 	KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1860 	KQ_LOCK(kq);
1861 
1862 	KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1863 
1864 	kq->kq_state &= ~KQ_TASKSCHED;
1865 	if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1866 		wakeup(&kq->kq_state);
1867 	}
1868 	KQ_UNLOCK(kq);
1869 	KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1870 }
1871 
1872 /*
1873  * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1874  * We treat KN_MARKER knotes as if they are in flux.
1875  */
1876 static int
1877 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1878     const struct timespec *tsp, struct kevent *keva, struct thread *td)
1879 {
1880 	struct kevent *kevp;
1881 	struct knote *kn, *marker;
1882 	struct knlist *knl;
1883 	sbintime_t asbt, rsbt;
1884 	int count, error, haskqglobal, influx, nkev, touch;
1885 
1886 	count = maxevents;
1887 	nkev = 0;
1888 	error = 0;
1889 	haskqglobal = 0;
1890 
1891 	if (maxevents == 0)
1892 		goto done_nl;
1893 	if (maxevents < 0) {
1894 		error = EINVAL;
1895 		goto done_nl;
1896 	}
1897 
1898 	rsbt = 0;
1899 	if (tsp != NULL) {
1900 		if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1901 		    tsp->tv_nsec >= 1000000000) {
1902 			error = EINVAL;
1903 			goto done_nl;
1904 		}
1905 		if (timespecisset(tsp)) {
1906 			if (tsp->tv_sec <= INT32_MAX) {
1907 				rsbt = tstosbt(*tsp);
1908 				if (TIMESEL(&asbt, rsbt))
1909 					asbt += tc_tick_sbt;
1910 				if (asbt <= SBT_MAX - rsbt)
1911 					asbt += rsbt;
1912 				else
1913 					asbt = 0;
1914 				rsbt >>= tc_precexp;
1915 			} else
1916 				asbt = 0;
1917 		} else
1918 			asbt = -1;
1919 	} else
1920 		asbt = 0;
1921 	marker = knote_alloc(M_WAITOK);
1922 	marker->kn_status = KN_MARKER;
1923 	KQ_LOCK(kq);
1924 
1925 retry:
1926 	kevp = keva;
1927 	if (kq->kq_count == 0) {
1928 		if (asbt == -1) {
1929 			error = EWOULDBLOCK;
1930 		} else {
1931 			kq->kq_state |= KQ_SLEEP;
1932 			error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1933 			    "kqread", asbt, rsbt, C_ABSOLUTE);
1934 		}
1935 		if (error == 0)
1936 			goto retry;
1937 		/* don't restart after signals... */
1938 		if (error == ERESTART)
1939 			error = EINTR;
1940 		else if (error == EWOULDBLOCK)
1941 			error = 0;
1942 		goto done;
1943 	}
1944 
1945 	TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1946 	influx = 0;
1947 	while (count) {
1948 		KQ_OWNED(kq);
1949 		kn = TAILQ_FIRST(&kq->kq_head);
1950 
1951 		if ((kn->kn_status == KN_MARKER && kn != marker) ||
1952 		    kn_in_flux(kn)) {
1953 			if (influx) {
1954 				influx = 0;
1955 				KQ_FLUX_WAKEUP(kq);
1956 			}
1957 			kq->kq_state |= KQ_FLUXWAIT;
1958 			error = msleep(kq, &kq->kq_lock, PSOCK,
1959 			    "kqflxwt", 0);
1960 			continue;
1961 		}
1962 
1963 		TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1964 		if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1965 			kn->kn_status &= ~KN_QUEUED;
1966 			kq->kq_count--;
1967 			continue;
1968 		}
1969 		if (kn == marker) {
1970 			KQ_FLUX_WAKEUP(kq);
1971 			if (count == maxevents)
1972 				goto retry;
1973 			goto done;
1974 		}
1975 		KASSERT(!kn_in_flux(kn),
1976 		    ("knote %p is unexpectedly in flux", kn));
1977 
1978 		if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1979 			kn->kn_status &= ~KN_QUEUED;
1980 			kn_enter_flux(kn);
1981 			kq->kq_count--;
1982 			KQ_UNLOCK(kq);
1983 			/*
1984 			 * We don't need to lock the list since we've
1985 			 * marked it as in flux.
1986 			 */
1987 			knote_drop(kn, td);
1988 			KQ_LOCK(kq);
1989 			continue;
1990 		} else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1991 			kn->kn_status &= ~KN_QUEUED;
1992 			kn_enter_flux(kn);
1993 			kq->kq_count--;
1994 			KQ_UNLOCK(kq);
1995 			/*
1996 			 * We don't need to lock the list since we've
1997 			 * marked the knote as being in flux.
1998 			 */
1999 			*kevp = kn->kn_kevent;
2000 			knote_drop(kn, td);
2001 			KQ_LOCK(kq);
2002 			kn = NULL;
2003 		} else {
2004 			kn->kn_status |= KN_SCAN;
2005 			kn_enter_flux(kn);
2006 			KQ_UNLOCK(kq);
2007 			if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
2008 				KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
2009 			knl = kn_list_lock(kn);
2010 			if (kn->kn_fop->f_event(kn, 0) == 0) {
2011 				KQ_LOCK(kq);
2012 				KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
2013 				kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE |
2014 				    KN_SCAN);
2015 				kn_leave_flux(kn);
2016 				kq->kq_count--;
2017 				kn_list_unlock(knl);
2018 				influx = 1;
2019 				continue;
2020 			}
2021 			touch = (!kn->kn_fop->f_isfd &&
2022 			    kn->kn_fop->f_touch != NULL);
2023 			if (touch)
2024 				kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
2025 			else
2026 				*kevp = kn->kn_kevent;
2027 			KQ_LOCK(kq);
2028 			KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
2029 			if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
2030 				/*
2031 				 * Manually clear knotes who weren't
2032 				 * 'touch'ed.
2033 				 */
2034 				if (touch == 0 && kn->kn_flags & EV_CLEAR) {
2035 					kn->kn_data = 0;
2036 					kn->kn_fflags = 0;
2037 				}
2038 				if (kn->kn_flags & EV_DISPATCH)
2039 					kn->kn_status |= KN_DISABLED;
2040 				kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
2041 				kq->kq_count--;
2042 			} else
2043 				TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2044 
2045 			kn->kn_status &= ~KN_SCAN;
2046 			kn_leave_flux(kn);
2047 			kn_list_unlock(knl);
2048 			influx = 1;
2049 		}
2050 
2051 		/* we are returning a copy to the user */
2052 		kevp++;
2053 		nkev++;
2054 		count--;
2055 
2056 		if (nkev == KQ_NEVENTS) {
2057 			influx = 0;
2058 			KQ_UNLOCK_FLUX(kq);
2059 			error = k_ops->k_copyout(k_ops->arg, keva, nkev);
2060 			nkev = 0;
2061 			kevp = keva;
2062 			KQ_LOCK(kq);
2063 			if (error)
2064 				break;
2065 		}
2066 	}
2067 	TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
2068 done:
2069 	KQ_OWNED(kq);
2070 	KQ_UNLOCK_FLUX(kq);
2071 	knote_free(marker);
2072 done_nl:
2073 	KQ_NOTOWNED(kq);
2074 	if (nkev != 0)
2075 		error = k_ops->k_copyout(k_ops->arg, keva, nkev);
2076 	td->td_retval[0] = maxevents - count;
2077 	return (error);
2078 }
2079 
2080 /*ARGSUSED*/
2081 static int
2082 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
2083 	struct ucred *active_cred, struct thread *td)
2084 {
2085 	/*
2086 	 * Enabling sigio causes two major problems:
2087 	 * 1) infinite recursion:
2088 	 * Synopsys: kevent is being used to track signals and have FIOASYNC
2089 	 * set.  On receipt of a signal this will cause a kqueue to recurse
2090 	 * into itself over and over.  Sending the sigio causes the kqueue
2091 	 * to become ready, which in turn posts sigio again, forever.
2092 	 * Solution: this can be solved by setting a flag in the kqueue that
2093 	 * we have a SIGIO in progress.
2094 	 * 2) locking problems:
2095 	 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
2096 	 * us above the proc and pgrp locks.
2097 	 * Solution: Post a signal using an async mechanism, being sure to
2098 	 * record a generation count in the delivery so that we do not deliver
2099 	 * a signal to the wrong process.
2100 	 *
2101 	 * Note, these two mechanisms are somewhat mutually exclusive!
2102 	 */
2103 #if 0
2104 	struct kqueue *kq;
2105 
2106 	kq = fp->f_data;
2107 	switch (cmd) {
2108 	case FIOASYNC:
2109 		if (*(int *)data) {
2110 			kq->kq_state |= KQ_ASYNC;
2111 		} else {
2112 			kq->kq_state &= ~KQ_ASYNC;
2113 		}
2114 		return (0);
2115 
2116 	case FIOSETOWN:
2117 		return (fsetown(*(int *)data, &kq->kq_sigio));
2118 
2119 	case FIOGETOWN:
2120 		*(int *)data = fgetown(&kq->kq_sigio);
2121 		return (0);
2122 	}
2123 #endif
2124 
2125 	return (ENOTTY);
2126 }
2127 
2128 /*ARGSUSED*/
2129 static int
2130 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
2131 	struct thread *td)
2132 {
2133 	struct kqueue *kq;
2134 	int revents = 0;
2135 	int error;
2136 
2137 	if ((error = kqueue_acquire(fp, &kq)))
2138 		return POLLERR;
2139 
2140 	KQ_LOCK(kq);
2141 	if (events & (POLLIN | POLLRDNORM)) {
2142 		if (kq->kq_count) {
2143 			revents |= events & (POLLIN | POLLRDNORM);
2144 		} else {
2145 			selrecord(td, &kq->kq_sel);
2146 			if (SEL_WAITING(&kq->kq_sel))
2147 				kq->kq_state |= KQ_SEL;
2148 		}
2149 	}
2150 	kqueue_release(kq, 1);
2151 	KQ_UNLOCK(kq);
2152 	return (revents);
2153 }
2154 
2155 /*ARGSUSED*/
2156 static int
2157 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
2158 	struct thread *td)
2159 {
2160 
2161 	bzero((void *)st, sizeof *st);
2162 	/*
2163 	 * We no longer return kq_count because the unlocked value is useless.
2164 	 * If you spent all this time getting the count, why not spend your
2165 	 * syscall better by calling kevent?
2166 	 *
2167 	 * XXX - This is needed for libc_r.
2168 	 */
2169 	st->st_mode = S_IFIFO;
2170 	return (0);
2171 }
2172 
2173 static void
2174 kqueue_drain(struct kqueue *kq, struct thread *td)
2175 {
2176 	struct knote *kn;
2177 	int i;
2178 
2179 	KQ_LOCK(kq);
2180 
2181 	KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
2182 	    ("kqueue already closing"));
2183 	kq->kq_state |= KQ_CLOSING;
2184 	if (kq->kq_refcnt > 1)
2185 		msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
2186 
2187 	KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
2188 
2189 	KASSERT(knlist_empty(&kq->kq_sel.si_note),
2190 	    ("kqueue's knlist not empty"));
2191 
2192 	for (i = 0; i < kq->kq_knlistsize; i++) {
2193 		while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
2194 			if (kn_in_flux(kn)) {
2195 				kq->kq_state |= KQ_FLUXWAIT;
2196 				msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
2197 				continue;
2198 			}
2199 			kn_enter_flux(kn);
2200 			KQ_UNLOCK(kq);
2201 			knote_drop(kn, td);
2202 			KQ_LOCK(kq);
2203 		}
2204 	}
2205 	if (kq->kq_knhashmask != 0) {
2206 		for (i = 0; i <= kq->kq_knhashmask; i++) {
2207 			while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
2208 				if (kn_in_flux(kn)) {
2209 					kq->kq_state |= KQ_FLUXWAIT;
2210 					msleep(kq, &kq->kq_lock, PSOCK,
2211 					       "kqclo2", 0);
2212 					continue;
2213 				}
2214 				kn_enter_flux(kn);
2215 				KQ_UNLOCK(kq);
2216 				knote_drop(kn, td);
2217 				KQ_LOCK(kq);
2218 			}
2219 		}
2220 	}
2221 
2222 	if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
2223 		kq->kq_state |= KQ_TASKDRAIN;
2224 		msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
2225 	}
2226 
2227 	if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2228 		selwakeuppri(&kq->kq_sel, PSOCK);
2229 		if (!SEL_WAITING(&kq->kq_sel))
2230 			kq->kq_state &= ~KQ_SEL;
2231 	}
2232 
2233 	KQ_UNLOCK(kq);
2234 }
2235 
2236 static void
2237 kqueue_destroy(struct kqueue *kq)
2238 {
2239 
2240 	KASSERT(kq->kq_fdp == NULL,
2241 	    ("kqueue still attached to a file descriptor"));
2242 	seldrain(&kq->kq_sel);
2243 	knlist_destroy(&kq->kq_sel.si_note);
2244 	mtx_destroy(&kq->kq_lock);
2245 
2246 	if (kq->kq_knhash != NULL)
2247 		free(kq->kq_knhash, M_KQUEUE);
2248 	if (kq->kq_knlist != NULL)
2249 		free(kq->kq_knlist, M_KQUEUE);
2250 
2251 	funsetown(&kq->kq_sigio);
2252 }
2253 
2254 /*ARGSUSED*/
2255 static int
2256 kqueue_close(struct file *fp, struct thread *td)
2257 {
2258 	struct kqueue *kq = fp->f_data;
2259 	struct filedesc *fdp;
2260 	int error;
2261 	int filedesc_unlock;
2262 
2263 	if ((error = kqueue_acquire(fp, &kq)))
2264 		return error;
2265 	kqueue_drain(kq, td);
2266 
2267 	/*
2268 	 * We could be called due to the knote_drop() doing fdrop(),
2269 	 * called from kqueue_register().  In this case the global
2270 	 * lock is owned, and filedesc sx is locked before, to not
2271 	 * take the sleepable lock after non-sleepable.
2272 	 */
2273 	fdp = kq->kq_fdp;
2274 	kq->kq_fdp = NULL;
2275 	if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
2276 		FILEDESC_XLOCK(fdp);
2277 		filedesc_unlock = 1;
2278 	} else
2279 		filedesc_unlock = 0;
2280 	TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
2281 	if (filedesc_unlock)
2282 		FILEDESC_XUNLOCK(fdp);
2283 
2284 	kqueue_destroy(kq);
2285 	chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
2286 	crfree(kq->kq_cred);
2287 	free(kq, M_KQUEUE);
2288 	fp->f_data = NULL;
2289 
2290 	return (0);
2291 }
2292 
2293 static int
2294 kqueue_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
2295 {
2296 
2297 	kif->kf_type = KF_TYPE_KQUEUE;
2298 	return (0);
2299 }
2300 
2301 static void
2302 kqueue_wakeup(struct kqueue *kq)
2303 {
2304 	KQ_OWNED(kq);
2305 
2306 	if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
2307 		kq->kq_state &= ~KQ_SLEEP;
2308 		wakeup(kq);
2309 	}
2310 	if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2311 		selwakeuppri(&kq->kq_sel, PSOCK);
2312 		if (!SEL_WAITING(&kq->kq_sel))
2313 			kq->kq_state &= ~KQ_SEL;
2314 	}
2315 	if (!knlist_empty(&kq->kq_sel.si_note))
2316 		kqueue_schedtask(kq);
2317 	if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
2318 		pgsigio(&kq->kq_sigio, SIGIO, 0);
2319 	}
2320 }
2321 
2322 /*
2323  * Walk down a list of knotes, activating them if their event has triggered.
2324  *
2325  * There is a possibility to optimize in the case of one kq watching another.
2326  * Instead of scheduling a task to wake it up, you could pass enough state
2327  * down the chain to make up the parent kqueue.  Make this code functional
2328  * first.
2329  */
2330 void
2331 knote(struct knlist *list, long hint, int lockflags)
2332 {
2333 	struct kqueue *kq;
2334 	struct knote *kn, *tkn;
2335 	int error;
2336 
2337 	if (list == NULL)
2338 		return;
2339 
2340 	KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
2341 
2342 	if ((lockflags & KNF_LISTLOCKED) == 0)
2343 		list->kl_lock(list->kl_lockarg);
2344 
2345 	/*
2346 	 * If we unlock the list lock (and enter influx), we can
2347 	 * eliminate the kqueue scheduling, but this will introduce
2348 	 * four lock/unlock's for each knote to test.  Also, marker
2349 	 * would be needed to keep iteration position, since filters
2350 	 * or other threads could remove events.
2351 	 */
2352 	SLIST_FOREACH_SAFE(kn, &list->kl_list, kn_selnext, tkn) {
2353 		kq = kn->kn_kq;
2354 		KQ_LOCK(kq);
2355 		if (kn_in_flux(kn) && (kn->kn_status & KN_SCAN) == 0) {
2356 			/*
2357 			 * Do not process the influx notes, except for
2358 			 * the influx coming from the kq unlock in the
2359 			 * kqueue_scan().  In the later case, we do
2360 			 * not interfere with the scan, since the code
2361 			 * fragment in kqueue_scan() locks the knlist,
2362 			 * and cannot proceed until we finished.
2363 			 */
2364 			KQ_UNLOCK(kq);
2365 		} else if ((lockflags & KNF_NOKQLOCK) != 0) {
2366 			kn_enter_flux(kn);
2367 			KQ_UNLOCK(kq);
2368 			error = kn->kn_fop->f_event(kn, hint);
2369 			KQ_LOCK(kq);
2370 			kn_leave_flux(kn);
2371 			if (error)
2372 				KNOTE_ACTIVATE(kn, 1);
2373 			KQ_UNLOCK_FLUX(kq);
2374 		} else {
2375 			if (kn->kn_fop->f_event(kn, hint))
2376 				KNOTE_ACTIVATE(kn, 1);
2377 			KQ_UNLOCK(kq);
2378 		}
2379 	}
2380 	if ((lockflags & KNF_LISTLOCKED) == 0)
2381 		list->kl_unlock(list->kl_lockarg);
2382 }
2383 
2384 /*
2385  * add a knote to a knlist
2386  */
2387 void
2388 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
2389 {
2390 
2391 	KNL_ASSERT_LOCK(knl, islocked);
2392 	KQ_NOTOWNED(kn->kn_kq);
2393 	KASSERT(kn_in_flux(kn), ("knote %p not in flux", kn));
2394 	KASSERT((kn->kn_status & KN_DETACHED) != 0,
2395 	    ("knote %p was not detached", kn));
2396 	if (!islocked)
2397 		knl->kl_lock(knl->kl_lockarg);
2398 	SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
2399 	if (!islocked)
2400 		knl->kl_unlock(knl->kl_lockarg);
2401 	KQ_LOCK(kn->kn_kq);
2402 	kn->kn_knlist = knl;
2403 	kn->kn_status &= ~KN_DETACHED;
2404 	KQ_UNLOCK(kn->kn_kq);
2405 }
2406 
2407 static void
2408 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked,
2409     int kqislocked)
2410 {
2411 
2412 	KASSERT(!kqislocked || knlislocked, ("kq locked w/o knl locked"));
2413 	KNL_ASSERT_LOCK(knl, knlislocked);
2414 	mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
2415 	KASSERT(kqislocked || kn_in_flux(kn), ("knote %p not in flux", kn));
2416 	KASSERT((kn->kn_status & KN_DETACHED) == 0,
2417 	    ("knote %p was already detached", kn));
2418 	if (!knlislocked)
2419 		knl->kl_lock(knl->kl_lockarg);
2420 	SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
2421 	kn->kn_knlist = NULL;
2422 	if (!knlislocked)
2423 		kn_list_unlock(knl);
2424 	if (!kqislocked)
2425 		KQ_LOCK(kn->kn_kq);
2426 	kn->kn_status |= KN_DETACHED;
2427 	if (!kqislocked)
2428 		KQ_UNLOCK(kn->kn_kq);
2429 }
2430 
2431 /*
2432  * remove knote from the specified knlist
2433  */
2434 void
2435 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
2436 {
2437 
2438 	knlist_remove_kq(knl, kn, islocked, 0);
2439 }
2440 
2441 int
2442 knlist_empty(struct knlist *knl)
2443 {
2444 
2445 	KNL_ASSERT_LOCKED(knl);
2446 	return (SLIST_EMPTY(&knl->kl_list));
2447 }
2448 
2449 static struct mtx knlist_lock;
2450 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2451     MTX_DEF);
2452 static void knlist_mtx_lock(void *arg);
2453 static void knlist_mtx_unlock(void *arg);
2454 
2455 static void
2456 knlist_mtx_lock(void *arg)
2457 {
2458 
2459 	mtx_lock((struct mtx *)arg);
2460 }
2461 
2462 static void
2463 knlist_mtx_unlock(void *arg)
2464 {
2465 
2466 	mtx_unlock((struct mtx *)arg);
2467 }
2468 
2469 static void
2470 knlist_mtx_assert_lock(void *arg, int what)
2471 {
2472 
2473 	if (what == LA_LOCKED)
2474 		mtx_assert((struct mtx *)arg, MA_OWNED);
2475 	else
2476 		mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2477 }
2478 
2479 static void
2480 knlist_rw_rlock(void *arg)
2481 {
2482 
2483 	rw_rlock((struct rwlock *)arg);
2484 }
2485 
2486 static void
2487 knlist_rw_runlock(void *arg)
2488 {
2489 
2490 	rw_runlock((struct rwlock *)arg);
2491 }
2492 
2493 static void
2494 knlist_rw_assert_lock(void *arg, int what)
2495 {
2496 
2497 	if (what == LA_LOCKED)
2498 		rw_assert((struct rwlock *)arg, RA_LOCKED);
2499 	else
2500 		rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2501 }
2502 
2503 void
2504 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2505     void (*kl_unlock)(void *),
2506     void (*kl_assert_lock)(void *, int))
2507 {
2508 
2509 	if (lock == NULL)
2510 		knl->kl_lockarg = &knlist_lock;
2511 	else
2512 		knl->kl_lockarg = lock;
2513 
2514 	if (kl_lock == NULL)
2515 		knl->kl_lock = knlist_mtx_lock;
2516 	else
2517 		knl->kl_lock = kl_lock;
2518 	if (kl_unlock == NULL)
2519 		knl->kl_unlock = knlist_mtx_unlock;
2520 	else
2521 		knl->kl_unlock = kl_unlock;
2522 	if (kl_assert_lock == NULL)
2523 		knl->kl_assert_lock = knlist_mtx_assert_lock;
2524 	else
2525 		knl->kl_assert_lock = kl_assert_lock;
2526 
2527 	knl->kl_autodestroy = 0;
2528 	SLIST_INIT(&knl->kl_list);
2529 }
2530 
2531 void
2532 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2533 {
2534 
2535 	knlist_init(knl, lock, NULL, NULL, NULL);
2536 }
2537 
2538 struct knlist *
2539 knlist_alloc(struct mtx *lock)
2540 {
2541 	struct knlist *knl;
2542 
2543 	knl = malloc(sizeof(struct knlist), M_KQUEUE, M_WAITOK);
2544 	knlist_init_mtx(knl, lock);
2545 	return (knl);
2546 }
2547 
2548 void
2549 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2550 {
2551 
2552 	knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2553 	    knlist_rw_assert_lock);
2554 }
2555 
2556 void
2557 knlist_destroy(struct knlist *knl)
2558 {
2559 
2560 	KASSERT(KNLIST_EMPTY(knl),
2561 	    ("destroying knlist %p with knotes on it", knl));
2562 }
2563 
2564 void
2565 knlist_detach(struct knlist *knl)
2566 {
2567 
2568 	KNL_ASSERT_LOCKED(knl);
2569 	knl->kl_autodestroy = 1;
2570 	if (knlist_empty(knl)) {
2571 		knlist_destroy(knl);
2572 		free(knl, M_KQUEUE);
2573 	}
2574 }
2575 
2576 /*
2577  * Even if we are locked, we may need to drop the lock to allow any influx
2578  * knotes time to "settle".
2579  */
2580 void
2581 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2582 {
2583 	struct knote *kn, *kn2;
2584 	struct kqueue *kq;
2585 
2586 	KASSERT(!knl->kl_autodestroy, ("cleardel for autodestroy %p", knl));
2587 	if (islocked)
2588 		KNL_ASSERT_LOCKED(knl);
2589 	else {
2590 		KNL_ASSERT_UNLOCKED(knl);
2591 again:		/* need to reacquire lock since we have dropped it */
2592 		knl->kl_lock(knl->kl_lockarg);
2593 	}
2594 
2595 	SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2596 		kq = kn->kn_kq;
2597 		KQ_LOCK(kq);
2598 		if (kn_in_flux(kn)) {
2599 			KQ_UNLOCK(kq);
2600 			continue;
2601 		}
2602 		knlist_remove_kq(knl, kn, 1, 1);
2603 		if (killkn) {
2604 			kn_enter_flux(kn);
2605 			KQ_UNLOCK(kq);
2606 			knote_drop_detached(kn, td);
2607 		} else {
2608 			/* Make sure cleared knotes disappear soon */
2609 			kn->kn_flags |= EV_EOF | EV_ONESHOT;
2610 			KQ_UNLOCK(kq);
2611 		}
2612 		kq = NULL;
2613 	}
2614 
2615 	if (!SLIST_EMPTY(&knl->kl_list)) {
2616 		/* there are still in flux knotes remaining */
2617 		kn = SLIST_FIRST(&knl->kl_list);
2618 		kq = kn->kn_kq;
2619 		KQ_LOCK(kq);
2620 		KASSERT(kn_in_flux(kn), ("knote removed w/o list lock"));
2621 		knl->kl_unlock(knl->kl_lockarg);
2622 		kq->kq_state |= KQ_FLUXWAIT;
2623 		msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2624 		kq = NULL;
2625 		goto again;
2626 	}
2627 
2628 	if (islocked)
2629 		KNL_ASSERT_LOCKED(knl);
2630 	else {
2631 		knl->kl_unlock(knl->kl_lockarg);
2632 		KNL_ASSERT_UNLOCKED(knl);
2633 	}
2634 }
2635 
2636 /*
2637  * Remove all knotes referencing a specified fd must be called with FILEDESC
2638  * lock.  This prevents a race where a new fd comes along and occupies the
2639  * entry and we attach a knote to the fd.
2640  */
2641 void
2642 knote_fdclose(struct thread *td, int fd)
2643 {
2644 	struct filedesc *fdp = td->td_proc->p_fd;
2645 	struct kqueue *kq;
2646 	struct knote *kn;
2647 	int influx;
2648 
2649 	FILEDESC_XLOCK_ASSERT(fdp);
2650 
2651 	/*
2652 	 * We shouldn't have to worry about new kevents appearing on fd
2653 	 * since filedesc is locked.
2654 	 */
2655 	TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2656 		KQ_LOCK(kq);
2657 
2658 again:
2659 		influx = 0;
2660 		while (kq->kq_knlistsize > fd &&
2661 		    (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2662 			if (kn_in_flux(kn)) {
2663 				/* someone else might be waiting on our knote */
2664 				if (influx)
2665 					wakeup(kq);
2666 				kq->kq_state |= KQ_FLUXWAIT;
2667 				msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2668 				goto again;
2669 			}
2670 			kn_enter_flux(kn);
2671 			KQ_UNLOCK(kq);
2672 			influx = 1;
2673 			knote_drop(kn, td);
2674 			KQ_LOCK(kq);
2675 		}
2676 		KQ_UNLOCK_FLUX(kq);
2677 	}
2678 }
2679 
2680 static int
2681 knote_attach(struct knote *kn, struct kqueue *kq)
2682 {
2683 	struct klist *list;
2684 
2685 	KASSERT(kn_in_flux(kn), ("knote %p not marked influx", kn));
2686 	KQ_OWNED(kq);
2687 
2688 	if ((kq->kq_state & KQ_CLOSING) != 0)
2689 		return (EBADF);
2690 	if (kn->kn_fop->f_isfd) {
2691 		if (kn->kn_id >= kq->kq_knlistsize)
2692 			return (ENOMEM);
2693 		list = &kq->kq_knlist[kn->kn_id];
2694 	} else {
2695 		if (kq->kq_knhash == NULL)
2696 			return (ENOMEM);
2697 		list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2698 	}
2699 	SLIST_INSERT_HEAD(list, kn, kn_link);
2700 	return (0);
2701 }
2702 
2703 static void
2704 knote_drop(struct knote *kn, struct thread *td)
2705 {
2706 
2707 	if ((kn->kn_status & KN_DETACHED) == 0)
2708 		kn->kn_fop->f_detach(kn);
2709 	knote_drop_detached(kn, td);
2710 }
2711 
2712 static void
2713 knote_drop_detached(struct knote *kn, struct thread *td)
2714 {
2715 	struct kqueue *kq;
2716 	struct klist *list;
2717 
2718 	kq = kn->kn_kq;
2719 
2720 	KASSERT((kn->kn_status & KN_DETACHED) != 0,
2721 	    ("knote %p still attached", kn));
2722 	KQ_NOTOWNED(kq);
2723 
2724 	KQ_LOCK(kq);
2725 	KASSERT(kn->kn_influx == 1,
2726 	    ("knote_drop called on %p with influx %d", kn, kn->kn_influx));
2727 
2728 	if (kn->kn_fop->f_isfd)
2729 		list = &kq->kq_knlist[kn->kn_id];
2730 	else
2731 		list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2732 
2733 	if (!SLIST_EMPTY(list))
2734 		SLIST_REMOVE(list, kn, knote, kn_link);
2735 	if (kn->kn_status & KN_QUEUED)
2736 		knote_dequeue(kn);
2737 	KQ_UNLOCK_FLUX(kq);
2738 
2739 	if (kn->kn_fop->f_isfd) {
2740 		fdrop(kn->kn_fp, td);
2741 		kn->kn_fp = NULL;
2742 	}
2743 	kqueue_fo_release(kn->kn_kevent.filter);
2744 	kn->kn_fop = NULL;
2745 	knote_free(kn);
2746 }
2747 
2748 static void
2749 knote_enqueue(struct knote *kn)
2750 {
2751 	struct kqueue *kq = kn->kn_kq;
2752 
2753 	KQ_OWNED(kn->kn_kq);
2754 	KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2755 
2756 	TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2757 	kn->kn_status |= KN_QUEUED;
2758 	kq->kq_count++;
2759 	kqueue_wakeup(kq);
2760 }
2761 
2762 static void
2763 knote_dequeue(struct knote *kn)
2764 {
2765 	struct kqueue *kq = kn->kn_kq;
2766 
2767 	KQ_OWNED(kn->kn_kq);
2768 	KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2769 
2770 	TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2771 	kn->kn_status &= ~KN_QUEUED;
2772 	kq->kq_count--;
2773 }
2774 
2775 static void
2776 knote_init(void)
2777 {
2778 
2779 	knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2780 	    NULL, NULL, UMA_ALIGN_PTR, 0);
2781 }
2782 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2783 
2784 static struct knote *
2785 knote_alloc(int mflag)
2786 {
2787 
2788 	return (uma_zalloc(knote_zone, mflag | M_ZERO));
2789 }
2790 
2791 static void
2792 knote_free(struct knote *kn)
2793 {
2794 
2795 	uma_zfree(knote_zone, kn);
2796 }
2797 
2798 /*
2799  * Register the kev w/ the kq specified by fd.
2800  */
2801 int
2802 kqfd_register(int fd, struct kevent *kev, struct thread *td, int mflag)
2803 {
2804 	struct kqueue *kq;
2805 	struct file *fp;
2806 	cap_rights_t rights;
2807 	int error;
2808 
2809 	error = fget(td, fd, cap_rights_init_one(&rights, CAP_KQUEUE_CHANGE),
2810 	    &fp);
2811 	if (error != 0)
2812 		return (error);
2813 	if ((error = kqueue_acquire(fp, &kq)) != 0)
2814 		goto noacquire;
2815 
2816 	error = kqueue_register(kq, kev, td, mflag);
2817 	kqueue_release(kq, 0);
2818 
2819 noacquire:
2820 	fdrop(fp, td);
2821 	return (error);
2822 }
2823