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