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