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