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