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