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