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