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