xref: /freebsd/sys/kern/kern_event.c (revision 50d3286d9dbd7bec7aef9c7ac76eaa690a760bec)
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 	error = fget(td, fd, cap_rights_init(&rights, CAP_POST_EVENT), &fp);
859 	if (error != 0)
860 		return (error);
861 	if ((error = kqueue_acquire(fp, &kq)) != 0)
862 		goto done_norel;
863 
864 	nerrors = 0;
865 
866 	while (nchanges > 0) {
867 		n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
868 		error = k_ops->k_copyin(k_ops->arg, keva, n);
869 		if (error)
870 			goto done;
871 		changes = keva;
872 		for (i = 0; i < n; i++) {
873 			kevp = &changes[i];
874 			if (!kevp->filter)
875 				continue;
876 			kevp->flags &= ~EV_SYSFLAGS;
877 			error = kqueue_register(kq, kevp, td, 1);
878 			if (error || (kevp->flags & EV_RECEIPT)) {
879 				if (nevents != 0) {
880 					kevp->flags = EV_ERROR;
881 					kevp->data = error;
882 					(void) k_ops->k_copyout(k_ops->arg,
883 					    kevp, 1);
884 					nevents--;
885 					nerrors++;
886 				} else {
887 					goto done;
888 				}
889 			}
890 		}
891 		nchanges -= n;
892 	}
893 	if (nerrors) {
894 		td->td_retval[0] = nerrors;
895 		error = 0;
896 		goto done;
897 	}
898 
899 	error = kqueue_scan(kq, nevents, k_ops, timeout, keva, td);
900 done:
901 	kqueue_release(kq, 0);
902 done_norel:
903 	fdrop(fp, td);
904 	return (error);
905 }
906 
907 int
908 kqueue_add_filteropts(int filt, struct filterops *filtops)
909 {
910 	int error;
911 
912 	error = 0;
913 	if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
914 		printf(
915 "trying to add a filterop that is out of range: %d is beyond %d\n",
916 		    ~filt, EVFILT_SYSCOUNT);
917 		return EINVAL;
918 	}
919 	mtx_lock(&filterops_lock);
920 	if (sysfilt_ops[~filt].for_fop != &null_filtops &&
921 	    sysfilt_ops[~filt].for_fop != NULL)
922 		error = EEXIST;
923 	else {
924 		sysfilt_ops[~filt].for_fop = filtops;
925 		sysfilt_ops[~filt].for_refcnt = 0;
926 	}
927 	mtx_unlock(&filterops_lock);
928 
929 	return (error);
930 }
931 
932 int
933 kqueue_del_filteropts(int filt)
934 {
935 	int error;
936 
937 	error = 0;
938 	if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
939 		return EINVAL;
940 
941 	mtx_lock(&filterops_lock);
942 	if (sysfilt_ops[~filt].for_fop == &null_filtops ||
943 	    sysfilt_ops[~filt].for_fop == NULL)
944 		error = EINVAL;
945 	else if (sysfilt_ops[~filt].for_refcnt != 0)
946 		error = EBUSY;
947 	else {
948 		sysfilt_ops[~filt].for_fop = &null_filtops;
949 		sysfilt_ops[~filt].for_refcnt = 0;
950 	}
951 	mtx_unlock(&filterops_lock);
952 
953 	return error;
954 }
955 
956 static struct filterops *
957 kqueue_fo_find(int filt)
958 {
959 
960 	if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
961 		return NULL;
962 
963 	mtx_lock(&filterops_lock);
964 	sysfilt_ops[~filt].for_refcnt++;
965 	if (sysfilt_ops[~filt].for_fop == NULL)
966 		sysfilt_ops[~filt].for_fop = &null_filtops;
967 	mtx_unlock(&filterops_lock);
968 
969 	return sysfilt_ops[~filt].for_fop;
970 }
971 
972 static void
973 kqueue_fo_release(int filt)
974 {
975 
976 	if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
977 		return;
978 
979 	mtx_lock(&filterops_lock);
980 	KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
981 	    ("filter object refcount not valid on release"));
982 	sysfilt_ops[~filt].for_refcnt--;
983 	mtx_unlock(&filterops_lock);
984 }
985 
986 /*
987  * A ref to kq (obtained via kqueue_acquire) must be held.  waitok will
988  * influence if memory allocation should wait.  Make sure it is 0 if you
989  * hold any mutexes.
990  */
991 static int
992 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
993 {
994 	struct filterops *fops;
995 	struct file *fp;
996 	struct knote *kn, *tkn;
997 	cap_rights_t rights;
998 	int error, filt, event;
999 	int haskqglobal, filedesc_unlock;
1000 
1001 	fp = NULL;
1002 	kn = NULL;
1003 	error = 0;
1004 	haskqglobal = 0;
1005 	filedesc_unlock = 0;
1006 
1007 	filt = kev->filter;
1008 	fops = kqueue_fo_find(filt);
1009 	if (fops == NULL)
1010 		return EINVAL;
1011 
1012 	tkn = knote_alloc(waitok);		/* prevent waiting with locks */
1013 
1014 findkn:
1015 	if (fops->f_isfd) {
1016 		KASSERT(td != NULL, ("td is NULL"));
1017 		error = fget(td, kev->ident,
1018 		    cap_rights_init(&rights, CAP_POLL_EVENT), &fp);
1019 		if (error)
1020 			goto done;
1021 
1022 		if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1023 		    kev->ident, 0) != 0) {
1024 			/* try again */
1025 			fdrop(fp, td);
1026 			fp = NULL;
1027 			error = kqueue_expand(kq, fops, kev->ident, waitok);
1028 			if (error)
1029 				goto done;
1030 			goto findkn;
1031 		}
1032 
1033 		if (fp->f_type == DTYPE_KQUEUE) {
1034 			/*
1035 			 * if we add some inteligence about what we are doing,
1036 			 * we should be able to support events on ourselves.
1037 			 * We need to know when we are doing this to prevent
1038 			 * getting both the knlist lock and the kq lock since
1039 			 * they are the same thing.
1040 			 */
1041 			if (fp->f_data == kq) {
1042 				error = EINVAL;
1043 				goto done;
1044 			}
1045 
1046 			/*
1047 			 * Pre-lock the filedesc before the global
1048 			 * lock mutex, see the comment in
1049 			 * kqueue_close().
1050 			 */
1051 			FILEDESC_XLOCK(td->td_proc->p_fd);
1052 			filedesc_unlock = 1;
1053 			KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1054 		}
1055 
1056 		KQ_LOCK(kq);
1057 		if (kev->ident < kq->kq_knlistsize) {
1058 			SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1059 				if (kev->filter == kn->kn_filter)
1060 					break;
1061 		}
1062 	} else {
1063 		if ((kev->flags & EV_ADD) == EV_ADD)
1064 			kqueue_expand(kq, fops, kev->ident, waitok);
1065 
1066 		KQ_LOCK(kq);
1067 		if (kq->kq_knhashmask != 0) {
1068 			struct klist *list;
1069 
1070 			list = &kq->kq_knhash[
1071 			    KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1072 			SLIST_FOREACH(kn, list, kn_link)
1073 				if (kev->ident == kn->kn_id &&
1074 				    kev->filter == kn->kn_filter)
1075 					break;
1076 		}
1077 	}
1078 
1079 	/* knote is in the process of changing, wait for it to stablize. */
1080 	if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1081 		KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1082 		if (filedesc_unlock) {
1083 			FILEDESC_XUNLOCK(td->td_proc->p_fd);
1084 			filedesc_unlock = 0;
1085 		}
1086 		kq->kq_state |= KQ_FLUXWAIT;
1087 		msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1088 		if (fp != NULL) {
1089 			fdrop(fp, td);
1090 			fp = NULL;
1091 		}
1092 		goto findkn;
1093 	}
1094 
1095 	/*
1096 	 * kn now contains the matching knote, or NULL if no match
1097 	 */
1098 	if (kn == NULL) {
1099 		if (kev->flags & EV_ADD) {
1100 			kn = tkn;
1101 			tkn = NULL;
1102 			if (kn == NULL) {
1103 				KQ_UNLOCK(kq);
1104 				error = ENOMEM;
1105 				goto done;
1106 			}
1107 			kn->kn_fp = fp;
1108 			kn->kn_kq = kq;
1109 			kn->kn_fop = fops;
1110 			/*
1111 			 * apply reference counts to knote structure, and
1112 			 * do not release it at the end of this routine.
1113 			 */
1114 			fops = NULL;
1115 			fp = NULL;
1116 
1117 			kn->kn_sfflags = kev->fflags;
1118 			kn->kn_sdata = kev->data;
1119 			kev->fflags = 0;
1120 			kev->data = 0;
1121 			kn->kn_kevent = *kev;
1122 			kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1123 			    EV_ENABLE | EV_DISABLE);
1124 			kn->kn_status = KN_INFLUX|KN_DETACHED;
1125 
1126 			error = knote_attach(kn, kq);
1127 			KQ_UNLOCK(kq);
1128 			if (error != 0) {
1129 				tkn = kn;
1130 				goto done;
1131 			}
1132 
1133 			if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1134 				knote_drop(kn, td);
1135 				goto done;
1136 			}
1137 			KN_LIST_LOCK(kn);
1138 			goto done_ev_add;
1139 		} else {
1140 			/* No matching knote and the EV_ADD flag is not set. */
1141 			KQ_UNLOCK(kq);
1142 			error = ENOENT;
1143 			goto done;
1144 		}
1145 	}
1146 
1147 	if (kev->flags & EV_DELETE) {
1148 		kn->kn_status |= KN_INFLUX;
1149 		KQ_UNLOCK(kq);
1150 		if (!(kn->kn_status & KN_DETACHED))
1151 			kn->kn_fop->f_detach(kn);
1152 		knote_drop(kn, td);
1153 		goto done;
1154 	}
1155 
1156 	/*
1157 	 * The user may change some filter values after the initial EV_ADD,
1158 	 * but doing so will not reset any filter which has already been
1159 	 * triggered.
1160 	 */
1161 	kn->kn_status |= KN_INFLUX;
1162 	KQ_UNLOCK(kq);
1163 	KN_LIST_LOCK(kn);
1164 	kn->kn_kevent.udata = kev->udata;
1165 	if (!fops->f_isfd && fops->f_touch != NULL) {
1166 		fops->f_touch(kn, kev, EVENT_REGISTER);
1167 	} else {
1168 		kn->kn_sfflags = kev->fflags;
1169 		kn->kn_sdata = kev->data;
1170 	}
1171 
1172 	/*
1173 	 * We can get here with kn->kn_knlist == NULL.  This can happen when
1174 	 * the initial attach event decides that the event is "completed"
1175 	 * already.  i.e. filt_procattach is called on a zombie process.  It
1176 	 * will call filt_proc which will remove it from the list, and NULL
1177 	 * kn_knlist.
1178 	 */
1179 done_ev_add:
1180 	event = kn->kn_fop->f_event(kn, 0);
1181 	KQ_LOCK(kq);
1182 	if (event)
1183 		KNOTE_ACTIVATE(kn, 1);
1184 	kn->kn_status &= ~KN_INFLUX;
1185 	KN_LIST_UNLOCK(kn);
1186 
1187 	if ((kev->flags & EV_DISABLE) &&
1188 	    ((kn->kn_status & KN_DISABLED) == 0)) {
1189 		kn->kn_status |= KN_DISABLED;
1190 	}
1191 
1192 	if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
1193 		kn->kn_status &= ~KN_DISABLED;
1194 		if ((kn->kn_status & KN_ACTIVE) &&
1195 		    ((kn->kn_status & KN_QUEUED) == 0))
1196 			knote_enqueue(kn);
1197 	}
1198 	KQ_UNLOCK_FLUX(kq);
1199 
1200 done:
1201 	KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1202 	if (filedesc_unlock)
1203 		FILEDESC_XUNLOCK(td->td_proc->p_fd);
1204 	if (fp != NULL)
1205 		fdrop(fp, td);
1206 	if (tkn != NULL)
1207 		knote_free(tkn);
1208 	if (fops != NULL)
1209 		kqueue_fo_release(filt);
1210 	return (error);
1211 }
1212 
1213 static int
1214 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1215 {
1216 	int error;
1217 	struct kqueue *kq;
1218 
1219 	error = 0;
1220 
1221 	kq = fp->f_data;
1222 	if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1223 		return (EBADF);
1224 	*kqp = kq;
1225 	KQ_LOCK(kq);
1226 	if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1227 		KQ_UNLOCK(kq);
1228 		return (EBADF);
1229 	}
1230 	kq->kq_refcnt++;
1231 	KQ_UNLOCK(kq);
1232 
1233 	return error;
1234 }
1235 
1236 static void
1237 kqueue_release(struct kqueue *kq, int locked)
1238 {
1239 	if (locked)
1240 		KQ_OWNED(kq);
1241 	else
1242 		KQ_LOCK(kq);
1243 	kq->kq_refcnt--;
1244 	if (kq->kq_refcnt == 1)
1245 		wakeup(&kq->kq_refcnt);
1246 	if (!locked)
1247 		KQ_UNLOCK(kq);
1248 }
1249 
1250 static void
1251 kqueue_schedtask(struct kqueue *kq)
1252 {
1253 
1254 	KQ_OWNED(kq);
1255 	KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1256 	    ("scheduling kqueue task while draining"));
1257 
1258 	if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1259 		taskqueue_enqueue(taskqueue_kqueue, &kq->kq_task);
1260 		kq->kq_state |= KQ_TASKSCHED;
1261 	}
1262 }
1263 
1264 /*
1265  * Expand the kq to make sure we have storage for fops/ident pair.
1266  *
1267  * Return 0 on success (or no work necessary), return errno on failure.
1268  *
1269  * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1270  * If kqueue_register is called from a non-fd context, there usually/should
1271  * be no locks held.
1272  */
1273 static int
1274 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1275 	int waitok)
1276 {
1277 	struct klist *list, *tmp_knhash, *to_free;
1278 	u_long tmp_knhashmask;
1279 	int size;
1280 	int fd;
1281 	int mflag = waitok ? M_WAITOK : M_NOWAIT;
1282 
1283 	KQ_NOTOWNED(kq);
1284 
1285 	to_free = NULL;
1286 	if (fops->f_isfd) {
1287 		fd = ident;
1288 		if (kq->kq_knlistsize <= fd) {
1289 			size = kq->kq_knlistsize;
1290 			while (size <= fd)
1291 				size += KQEXTENT;
1292 			list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1293 			if (list == NULL)
1294 				return ENOMEM;
1295 			KQ_LOCK(kq);
1296 			if (kq->kq_knlistsize > fd) {
1297 				to_free = list;
1298 				list = NULL;
1299 			} else {
1300 				if (kq->kq_knlist != NULL) {
1301 					bcopy(kq->kq_knlist, list,
1302 					    kq->kq_knlistsize * sizeof(*list));
1303 					to_free = kq->kq_knlist;
1304 					kq->kq_knlist = NULL;
1305 				}
1306 				bzero((caddr_t)list +
1307 				    kq->kq_knlistsize * sizeof(*list),
1308 				    (size - kq->kq_knlistsize) * sizeof(*list));
1309 				kq->kq_knlistsize = size;
1310 				kq->kq_knlist = list;
1311 			}
1312 			KQ_UNLOCK(kq);
1313 		}
1314 	} else {
1315 		if (kq->kq_knhashmask == 0) {
1316 			tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1317 			    &tmp_knhashmask);
1318 			if (tmp_knhash == NULL)
1319 				return ENOMEM;
1320 			KQ_LOCK(kq);
1321 			if (kq->kq_knhashmask == 0) {
1322 				kq->kq_knhash = tmp_knhash;
1323 				kq->kq_knhashmask = tmp_knhashmask;
1324 			} else {
1325 				to_free = tmp_knhash;
1326 			}
1327 			KQ_UNLOCK(kq);
1328 		}
1329 	}
1330 	free(to_free, M_KQUEUE);
1331 
1332 	KQ_NOTOWNED(kq);
1333 	return 0;
1334 }
1335 
1336 static void
1337 kqueue_task(void *arg, int pending)
1338 {
1339 	struct kqueue *kq;
1340 	int haskqglobal;
1341 
1342 	haskqglobal = 0;
1343 	kq = arg;
1344 
1345 	KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1346 	KQ_LOCK(kq);
1347 
1348 	KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1349 
1350 	kq->kq_state &= ~KQ_TASKSCHED;
1351 	if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1352 		wakeup(&kq->kq_state);
1353 	}
1354 	KQ_UNLOCK(kq);
1355 	KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1356 }
1357 
1358 /*
1359  * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1360  * We treat KN_MARKER knotes as if they are INFLUX.
1361  */
1362 static int
1363 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1364     const struct timespec *tsp, struct kevent *keva, struct thread *td)
1365 {
1366 	struct kevent *kevp;
1367 	struct knote *kn, *marker;
1368 	sbintime_t asbt, rsbt;
1369 	int count, error, haskqglobal, influx, nkev, touch;
1370 
1371 	count = maxevents;
1372 	nkev = 0;
1373 	error = 0;
1374 	haskqglobal = 0;
1375 
1376 	if (maxevents == 0)
1377 		goto done_nl;
1378 
1379 	rsbt = 0;
1380 	if (tsp != NULL) {
1381 		if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1382 		    tsp->tv_nsec >= 1000000000) {
1383 			error = EINVAL;
1384 			goto done_nl;
1385 		}
1386 		if (timespecisset(tsp)) {
1387 			if (tsp->tv_sec <= INT32_MAX) {
1388 				rsbt = tstosbt(*tsp);
1389 				if (TIMESEL(&asbt, rsbt))
1390 					asbt += tc_tick_sbt;
1391 				if (asbt <= INT64_MAX - rsbt)
1392 					asbt += rsbt;
1393 				else
1394 					asbt = 0;
1395 				rsbt >>= tc_precexp;
1396 			} else
1397 				asbt = 0;
1398 		} else
1399 			asbt = -1;
1400 	} else
1401 		asbt = 0;
1402 	marker = knote_alloc(1);
1403 	if (marker == NULL) {
1404 		error = ENOMEM;
1405 		goto done_nl;
1406 	}
1407 	marker->kn_status = KN_MARKER;
1408 	KQ_LOCK(kq);
1409 
1410 retry:
1411 	kevp = keva;
1412 	if (kq->kq_count == 0) {
1413 		if (asbt == -1) {
1414 			error = EWOULDBLOCK;
1415 		} else {
1416 			kq->kq_state |= KQ_SLEEP;
1417 			error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1418 			    "kqread", asbt, rsbt, C_ABSOLUTE);
1419 		}
1420 		if (error == 0)
1421 			goto retry;
1422 		/* don't restart after signals... */
1423 		if (error == ERESTART)
1424 			error = EINTR;
1425 		else if (error == EWOULDBLOCK)
1426 			error = 0;
1427 		goto done;
1428 	}
1429 
1430 	TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1431 	influx = 0;
1432 	while (count) {
1433 		KQ_OWNED(kq);
1434 		kn = TAILQ_FIRST(&kq->kq_head);
1435 
1436 		if ((kn->kn_status == KN_MARKER && kn != marker) ||
1437 		    (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1438 			if (influx) {
1439 				influx = 0;
1440 				KQ_FLUX_WAKEUP(kq);
1441 			}
1442 			kq->kq_state |= KQ_FLUXWAIT;
1443 			error = msleep(kq, &kq->kq_lock, PSOCK,
1444 			    "kqflxwt", 0);
1445 			continue;
1446 		}
1447 
1448 		TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1449 		if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1450 			kn->kn_status &= ~KN_QUEUED;
1451 			kq->kq_count--;
1452 			continue;
1453 		}
1454 		if (kn == marker) {
1455 			KQ_FLUX_WAKEUP(kq);
1456 			if (count == maxevents)
1457 				goto retry;
1458 			goto done;
1459 		}
1460 		KASSERT((kn->kn_status & KN_INFLUX) == 0,
1461 		    ("KN_INFLUX set when not suppose to be"));
1462 
1463 		if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1464 			kn->kn_status &= ~KN_QUEUED;
1465 			kn->kn_status |= KN_INFLUX;
1466 			kq->kq_count--;
1467 			KQ_UNLOCK(kq);
1468 			/*
1469 			 * We don't need to lock the list since we've marked
1470 			 * it _INFLUX.
1471 			 */
1472 			if (!(kn->kn_status & KN_DETACHED))
1473 				kn->kn_fop->f_detach(kn);
1474 			knote_drop(kn, td);
1475 			KQ_LOCK(kq);
1476 			continue;
1477 		} else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1478 			kn->kn_status &= ~KN_QUEUED;
1479 			kn->kn_status |= KN_INFLUX;
1480 			kq->kq_count--;
1481 			KQ_UNLOCK(kq);
1482 			/*
1483 			 * We don't need to lock the list since we've marked
1484 			 * it _INFLUX.
1485 			 */
1486 			*kevp = kn->kn_kevent;
1487 			if (!(kn->kn_status & KN_DETACHED))
1488 				kn->kn_fop->f_detach(kn);
1489 			knote_drop(kn, td);
1490 			KQ_LOCK(kq);
1491 			kn = NULL;
1492 		} else {
1493 			kn->kn_status |= KN_INFLUX;
1494 			KQ_UNLOCK(kq);
1495 			if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1496 				KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1497 			KN_LIST_LOCK(kn);
1498 			if (kn->kn_fop->f_event(kn, 0) == 0) {
1499 				KQ_LOCK(kq);
1500 				KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1501 				kn->kn_status &=
1502 				    ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX);
1503 				kq->kq_count--;
1504 				KN_LIST_UNLOCK(kn);
1505 				influx = 1;
1506 				continue;
1507 			}
1508 			touch = (!kn->kn_fop->f_isfd &&
1509 			    kn->kn_fop->f_touch != NULL);
1510 			if (touch)
1511 				kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1512 			else
1513 				*kevp = kn->kn_kevent;
1514 			KQ_LOCK(kq);
1515 			KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1516 			if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1517 				/*
1518 				 * Manually clear knotes who weren't
1519 				 * 'touch'ed.
1520 				 */
1521 				if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1522 					kn->kn_data = 0;
1523 					kn->kn_fflags = 0;
1524 				}
1525 				if (kn->kn_flags & EV_DISPATCH)
1526 					kn->kn_status |= KN_DISABLED;
1527 				kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1528 				kq->kq_count--;
1529 			} else
1530 				TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1531 
1532 			kn->kn_status &= ~(KN_INFLUX);
1533 			KN_LIST_UNLOCK(kn);
1534 			influx = 1;
1535 		}
1536 
1537 		/* we are returning a copy to the user */
1538 		kevp++;
1539 		nkev++;
1540 		count--;
1541 
1542 		if (nkev == KQ_NEVENTS) {
1543 			influx = 0;
1544 			KQ_UNLOCK_FLUX(kq);
1545 			error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1546 			nkev = 0;
1547 			kevp = keva;
1548 			KQ_LOCK(kq);
1549 			if (error)
1550 				break;
1551 		}
1552 	}
1553 	TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1554 done:
1555 	KQ_OWNED(kq);
1556 	KQ_UNLOCK_FLUX(kq);
1557 	knote_free(marker);
1558 done_nl:
1559 	KQ_NOTOWNED(kq);
1560 	if (nkev != 0)
1561 		error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1562 	td->td_retval[0] = maxevents - count;
1563 	return (error);
1564 }
1565 
1566 /*
1567  * XXX
1568  * This could be expanded to call kqueue_scan, if desired.
1569  */
1570 /*ARGSUSED*/
1571 static int
1572 kqueue_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
1573 	int flags, struct thread *td)
1574 {
1575 	return (ENXIO);
1576 }
1577 
1578 /*ARGSUSED*/
1579 static int
1580 kqueue_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
1581 	 int flags, struct thread *td)
1582 {
1583 	return (ENXIO);
1584 }
1585 
1586 /*ARGSUSED*/
1587 static int
1588 kqueue_truncate(struct file *fp, off_t length, struct ucred *active_cred,
1589 	struct thread *td)
1590 {
1591 
1592 	return (EINVAL);
1593 }
1594 
1595 /*ARGSUSED*/
1596 static int
1597 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1598 	struct ucred *active_cred, struct thread *td)
1599 {
1600 	/*
1601 	 * Enabling sigio causes two major problems:
1602 	 * 1) infinite recursion:
1603 	 * Synopsys: kevent is being used to track signals and have FIOASYNC
1604 	 * set.  On receipt of a signal this will cause a kqueue to recurse
1605 	 * into itself over and over.  Sending the sigio causes the kqueue
1606 	 * to become ready, which in turn posts sigio again, forever.
1607 	 * Solution: this can be solved by setting a flag in the kqueue that
1608 	 * we have a SIGIO in progress.
1609 	 * 2) locking problems:
1610 	 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1611 	 * us above the proc and pgrp locks.
1612 	 * Solution: Post a signal using an async mechanism, being sure to
1613 	 * record a generation count in the delivery so that we do not deliver
1614 	 * a signal to the wrong process.
1615 	 *
1616 	 * Note, these two mechanisms are somewhat mutually exclusive!
1617 	 */
1618 #if 0
1619 	struct kqueue *kq;
1620 
1621 	kq = fp->f_data;
1622 	switch (cmd) {
1623 	case FIOASYNC:
1624 		if (*(int *)data) {
1625 			kq->kq_state |= KQ_ASYNC;
1626 		} else {
1627 			kq->kq_state &= ~KQ_ASYNC;
1628 		}
1629 		return (0);
1630 
1631 	case FIOSETOWN:
1632 		return (fsetown(*(int *)data, &kq->kq_sigio));
1633 
1634 	case FIOGETOWN:
1635 		*(int *)data = fgetown(&kq->kq_sigio);
1636 		return (0);
1637 	}
1638 #endif
1639 
1640 	return (ENOTTY);
1641 }
1642 
1643 /*ARGSUSED*/
1644 static int
1645 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1646 	struct thread *td)
1647 {
1648 	struct kqueue *kq;
1649 	int revents = 0;
1650 	int error;
1651 
1652 	if ((error = kqueue_acquire(fp, &kq)))
1653 		return POLLERR;
1654 
1655 	KQ_LOCK(kq);
1656 	if (events & (POLLIN | POLLRDNORM)) {
1657 		if (kq->kq_count) {
1658 			revents |= events & (POLLIN | POLLRDNORM);
1659 		} else {
1660 			selrecord(td, &kq->kq_sel);
1661 			if (SEL_WAITING(&kq->kq_sel))
1662 				kq->kq_state |= KQ_SEL;
1663 		}
1664 	}
1665 	kqueue_release(kq, 1);
1666 	KQ_UNLOCK(kq);
1667 	return (revents);
1668 }
1669 
1670 /*ARGSUSED*/
1671 static int
1672 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1673 	struct thread *td)
1674 {
1675 
1676 	bzero((void *)st, sizeof *st);
1677 	/*
1678 	 * We no longer return kq_count because the unlocked value is useless.
1679 	 * If you spent all this time getting the count, why not spend your
1680 	 * syscall better by calling kevent?
1681 	 *
1682 	 * XXX - This is needed for libc_r.
1683 	 */
1684 	st->st_mode = S_IFIFO;
1685 	return (0);
1686 }
1687 
1688 /*ARGSUSED*/
1689 static int
1690 kqueue_close(struct file *fp, struct thread *td)
1691 {
1692 	struct kqueue *kq = fp->f_data;
1693 	struct filedesc *fdp;
1694 	struct knote *kn;
1695 	int i;
1696 	int error;
1697 	int filedesc_unlock;
1698 
1699 	if ((error = kqueue_acquire(fp, &kq)))
1700 		return error;
1701 
1702 	filedesc_unlock = 0;
1703 	KQ_LOCK(kq);
1704 
1705 	KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1706 	    ("kqueue already closing"));
1707 	kq->kq_state |= KQ_CLOSING;
1708 	if (kq->kq_refcnt > 1)
1709 		msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1710 
1711 	KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1712 	fdp = kq->kq_fdp;
1713 
1714 	KASSERT(knlist_empty(&kq->kq_sel.si_note),
1715 	    ("kqueue's knlist not empty"));
1716 
1717 	for (i = 0; i < kq->kq_knlistsize; i++) {
1718 		while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1719 			if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1720 				kq->kq_state |= KQ_FLUXWAIT;
1721 				msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
1722 				continue;
1723 			}
1724 			kn->kn_status |= KN_INFLUX;
1725 			KQ_UNLOCK(kq);
1726 			if (!(kn->kn_status & KN_DETACHED))
1727 				kn->kn_fop->f_detach(kn);
1728 			knote_drop(kn, td);
1729 			KQ_LOCK(kq);
1730 		}
1731 	}
1732 	if (kq->kq_knhashmask != 0) {
1733 		for (i = 0; i <= kq->kq_knhashmask; i++) {
1734 			while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1735 				if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1736 					kq->kq_state |= KQ_FLUXWAIT;
1737 					msleep(kq, &kq->kq_lock, PSOCK,
1738 					       "kqclo2", 0);
1739 					continue;
1740 				}
1741 				kn->kn_status |= KN_INFLUX;
1742 				KQ_UNLOCK(kq);
1743 				if (!(kn->kn_status & KN_DETACHED))
1744 					kn->kn_fop->f_detach(kn);
1745 				knote_drop(kn, td);
1746 				KQ_LOCK(kq);
1747 			}
1748 		}
1749 	}
1750 
1751 	if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1752 		kq->kq_state |= KQ_TASKDRAIN;
1753 		msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1754 	}
1755 
1756 	if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1757 		selwakeuppri(&kq->kq_sel, PSOCK);
1758 		if (!SEL_WAITING(&kq->kq_sel))
1759 			kq->kq_state &= ~KQ_SEL;
1760 	}
1761 
1762 	KQ_UNLOCK(kq);
1763 
1764 	/*
1765 	 * We could be called due to the knote_drop() doing fdrop(),
1766 	 * called from kqueue_register().  In this case the global
1767 	 * lock is owned, and filedesc sx is locked before, to not
1768 	 * take the sleepable lock after non-sleepable.
1769 	 */
1770 	if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
1771 		FILEDESC_XLOCK(fdp);
1772 		filedesc_unlock = 1;
1773 	} else
1774 		filedesc_unlock = 0;
1775 	TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
1776 	if (filedesc_unlock)
1777 		FILEDESC_XUNLOCK(fdp);
1778 
1779 	seldrain(&kq->kq_sel);
1780 	knlist_destroy(&kq->kq_sel.si_note);
1781 	mtx_destroy(&kq->kq_lock);
1782 	kq->kq_fdp = NULL;
1783 
1784 	if (kq->kq_knhash != NULL)
1785 		free(kq->kq_knhash, M_KQUEUE);
1786 	if (kq->kq_knlist != NULL)
1787 		free(kq->kq_knlist, M_KQUEUE);
1788 
1789 	funsetown(&kq->kq_sigio);
1790 	chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
1791 	crfree(kq->kq_cred);
1792 	free(kq, M_KQUEUE);
1793 	fp->f_data = NULL;
1794 
1795 	return (0);
1796 }
1797 
1798 static void
1799 kqueue_wakeup(struct kqueue *kq)
1800 {
1801 	KQ_OWNED(kq);
1802 
1803 	if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
1804 		kq->kq_state &= ~KQ_SLEEP;
1805 		wakeup(kq);
1806 	}
1807 	if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1808 		selwakeuppri(&kq->kq_sel, PSOCK);
1809 		if (!SEL_WAITING(&kq->kq_sel))
1810 			kq->kq_state &= ~KQ_SEL;
1811 	}
1812 	if (!knlist_empty(&kq->kq_sel.si_note))
1813 		kqueue_schedtask(kq);
1814 	if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
1815 		pgsigio(&kq->kq_sigio, SIGIO, 0);
1816 	}
1817 }
1818 
1819 /*
1820  * Walk down a list of knotes, activating them if their event has triggered.
1821  *
1822  * There is a possibility to optimize in the case of one kq watching another.
1823  * Instead of scheduling a task to wake it up, you could pass enough state
1824  * down the chain to make up the parent kqueue.  Make this code functional
1825  * first.
1826  */
1827 void
1828 knote(struct knlist *list, long hint, int lockflags)
1829 {
1830 	struct kqueue *kq;
1831 	struct knote *kn;
1832 	int error;
1833 
1834 	if (list == NULL)
1835 		return;
1836 
1837 	KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
1838 
1839 	if ((lockflags & KNF_LISTLOCKED) == 0)
1840 		list->kl_lock(list->kl_lockarg);
1841 
1842 	/*
1843 	 * If we unlock the list lock (and set KN_INFLUX), we can eliminate
1844 	 * the kqueue scheduling, but this will introduce four
1845 	 * lock/unlock's for each knote to test.  If we do, continue to use
1846 	 * SLIST_FOREACH, SLIST_FOREACH_SAFE is not safe in our case, it is
1847 	 * only safe if you want to remove the current item, which we are
1848 	 * not doing.
1849 	 */
1850 	SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
1851 		kq = kn->kn_kq;
1852 		if ((kn->kn_status & KN_INFLUX) != KN_INFLUX) {
1853 			KQ_LOCK(kq);
1854 			if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1855 				KQ_UNLOCK(kq);
1856 			} else if ((lockflags & KNF_NOKQLOCK) != 0) {
1857 				kn->kn_status |= KN_INFLUX;
1858 				KQ_UNLOCK(kq);
1859 				error = kn->kn_fop->f_event(kn, hint);
1860 				KQ_LOCK(kq);
1861 				kn->kn_status &= ~KN_INFLUX;
1862 				if (error)
1863 					KNOTE_ACTIVATE(kn, 1);
1864 				KQ_UNLOCK_FLUX(kq);
1865 			} else {
1866 				kn->kn_status |= KN_HASKQLOCK;
1867 				if (kn->kn_fop->f_event(kn, hint))
1868 					KNOTE_ACTIVATE(kn, 1);
1869 				kn->kn_status &= ~KN_HASKQLOCK;
1870 				KQ_UNLOCK(kq);
1871 			}
1872 		}
1873 		kq = NULL;
1874 	}
1875 	if ((lockflags & KNF_LISTLOCKED) == 0)
1876 		list->kl_unlock(list->kl_lockarg);
1877 }
1878 
1879 /*
1880  * add a knote to a knlist
1881  */
1882 void
1883 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
1884 {
1885 	KNL_ASSERT_LOCK(knl, islocked);
1886 	KQ_NOTOWNED(kn->kn_kq);
1887 	KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
1888 	    (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
1889 	if (!islocked)
1890 		knl->kl_lock(knl->kl_lockarg);
1891 	SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
1892 	if (!islocked)
1893 		knl->kl_unlock(knl->kl_lockarg);
1894 	KQ_LOCK(kn->kn_kq);
1895 	kn->kn_knlist = knl;
1896 	kn->kn_status &= ~KN_DETACHED;
1897 	KQ_UNLOCK(kn->kn_kq);
1898 }
1899 
1900 static void
1901 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked, int kqislocked)
1902 {
1903 	KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
1904 	KNL_ASSERT_LOCK(knl, knlislocked);
1905 	mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
1906 	if (!kqislocked)
1907 		KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
1908     ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
1909 	if (!knlislocked)
1910 		knl->kl_lock(knl->kl_lockarg);
1911 	SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
1912 	kn->kn_knlist = NULL;
1913 	if (!knlislocked)
1914 		knl->kl_unlock(knl->kl_lockarg);
1915 	if (!kqislocked)
1916 		KQ_LOCK(kn->kn_kq);
1917 	kn->kn_status |= KN_DETACHED;
1918 	if (!kqislocked)
1919 		KQ_UNLOCK(kn->kn_kq);
1920 }
1921 
1922 /*
1923  * remove knote from the specified knlist
1924  */
1925 void
1926 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
1927 {
1928 
1929 	knlist_remove_kq(knl, kn, islocked, 0);
1930 }
1931 
1932 /*
1933  * remove knote from the specified knlist while in f_event handler.
1934  */
1935 void
1936 knlist_remove_inevent(struct knlist *knl, struct knote *kn)
1937 {
1938 
1939 	knlist_remove_kq(knl, kn, 1,
1940 	    (kn->kn_status & KN_HASKQLOCK) == KN_HASKQLOCK);
1941 }
1942 
1943 int
1944 knlist_empty(struct knlist *knl)
1945 {
1946 
1947 	KNL_ASSERT_LOCKED(knl);
1948 	return SLIST_EMPTY(&knl->kl_list);
1949 }
1950 
1951 static struct mtx	knlist_lock;
1952 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
1953 	MTX_DEF);
1954 static void knlist_mtx_lock(void *arg);
1955 static void knlist_mtx_unlock(void *arg);
1956 
1957 static void
1958 knlist_mtx_lock(void *arg)
1959 {
1960 
1961 	mtx_lock((struct mtx *)arg);
1962 }
1963 
1964 static void
1965 knlist_mtx_unlock(void *arg)
1966 {
1967 
1968 	mtx_unlock((struct mtx *)arg);
1969 }
1970 
1971 static void
1972 knlist_mtx_assert_locked(void *arg)
1973 {
1974 
1975 	mtx_assert((struct mtx *)arg, MA_OWNED);
1976 }
1977 
1978 static void
1979 knlist_mtx_assert_unlocked(void *arg)
1980 {
1981 
1982 	mtx_assert((struct mtx *)arg, MA_NOTOWNED);
1983 }
1984 
1985 static void
1986 knlist_rw_rlock(void *arg)
1987 {
1988 
1989 	rw_rlock((struct rwlock *)arg);
1990 }
1991 
1992 static void
1993 knlist_rw_runlock(void *arg)
1994 {
1995 
1996 	rw_runlock((struct rwlock *)arg);
1997 }
1998 
1999 static void
2000 knlist_rw_assert_locked(void *arg)
2001 {
2002 
2003 	rw_assert((struct rwlock *)arg, RA_LOCKED);
2004 }
2005 
2006 static void
2007 knlist_rw_assert_unlocked(void *arg)
2008 {
2009 
2010 	rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2011 }
2012 
2013 void
2014 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2015     void (*kl_unlock)(void *),
2016     void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2017 {
2018 
2019 	if (lock == NULL)
2020 		knl->kl_lockarg = &knlist_lock;
2021 	else
2022 		knl->kl_lockarg = lock;
2023 
2024 	if (kl_lock == NULL)
2025 		knl->kl_lock = knlist_mtx_lock;
2026 	else
2027 		knl->kl_lock = kl_lock;
2028 	if (kl_unlock == NULL)
2029 		knl->kl_unlock = knlist_mtx_unlock;
2030 	else
2031 		knl->kl_unlock = kl_unlock;
2032 	if (kl_assert_locked == NULL)
2033 		knl->kl_assert_locked = knlist_mtx_assert_locked;
2034 	else
2035 		knl->kl_assert_locked = kl_assert_locked;
2036 	if (kl_assert_unlocked == NULL)
2037 		knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2038 	else
2039 		knl->kl_assert_unlocked = kl_assert_unlocked;
2040 
2041 	SLIST_INIT(&knl->kl_list);
2042 }
2043 
2044 void
2045 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2046 {
2047 
2048 	knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2049 }
2050 
2051 void
2052 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2053 {
2054 
2055 	knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2056 	    knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2057 }
2058 
2059 void
2060 knlist_destroy(struct knlist *knl)
2061 {
2062 
2063 #ifdef INVARIANTS
2064 	/*
2065 	 * if we run across this error, we need to find the offending
2066 	 * driver and have it call knlist_clear or knlist_delete.
2067 	 */
2068 	if (!SLIST_EMPTY(&knl->kl_list))
2069 		printf("WARNING: destroying knlist w/ knotes on it!\n");
2070 #endif
2071 
2072 	knl->kl_lockarg = knl->kl_lock = knl->kl_unlock = NULL;
2073 	SLIST_INIT(&knl->kl_list);
2074 }
2075 
2076 /*
2077  * Even if we are locked, we may need to drop the lock to allow any influx
2078  * knotes time to "settle".
2079  */
2080 void
2081 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2082 {
2083 	struct knote *kn, *kn2;
2084 	struct kqueue *kq;
2085 
2086 	if (islocked)
2087 		KNL_ASSERT_LOCKED(knl);
2088 	else {
2089 		KNL_ASSERT_UNLOCKED(knl);
2090 again:		/* need to reacquire lock since we have dropped it */
2091 		knl->kl_lock(knl->kl_lockarg);
2092 	}
2093 
2094 	SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2095 		kq = kn->kn_kq;
2096 		KQ_LOCK(kq);
2097 		if ((kn->kn_status & KN_INFLUX)) {
2098 			KQ_UNLOCK(kq);
2099 			continue;
2100 		}
2101 		knlist_remove_kq(knl, kn, 1, 1);
2102 		if (killkn) {
2103 			kn->kn_status |= KN_INFLUX | KN_DETACHED;
2104 			KQ_UNLOCK(kq);
2105 			knote_drop(kn, td);
2106 		} else {
2107 			/* Make sure cleared knotes disappear soon */
2108 			kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2109 			KQ_UNLOCK(kq);
2110 		}
2111 		kq = NULL;
2112 	}
2113 
2114 	if (!SLIST_EMPTY(&knl->kl_list)) {
2115 		/* there are still KN_INFLUX remaining */
2116 		kn = SLIST_FIRST(&knl->kl_list);
2117 		kq = kn->kn_kq;
2118 		KQ_LOCK(kq);
2119 		KASSERT(kn->kn_status & KN_INFLUX,
2120 		    ("knote removed w/o list lock"));
2121 		knl->kl_unlock(knl->kl_lockarg);
2122 		kq->kq_state |= KQ_FLUXWAIT;
2123 		msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2124 		kq = NULL;
2125 		goto again;
2126 	}
2127 
2128 	if (islocked)
2129 		KNL_ASSERT_LOCKED(knl);
2130 	else {
2131 		knl->kl_unlock(knl->kl_lockarg);
2132 		KNL_ASSERT_UNLOCKED(knl);
2133 	}
2134 }
2135 
2136 /*
2137  * Remove all knotes referencing a specified fd must be called with FILEDESC
2138  * lock.  This prevents a race where a new fd comes along and occupies the
2139  * entry and we attach a knote to the fd.
2140  */
2141 void
2142 knote_fdclose(struct thread *td, int fd)
2143 {
2144 	struct filedesc *fdp = td->td_proc->p_fd;
2145 	struct kqueue *kq;
2146 	struct knote *kn;
2147 	int influx;
2148 
2149 	FILEDESC_XLOCK_ASSERT(fdp);
2150 
2151 	/*
2152 	 * We shouldn't have to worry about new kevents appearing on fd
2153 	 * since filedesc is locked.
2154 	 */
2155 	TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2156 		KQ_LOCK(kq);
2157 
2158 again:
2159 		influx = 0;
2160 		while (kq->kq_knlistsize > fd &&
2161 		    (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2162 			if (kn->kn_status & KN_INFLUX) {
2163 				/* someone else might be waiting on our knote */
2164 				if (influx)
2165 					wakeup(kq);
2166 				kq->kq_state |= KQ_FLUXWAIT;
2167 				msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2168 				goto again;
2169 			}
2170 			kn->kn_status |= KN_INFLUX;
2171 			KQ_UNLOCK(kq);
2172 			if (!(kn->kn_status & KN_DETACHED))
2173 				kn->kn_fop->f_detach(kn);
2174 			knote_drop(kn, td);
2175 			influx = 1;
2176 			KQ_LOCK(kq);
2177 		}
2178 		KQ_UNLOCK_FLUX(kq);
2179 	}
2180 }
2181 
2182 static int
2183 knote_attach(struct knote *kn, struct kqueue *kq)
2184 {
2185 	struct klist *list;
2186 
2187 	KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
2188 	KQ_OWNED(kq);
2189 
2190 	if (kn->kn_fop->f_isfd) {
2191 		if (kn->kn_id >= kq->kq_knlistsize)
2192 			return ENOMEM;
2193 		list = &kq->kq_knlist[kn->kn_id];
2194 	} else {
2195 		if (kq->kq_knhash == NULL)
2196 			return ENOMEM;
2197 		list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2198 	}
2199 
2200 	SLIST_INSERT_HEAD(list, kn, kn_link);
2201 
2202 	return 0;
2203 }
2204 
2205 /*
2206  * knote must already have been detached using the f_detach method.
2207  * no lock need to be held, it is assumed that the KN_INFLUX flag is set
2208  * to prevent other removal.
2209  */
2210 static void
2211 knote_drop(struct knote *kn, struct thread *td)
2212 {
2213 	struct kqueue *kq;
2214 	struct klist *list;
2215 
2216 	kq = kn->kn_kq;
2217 
2218 	KQ_NOTOWNED(kq);
2219 	KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
2220 	    ("knote_drop called without KN_INFLUX set in kn_status"));
2221 
2222 	KQ_LOCK(kq);
2223 	if (kn->kn_fop->f_isfd)
2224 		list = &kq->kq_knlist[kn->kn_id];
2225 	else
2226 		list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2227 
2228 	if (!SLIST_EMPTY(list))
2229 		SLIST_REMOVE(list, kn, knote, kn_link);
2230 	if (kn->kn_status & KN_QUEUED)
2231 		knote_dequeue(kn);
2232 	KQ_UNLOCK_FLUX(kq);
2233 
2234 	if (kn->kn_fop->f_isfd) {
2235 		fdrop(kn->kn_fp, td);
2236 		kn->kn_fp = NULL;
2237 	}
2238 	kqueue_fo_release(kn->kn_kevent.filter);
2239 	kn->kn_fop = NULL;
2240 	knote_free(kn);
2241 }
2242 
2243 static void
2244 knote_enqueue(struct knote *kn)
2245 {
2246 	struct kqueue *kq = kn->kn_kq;
2247 
2248 	KQ_OWNED(kn->kn_kq);
2249 	KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2250 
2251 	TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2252 	kn->kn_status |= KN_QUEUED;
2253 	kq->kq_count++;
2254 	kqueue_wakeup(kq);
2255 }
2256 
2257 static void
2258 knote_dequeue(struct knote *kn)
2259 {
2260 	struct kqueue *kq = kn->kn_kq;
2261 
2262 	KQ_OWNED(kn->kn_kq);
2263 	KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2264 
2265 	TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2266 	kn->kn_status &= ~KN_QUEUED;
2267 	kq->kq_count--;
2268 }
2269 
2270 static void
2271 knote_init(void)
2272 {
2273 
2274 	knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2275 	    NULL, NULL, UMA_ALIGN_PTR, 0);
2276 }
2277 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2278 
2279 static struct knote *
2280 knote_alloc(int waitok)
2281 {
2282 	return ((struct knote *)uma_zalloc(knote_zone,
2283 	    (waitok ? M_WAITOK : M_NOWAIT)|M_ZERO));
2284 }
2285 
2286 static void
2287 knote_free(struct knote *kn)
2288 {
2289 	if (kn != NULL)
2290 		uma_zfree(knote_zone, kn);
2291 }
2292 
2293 /*
2294  * Register the kev w/ the kq specified by fd.
2295  */
2296 int
2297 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2298 {
2299 	struct kqueue *kq;
2300 	struct file *fp;
2301 	cap_rights_t rights;
2302 	int error;
2303 
2304 	error = fget(td, fd, cap_rights_init(&rights, CAP_POST_EVENT), &fp);
2305 	if (error != 0)
2306 		return (error);
2307 	if ((error = kqueue_acquire(fp, &kq)) != 0)
2308 		goto noacquire;
2309 
2310 	error = kqueue_register(kq, kev, td, waitok);
2311 
2312 	kqueue_release(kq, 0);
2313 
2314 noacquire:
2315 	fdrop(fp, td);
2316 
2317 	return error;
2318 }
2319