xref: /freebsd/sys/kern/kern_event.c (revision fc05543fa75195cd1529ba1abd9206c93c22b8e3)
1 /*-
2  * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon@FreeBSD.org>
3  * Copyright 2004 John-Mark Gurney <jmg@FreeBSD.org>
4  * Copyright (c) 2009 Apple, Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include "opt_ktrace.h"
33 #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 
75 static 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  */
81 static struct mtx	kq_global;
82 MTX_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 
94 TASKQUEUE_DEFINE_THREAD(kqueue_ctx);
95 
96 static int	kevent_copyout(void *arg, struct kevent *kevp, int count);
97 static int	kevent_copyin(void *arg, struct kevent *kevp, int count);
98 static int	kqueue_register(struct kqueue *kq, struct kevent *kev,
99 		    struct thread *td, int waitok);
100 static int	kqueue_acquire(struct file *fp, struct kqueue **kqp);
101 static void	kqueue_release(struct kqueue *kq, int locked);
102 static void	kqueue_destroy(struct kqueue *kq);
103 static void	kqueue_drain(struct kqueue *kq, struct thread *td);
104 static int	kqueue_expand(struct kqueue *kq, struct filterops *fops,
105 		    uintptr_t ident, int waitok);
106 static void	kqueue_task(void *arg, int pending);
107 static 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);
111 static void 	kqueue_wakeup(struct kqueue *kq);
112 static struct filterops *kqueue_fo_find(int filt);
113 static void	kqueue_fo_release(int filt);
114 
115 static fo_ioctl_t	kqueue_ioctl;
116 static fo_poll_t	kqueue_poll;
117 static fo_kqfilter_t	kqueue_kqfilter;
118 static fo_stat_t	kqueue_stat;
119 static fo_close_t	kqueue_close;
120 static fo_fill_kinfo_t	kqueue_fill_kinfo;
121 
122 static 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 
137 static int 	knote_attach(struct knote *kn, struct kqueue *kq);
138 static void 	knote_drop(struct knote *kn, struct thread *td);
139 static void 	knote_enqueue(struct knote *kn);
140 static void 	knote_dequeue(struct knote *kn);
141 static void 	knote_init(void);
142 static struct 	knote *knote_alloc(int waitok);
143 static void 	knote_free(struct knote *kn);
144 
145 static void	filt_kqdetach(struct knote *kn);
146 static int	filt_kqueue(struct knote *kn, long hint);
147 static int	filt_procattach(struct knote *kn);
148 static void	filt_procdetach(struct knote *kn);
149 static int	filt_proc(struct knote *kn, long hint);
150 static int	filt_fileattach(struct knote *kn);
151 static void	filt_timerexpire(void *knx);
152 static int	filt_timerattach(struct knote *kn);
153 static void	filt_timerdetach(struct knote *kn);
154 static int	filt_timer(struct knote *kn, long hint);
155 static int	filt_userattach(struct knote *kn);
156 static void	filt_userdetach(struct knote *kn);
157 static int	filt_user(struct knote *kn, long hint);
158 static void	filt_usertouch(struct knote *kn, struct kevent *kev,
159 		    u_long type);
160 
161 static struct filterops file_filtops = {
162 	.f_isfd = 1,
163 	.f_attach = filt_fileattach,
164 };
165 static 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?  */
171 static struct filterops proc_filtops = {
172 	.f_isfd = 0,
173 	.f_attach = filt_procattach,
174 	.f_detach = filt_procdetach,
175 	.f_event = filt_proc,
176 };
177 static struct filterops timer_filtops = {
178 	.f_isfd = 0,
179 	.f_attach = filt_timerattach,
180 	.f_detach = filt_timerdetach,
181 	.f_event = filt_timer,
182 };
183 static 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 
190 static uma_zone_t	knote_zone;
191 static unsigned int	kq_ncallouts = 0;
192 static unsigned int 	kq_calloutmax = 4 * 1024;
193 SYSCTL_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 
231 static struct knlist *
232 kn_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 
242 static void
243 kn_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 
281 static int
282 filt_nullattach(struct knote *kn)
283 {
284 
285 	return (ENXIO);
286 };
287 
288 struct 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. */
294 extern struct filterops sig_filtops;
295 extern struct filterops fs_filtops;
296 
297 /*
298  * Table for for all system-defined filters.
299  */
300 static struct mtx	filterops_lock;
301 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops",
302 	MTX_DEF);
303 static 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  */
326 static int
327 filt_fileattach(struct knote *kn)
328 {
329 
330 	return (fo_kqfilter(kn->kn_fp, kn));
331 }
332 
333 /*ARGSUSED*/
334 static int
335 kqueue_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 
349 static void
350 filt_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*/
358 static int
359 filt_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?  */
368 static int
369 filt_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?  */
438 static void
439 filt_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?  */
447 static int
448 filt_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  */
486 void
487 knote_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 
579 static sbintime_t
580 timer2sbintime(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 
634 struct 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 
640 static void
641 filt_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  */
662 static int
663 filt_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 
699 static void
700 filt_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 
713 static int
714 filt_timer(struct knote *kn, long hint)
715 {
716 
717 	return (kn->kn_data != 0);
718 }
719 
720 static int
721 filt_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 
735 static void
736 filt_userdetach(__unused struct knote *kn)
737 {
738 
739 	/*
740 	 * EVFILT_USER knotes are not attached to anything in the kernel.
741 	 */
742 }
743 
744 static int
745 filt_user(struct knote *kn, __unused long hint)
746 {
747 
748 	return (kn->kn_hookid);
749 }
750 
751 static void
752 filt_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 
808 int
809 sys_kqueue(struct thread *td, struct kqueue_args *uap)
810 {
811 
812 	return (kern_kqueue(td, 0, NULL));
813 }
814 
815 static void
816 kqueue_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 
825 int
826 kern_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 #ifndef _SYS_SYSPROTO_H_
863 struct kevent_args {
864 	int	fd;
865 	const struct kevent *changelist;
866 	int	nchanges;
867 	struct	kevent *eventlist;
868 	int	nevents;
869 	const struct timespec *timeout;
870 };
871 #endif
872 int
873 sys_kevent(struct thread *td, struct kevent_args *uap)
874 {
875 	struct timespec ts, *tsp;
876 	struct kevent_copyops k_ops = { uap,
877 					kevent_copyout,
878 					kevent_copyin};
879 	int error;
880 #ifdef KTRACE
881 	struct uio ktruio;
882 	struct iovec ktriov;
883 	struct uio *ktruioin = NULL;
884 	struct uio *ktruioout = NULL;
885 #endif
886 
887 	if (uap->timeout != NULL) {
888 		error = copyin(uap->timeout, &ts, sizeof(ts));
889 		if (error)
890 			return (error);
891 		tsp = &ts;
892 	} else
893 		tsp = NULL;
894 
895 #ifdef KTRACE
896 	if (KTRPOINT(td, KTR_GENIO)) {
897 		ktriov.iov_base = uap->changelist;
898 		ktriov.iov_len = uap->nchanges * sizeof(struct kevent);
899 		ktruio = (struct uio){ .uio_iov = &ktriov, .uio_iovcnt = 1,
900 		    .uio_segflg = UIO_USERSPACE, .uio_rw = UIO_READ,
901 		    .uio_td = td };
902 		ktruioin = cloneuio(&ktruio);
903 		ktriov.iov_base = uap->eventlist;
904 		ktriov.iov_len = uap->nevents * sizeof(struct kevent);
905 		ktruioout = cloneuio(&ktruio);
906 	}
907 #endif
908 
909 	error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
910 	    &k_ops, tsp);
911 
912 #ifdef KTRACE
913 	if (ktruioin != NULL) {
914 		ktruioin->uio_resid = uap->nchanges * sizeof(struct kevent);
915 		ktrgenio(uap->fd, UIO_WRITE, ktruioin, 0);
916 		ktruioout->uio_resid = td->td_retval[0] * sizeof(struct kevent);
917 		ktrgenio(uap->fd, UIO_READ, ktruioout, error);
918 	}
919 #endif
920 
921 	return (error);
922 }
923 
924 /*
925  * Copy 'count' items into the destination list pointed to by uap->eventlist.
926  */
927 static int
928 kevent_copyout(void *arg, struct kevent *kevp, int count)
929 {
930 	struct kevent_args *uap;
931 	int error;
932 
933 	KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
934 	uap = (struct kevent_args *)arg;
935 
936 	error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
937 	if (error == 0)
938 		uap->eventlist += count;
939 	return (error);
940 }
941 
942 /*
943  * Copy 'count' items from the list pointed to by uap->changelist.
944  */
945 static int
946 kevent_copyin(void *arg, struct kevent *kevp, int count)
947 {
948 	struct kevent_args *uap;
949 	int error;
950 
951 	KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
952 	uap = (struct kevent_args *)arg;
953 
954 	error = copyin(uap->changelist, kevp, count * sizeof *kevp);
955 	if (error == 0)
956 		uap->changelist += count;
957 	return (error);
958 }
959 
960 int
961 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
962     struct kevent_copyops *k_ops, const struct timespec *timeout)
963 {
964 	cap_rights_t rights;
965 	struct file *fp;
966 	int error;
967 
968 	cap_rights_init(&rights);
969 	if (nchanges > 0)
970 		cap_rights_set(&rights, CAP_KQUEUE_CHANGE);
971 	if (nevents > 0)
972 		cap_rights_set(&rights, CAP_KQUEUE_EVENT);
973 	error = fget(td, fd, &rights, &fp);
974 	if (error != 0)
975 		return (error);
976 
977 	error = kern_kevent_fp(td, fp, nchanges, nevents, k_ops, timeout);
978 	fdrop(fp, td);
979 
980 	return (error);
981 }
982 
983 static int
984 kqueue_kevent(struct kqueue *kq, struct thread *td, int nchanges, int nevents,
985     struct kevent_copyops *k_ops, const struct timespec *timeout)
986 {
987 	struct kevent keva[KQ_NEVENTS];
988 	struct kevent *kevp, *changes;
989 	int i, n, nerrors, error;
990 
991 	nerrors = 0;
992 	while (nchanges > 0) {
993 		n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
994 		error = k_ops->k_copyin(k_ops->arg, keva, n);
995 		if (error)
996 			return (error);
997 		changes = keva;
998 		for (i = 0; i < n; i++) {
999 			kevp = &changes[i];
1000 			if (!kevp->filter)
1001 				continue;
1002 			kevp->flags &= ~EV_SYSFLAGS;
1003 			error = kqueue_register(kq, kevp, td, 1);
1004 			if (error || (kevp->flags & EV_RECEIPT)) {
1005 				if (nevents == 0)
1006 					return (error);
1007 				kevp->flags = EV_ERROR;
1008 				kevp->data = error;
1009 				(void)k_ops->k_copyout(k_ops->arg, kevp, 1);
1010 				nevents--;
1011 				nerrors++;
1012 			}
1013 		}
1014 		nchanges -= n;
1015 	}
1016 	if (nerrors) {
1017 		td->td_retval[0] = nerrors;
1018 		return (0);
1019 	}
1020 
1021 	return (kqueue_scan(kq, nevents, k_ops, timeout, keva, td));
1022 }
1023 
1024 int
1025 kern_kevent_fp(struct thread *td, struct file *fp, int nchanges, int nevents,
1026     struct kevent_copyops *k_ops, const struct timespec *timeout)
1027 {
1028 	struct kqueue *kq;
1029 	int error;
1030 
1031 	error = kqueue_acquire(fp, &kq);
1032 	if (error != 0)
1033 		return (error);
1034 	error = kqueue_kevent(kq, td, nchanges, nevents, k_ops, timeout);
1035 	kqueue_release(kq, 0);
1036 	return (error);
1037 }
1038 
1039 /*
1040  * Performs a kevent() call on a temporarily created kqueue. This can be
1041  * used to perform one-shot polling, similar to poll() and select().
1042  */
1043 int
1044 kern_kevent_anonymous(struct thread *td, int nevents,
1045     struct kevent_copyops *k_ops)
1046 {
1047 	struct kqueue kq = {};
1048 	int error;
1049 
1050 	kqueue_init(&kq);
1051 	kq.kq_refcnt = 1;
1052 	error = kqueue_kevent(&kq, td, nevents, nevents, k_ops, NULL);
1053 	kqueue_drain(&kq, td);
1054 	kqueue_destroy(&kq);
1055 	return (error);
1056 }
1057 
1058 int
1059 kqueue_add_filteropts(int filt, struct filterops *filtops)
1060 {
1061 	int error;
1062 
1063 	error = 0;
1064 	if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
1065 		printf(
1066 "trying to add a filterop that is out of range: %d is beyond %d\n",
1067 		    ~filt, EVFILT_SYSCOUNT);
1068 		return EINVAL;
1069 	}
1070 	mtx_lock(&filterops_lock);
1071 	if (sysfilt_ops[~filt].for_fop != &null_filtops &&
1072 	    sysfilt_ops[~filt].for_fop != NULL)
1073 		error = EEXIST;
1074 	else {
1075 		sysfilt_ops[~filt].for_fop = filtops;
1076 		sysfilt_ops[~filt].for_refcnt = 0;
1077 	}
1078 	mtx_unlock(&filterops_lock);
1079 
1080 	return (error);
1081 }
1082 
1083 int
1084 kqueue_del_filteropts(int filt)
1085 {
1086 	int error;
1087 
1088 	error = 0;
1089 	if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1090 		return EINVAL;
1091 
1092 	mtx_lock(&filterops_lock);
1093 	if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1094 	    sysfilt_ops[~filt].for_fop == NULL)
1095 		error = EINVAL;
1096 	else if (sysfilt_ops[~filt].for_refcnt != 0)
1097 		error = EBUSY;
1098 	else {
1099 		sysfilt_ops[~filt].for_fop = &null_filtops;
1100 		sysfilt_ops[~filt].for_refcnt = 0;
1101 	}
1102 	mtx_unlock(&filterops_lock);
1103 
1104 	return error;
1105 }
1106 
1107 static struct filterops *
1108 kqueue_fo_find(int filt)
1109 {
1110 
1111 	if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1112 		return NULL;
1113 
1114 	if (sysfilt_ops[~filt].for_nolock)
1115 		return sysfilt_ops[~filt].for_fop;
1116 
1117 	mtx_lock(&filterops_lock);
1118 	sysfilt_ops[~filt].for_refcnt++;
1119 	if (sysfilt_ops[~filt].for_fop == NULL)
1120 		sysfilt_ops[~filt].for_fop = &null_filtops;
1121 	mtx_unlock(&filterops_lock);
1122 
1123 	return sysfilt_ops[~filt].for_fop;
1124 }
1125 
1126 static void
1127 kqueue_fo_release(int filt)
1128 {
1129 
1130 	if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1131 		return;
1132 
1133 	if (sysfilt_ops[~filt].for_nolock)
1134 		return;
1135 
1136 	mtx_lock(&filterops_lock);
1137 	KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1138 	    ("filter object refcount not valid on release"));
1139 	sysfilt_ops[~filt].for_refcnt--;
1140 	mtx_unlock(&filterops_lock);
1141 }
1142 
1143 /*
1144  * A ref to kq (obtained via kqueue_acquire) must be held.  waitok will
1145  * influence if memory allocation should wait.  Make sure it is 0 if you
1146  * hold any mutexes.
1147  */
1148 static int
1149 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
1150 {
1151 	struct filterops *fops;
1152 	struct file *fp;
1153 	struct knote *kn, *tkn;
1154 	struct knlist *knl;
1155 	cap_rights_t rights;
1156 	int error, filt, event;
1157 	int haskqglobal, filedesc_unlock;
1158 
1159 	if ((kev->flags & (EV_ENABLE | EV_DISABLE)) == (EV_ENABLE | EV_DISABLE))
1160 		return (EINVAL);
1161 
1162 	fp = NULL;
1163 	kn = NULL;
1164 	knl = NULL;
1165 	error = 0;
1166 	haskqglobal = 0;
1167 	filedesc_unlock = 0;
1168 
1169 	filt = kev->filter;
1170 	fops = kqueue_fo_find(filt);
1171 	if (fops == NULL)
1172 		return EINVAL;
1173 
1174 	if (kev->flags & EV_ADD) {
1175 		/*
1176 		 * Prevent waiting with locks.  Non-sleepable
1177 		 * allocation failures are handled in the loop, only
1178 		 * if the spare knote appears to be actually required.
1179 		 */
1180 		tkn = knote_alloc(waitok);
1181 	} else {
1182 		tkn = NULL;
1183 	}
1184 
1185 findkn:
1186 	if (fops->f_isfd) {
1187 		KASSERT(td != NULL, ("td is NULL"));
1188 		if (kev->ident > INT_MAX)
1189 			error = EBADF;
1190 		else
1191 			error = fget(td, kev->ident,
1192 			    cap_rights_init(&rights, CAP_EVENT), &fp);
1193 		if (error)
1194 			goto done;
1195 
1196 		if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1197 		    kev->ident, 0) != 0) {
1198 			/* try again */
1199 			fdrop(fp, td);
1200 			fp = NULL;
1201 			error = kqueue_expand(kq, fops, kev->ident, waitok);
1202 			if (error)
1203 				goto done;
1204 			goto findkn;
1205 		}
1206 
1207 		if (fp->f_type == DTYPE_KQUEUE) {
1208 			/*
1209 			 * If we add some intelligence about what we are doing,
1210 			 * we should be able to support events on ourselves.
1211 			 * We need to know when we are doing this to prevent
1212 			 * getting both the knlist lock and the kq lock since
1213 			 * they are the same thing.
1214 			 */
1215 			if (fp->f_data == kq) {
1216 				error = EINVAL;
1217 				goto done;
1218 			}
1219 
1220 			/*
1221 			 * Pre-lock the filedesc before the global
1222 			 * lock mutex, see the comment in
1223 			 * kqueue_close().
1224 			 */
1225 			FILEDESC_XLOCK(td->td_proc->p_fd);
1226 			filedesc_unlock = 1;
1227 			KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1228 		}
1229 
1230 		KQ_LOCK(kq);
1231 		if (kev->ident < kq->kq_knlistsize) {
1232 			SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1233 				if (kev->filter == kn->kn_filter)
1234 					break;
1235 		}
1236 	} else {
1237 		if ((kev->flags & EV_ADD) == EV_ADD)
1238 			kqueue_expand(kq, fops, kev->ident, waitok);
1239 
1240 		KQ_LOCK(kq);
1241 
1242 		/*
1243 		 * If possible, find an existing knote to use for this kevent.
1244 		 */
1245 		if (kev->filter == EVFILT_PROC &&
1246 		    (kev->flags & (EV_FLAG1 | EV_FLAG2)) != 0) {
1247 			/* This is an internal creation of a process tracking
1248 			 * note. Don't attempt to coalesce this with an
1249 			 * existing note.
1250 			 */
1251 			;
1252 		} else if (kq->kq_knhashmask != 0) {
1253 			struct klist *list;
1254 
1255 			list = &kq->kq_knhash[
1256 			    KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1257 			SLIST_FOREACH(kn, list, kn_link)
1258 				if (kev->ident == kn->kn_id &&
1259 				    kev->filter == kn->kn_filter)
1260 					break;
1261 		}
1262 	}
1263 
1264 	/* knote is in the process of changing, wait for it to stabilize. */
1265 	if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1266 		KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1267 		if (filedesc_unlock) {
1268 			FILEDESC_XUNLOCK(td->td_proc->p_fd);
1269 			filedesc_unlock = 0;
1270 		}
1271 		kq->kq_state |= KQ_FLUXWAIT;
1272 		msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1273 		if (fp != NULL) {
1274 			fdrop(fp, td);
1275 			fp = NULL;
1276 		}
1277 		goto findkn;
1278 	}
1279 
1280 	/*
1281 	 * kn now contains the matching knote, or NULL if no match
1282 	 */
1283 	if (kn == NULL) {
1284 		if (kev->flags & EV_ADD) {
1285 			kn = tkn;
1286 			tkn = NULL;
1287 			if (kn == NULL) {
1288 				KQ_UNLOCK(kq);
1289 				error = ENOMEM;
1290 				goto done;
1291 			}
1292 			kn->kn_fp = fp;
1293 			kn->kn_kq = kq;
1294 			kn->kn_fop = fops;
1295 			/*
1296 			 * apply reference counts to knote structure, and
1297 			 * do not release it at the end of this routine.
1298 			 */
1299 			fops = NULL;
1300 			fp = NULL;
1301 
1302 			kn->kn_sfflags = kev->fflags;
1303 			kn->kn_sdata = kev->data;
1304 			kev->fflags = 0;
1305 			kev->data = 0;
1306 			kn->kn_kevent = *kev;
1307 			kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1308 			    EV_ENABLE | EV_DISABLE | EV_FORCEONESHOT);
1309 			kn->kn_status = KN_INFLUX|KN_DETACHED;
1310 
1311 			error = knote_attach(kn, kq);
1312 			KQ_UNLOCK(kq);
1313 			if (error != 0) {
1314 				tkn = kn;
1315 				goto done;
1316 			}
1317 
1318 			if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1319 				knote_drop(kn, td);
1320 				goto done;
1321 			}
1322 			knl = kn_list_lock(kn);
1323 			goto done_ev_add;
1324 		} else {
1325 			/* No matching knote and the EV_ADD flag is not set. */
1326 			KQ_UNLOCK(kq);
1327 			error = ENOENT;
1328 			goto done;
1329 		}
1330 	}
1331 
1332 	if (kev->flags & EV_DELETE) {
1333 		kn->kn_status |= KN_INFLUX;
1334 		KQ_UNLOCK(kq);
1335 		if (!(kn->kn_status & KN_DETACHED))
1336 			kn->kn_fop->f_detach(kn);
1337 		knote_drop(kn, td);
1338 		goto done;
1339 	}
1340 
1341 	if (kev->flags & EV_FORCEONESHOT) {
1342 		kn->kn_flags |= EV_ONESHOT;
1343 		KNOTE_ACTIVATE(kn, 1);
1344 	}
1345 
1346 	/*
1347 	 * The user may change some filter values after the initial EV_ADD,
1348 	 * but doing so will not reset any filter which has already been
1349 	 * triggered.
1350 	 */
1351 	kn->kn_status |= KN_INFLUX | KN_SCAN;
1352 	KQ_UNLOCK(kq);
1353 	knl = kn_list_lock(kn);
1354 	kn->kn_kevent.udata = kev->udata;
1355 	if (!fops->f_isfd && fops->f_touch != NULL) {
1356 		fops->f_touch(kn, kev, EVENT_REGISTER);
1357 	} else {
1358 		kn->kn_sfflags = kev->fflags;
1359 		kn->kn_sdata = kev->data;
1360 	}
1361 
1362 	/*
1363 	 * We can get here with kn->kn_knlist == NULL.  This can happen when
1364 	 * the initial attach event decides that the event is "completed"
1365 	 * already.  i.e. filt_procattach is called on a zombie process.  It
1366 	 * will call filt_proc which will remove it from the list, and NULL
1367 	 * kn_knlist.
1368 	 */
1369 done_ev_add:
1370 	if ((kev->flags & EV_ENABLE) != 0)
1371 		kn->kn_status &= ~KN_DISABLED;
1372 	else if ((kev->flags & EV_DISABLE) != 0)
1373 		kn->kn_status |= KN_DISABLED;
1374 
1375 	if ((kn->kn_status & KN_DISABLED) == 0)
1376 		event = kn->kn_fop->f_event(kn, 0);
1377 	else
1378 		event = 0;
1379 
1380 	KQ_LOCK(kq);
1381 	if (event)
1382 		kn->kn_status |= KN_ACTIVE;
1383 	if ((kn->kn_status & (KN_ACTIVE | KN_DISABLED | KN_QUEUED)) ==
1384 	    KN_ACTIVE)
1385 		knote_enqueue(kn);
1386 	kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1387 	kn_list_unlock(knl);
1388 	KQ_UNLOCK_FLUX(kq);
1389 
1390 done:
1391 	KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1392 	if (filedesc_unlock)
1393 		FILEDESC_XUNLOCK(td->td_proc->p_fd);
1394 	if (fp != NULL)
1395 		fdrop(fp, td);
1396 	knote_free(tkn);
1397 	if (fops != NULL)
1398 		kqueue_fo_release(filt);
1399 	return (error);
1400 }
1401 
1402 static int
1403 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1404 {
1405 	int error;
1406 	struct kqueue *kq;
1407 
1408 	error = 0;
1409 
1410 	kq = fp->f_data;
1411 	if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1412 		return (EBADF);
1413 	*kqp = kq;
1414 	KQ_LOCK(kq);
1415 	if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1416 		KQ_UNLOCK(kq);
1417 		return (EBADF);
1418 	}
1419 	kq->kq_refcnt++;
1420 	KQ_UNLOCK(kq);
1421 
1422 	return error;
1423 }
1424 
1425 static void
1426 kqueue_release(struct kqueue *kq, int locked)
1427 {
1428 	if (locked)
1429 		KQ_OWNED(kq);
1430 	else
1431 		KQ_LOCK(kq);
1432 	kq->kq_refcnt--;
1433 	if (kq->kq_refcnt == 1)
1434 		wakeup(&kq->kq_refcnt);
1435 	if (!locked)
1436 		KQ_UNLOCK(kq);
1437 }
1438 
1439 static void
1440 kqueue_schedtask(struct kqueue *kq)
1441 {
1442 
1443 	KQ_OWNED(kq);
1444 	KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1445 	    ("scheduling kqueue task while draining"));
1446 
1447 	if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1448 		taskqueue_enqueue(taskqueue_kqueue_ctx, &kq->kq_task);
1449 		kq->kq_state |= KQ_TASKSCHED;
1450 	}
1451 }
1452 
1453 /*
1454  * Expand the kq to make sure we have storage for fops/ident pair.
1455  *
1456  * Return 0 on success (or no work necessary), return errno on failure.
1457  *
1458  * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1459  * If kqueue_register is called from a non-fd context, there usually/should
1460  * be no locks held.
1461  */
1462 static int
1463 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1464 	int waitok)
1465 {
1466 	struct klist *list, *tmp_knhash, *to_free;
1467 	u_long tmp_knhashmask;
1468 	int size;
1469 	int fd;
1470 	int mflag = waitok ? M_WAITOK : M_NOWAIT;
1471 
1472 	KQ_NOTOWNED(kq);
1473 
1474 	to_free = NULL;
1475 	if (fops->f_isfd) {
1476 		fd = ident;
1477 		if (kq->kq_knlistsize <= fd) {
1478 			size = kq->kq_knlistsize;
1479 			while (size <= fd)
1480 				size += KQEXTENT;
1481 			list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1482 			if (list == NULL)
1483 				return ENOMEM;
1484 			KQ_LOCK(kq);
1485 			if (kq->kq_knlistsize > fd) {
1486 				to_free = list;
1487 				list = NULL;
1488 			} else {
1489 				if (kq->kq_knlist != NULL) {
1490 					bcopy(kq->kq_knlist, list,
1491 					    kq->kq_knlistsize * sizeof(*list));
1492 					to_free = kq->kq_knlist;
1493 					kq->kq_knlist = NULL;
1494 				}
1495 				bzero((caddr_t)list +
1496 				    kq->kq_knlistsize * sizeof(*list),
1497 				    (size - kq->kq_knlistsize) * sizeof(*list));
1498 				kq->kq_knlistsize = size;
1499 				kq->kq_knlist = list;
1500 			}
1501 			KQ_UNLOCK(kq);
1502 		}
1503 	} else {
1504 		if (kq->kq_knhashmask == 0) {
1505 			tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1506 			    &tmp_knhashmask);
1507 			if (tmp_knhash == NULL)
1508 				return ENOMEM;
1509 			KQ_LOCK(kq);
1510 			if (kq->kq_knhashmask == 0) {
1511 				kq->kq_knhash = tmp_knhash;
1512 				kq->kq_knhashmask = tmp_knhashmask;
1513 			} else {
1514 				to_free = tmp_knhash;
1515 			}
1516 			KQ_UNLOCK(kq);
1517 		}
1518 	}
1519 	free(to_free, M_KQUEUE);
1520 
1521 	KQ_NOTOWNED(kq);
1522 	return 0;
1523 }
1524 
1525 static void
1526 kqueue_task(void *arg, int pending)
1527 {
1528 	struct kqueue *kq;
1529 	int haskqglobal;
1530 
1531 	haskqglobal = 0;
1532 	kq = arg;
1533 
1534 	KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1535 	KQ_LOCK(kq);
1536 
1537 	KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1538 
1539 	kq->kq_state &= ~KQ_TASKSCHED;
1540 	if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1541 		wakeup(&kq->kq_state);
1542 	}
1543 	KQ_UNLOCK(kq);
1544 	KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1545 }
1546 
1547 /*
1548  * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1549  * We treat KN_MARKER knotes as if they are INFLUX.
1550  */
1551 static int
1552 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1553     const struct timespec *tsp, struct kevent *keva, struct thread *td)
1554 {
1555 	struct kevent *kevp;
1556 	struct knote *kn, *marker;
1557 	struct knlist *knl;
1558 	sbintime_t asbt, rsbt;
1559 	int count, error, haskqglobal, influx, nkev, touch;
1560 
1561 	count = maxevents;
1562 	nkev = 0;
1563 	error = 0;
1564 	haskqglobal = 0;
1565 
1566 	if (maxevents == 0)
1567 		goto done_nl;
1568 
1569 	rsbt = 0;
1570 	if (tsp != NULL) {
1571 		if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1572 		    tsp->tv_nsec >= 1000000000) {
1573 			error = EINVAL;
1574 			goto done_nl;
1575 		}
1576 		if (timespecisset(tsp)) {
1577 			if (tsp->tv_sec <= INT32_MAX) {
1578 				rsbt = tstosbt(*tsp);
1579 				if (TIMESEL(&asbt, rsbt))
1580 					asbt += tc_tick_sbt;
1581 				if (asbt <= SBT_MAX - rsbt)
1582 					asbt += rsbt;
1583 				else
1584 					asbt = 0;
1585 				rsbt >>= tc_precexp;
1586 			} else
1587 				asbt = 0;
1588 		} else
1589 			asbt = -1;
1590 	} else
1591 		asbt = 0;
1592 	marker = knote_alloc(1);
1593 	marker->kn_status = KN_MARKER;
1594 	KQ_LOCK(kq);
1595 
1596 retry:
1597 	kevp = keva;
1598 	if (kq->kq_count == 0) {
1599 		if (asbt == -1) {
1600 			error = EWOULDBLOCK;
1601 		} else {
1602 			kq->kq_state |= KQ_SLEEP;
1603 			error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1604 			    "kqread", asbt, rsbt, C_ABSOLUTE);
1605 		}
1606 		if (error == 0)
1607 			goto retry;
1608 		/* don't restart after signals... */
1609 		if (error == ERESTART)
1610 			error = EINTR;
1611 		else if (error == EWOULDBLOCK)
1612 			error = 0;
1613 		goto done;
1614 	}
1615 
1616 	TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1617 	influx = 0;
1618 	while (count) {
1619 		KQ_OWNED(kq);
1620 		kn = TAILQ_FIRST(&kq->kq_head);
1621 
1622 		if ((kn->kn_status == KN_MARKER && kn != marker) ||
1623 		    (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1624 			if (influx) {
1625 				influx = 0;
1626 				KQ_FLUX_WAKEUP(kq);
1627 			}
1628 			kq->kq_state |= KQ_FLUXWAIT;
1629 			error = msleep(kq, &kq->kq_lock, PSOCK,
1630 			    "kqflxwt", 0);
1631 			continue;
1632 		}
1633 
1634 		TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1635 		if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1636 			kn->kn_status &= ~KN_QUEUED;
1637 			kq->kq_count--;
1638 			continue;
1639 		}
1640 		if (kn == marker) {
1641 			KQ_FLUX_WAKEUP(kq);
1642 			if (count == maxevents)
1643 				goto retry;
1644 			goto done;
1645 		}
1646 		KASSERT((kn->kn_status & KN_INFLUX) == 0,
1647 		    ("KN_INFLUX set when not suppose to be"));
1648 
1649 		if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1650 			kn->kn_status &= ~KN_QUEUED;
1651 			kn->kn_status |= KN_INFLUX;
1652 			kq->kq_count--;
1653 			KQ_UNLOCK(kq);
1654 			/*
1655 			 * We don't need to lock the list since we've marked
1656 			 * it _INFLUX.
1657 			 */
1658 			if (!(kn->kn_status & KN_DETACHED))
1659 				kn->kn_fop->f_detach(kn);
1660 			knote_drop(kn, td);
1661 			KQ_LOCK(kq);
1662 			continue;
1663 		} else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
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 			*kevp = kn->kn_kevent;
1673 			if (!(kn->kn_status & KN_DETACHED))
1674 				kn->kn_fop->f_detach(kn);
1675 			knote_drop(kn, td);
1676 			KQ_LOCK(kq);
1677 			kn = NULL;
1678 		} else {
1679 			kn->kn_status |= KN_INFLUX | KN_SCAN;
1680 			KQ_UNLOCK(kq);
1681 			if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1682 				KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1683 			knl = kn_list_lock(kn);
1684 			if (kn->kn_fop->f_event(kn, 0) == 0) {
1685 				KQ_LOCK(kq);
1686 				KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1687 				kn->kn_status &=
1688 				    ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX |
1689 				    KN_SCAN);
1690 				kq->kq_count--;
1691 				kn_list_unlock(knl);
1692 				influx = 1;
1693 				continue;
1694 			}
1695 			touch = (!kn->kn_fop->f_isfd &&
1696 			    kn->kn_fop->f_touch != NULL);
1697 			if (touch)
1698 				kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1699 			else
1700 				*kevp = kn->kn_kevent;
1701 			KQ_LOCK(kq);
1702 			KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1703 			if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1704 				/*
1705 				 * Manually clear knotes who weren't
1706 				 * 'touch'ed.
1707 				 */
1708 				if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1709 					kn->kn_data = 0;
1710 					kn->kn_fflags = 0;
1711 				}
1712 				if (kn->kn_flags & EV_DISPATCH)
1713 					kn->kn_status |= KN_DISABLED;
1714 				kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1715 				kq->kq_count--;
1716 			} else
1717 				TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1718 
1719 			kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1720 			kn_list_unlock(knl);
1721 			influx = 1;
1722 		}
1723 
1724 		/* we are returning a copy to the user */
1725 		kevp++;
1726 		nkev++;
1727 		count--;
1728 
1729 		if (nkev == KQ_NEVENTS) {
1730 			influx = 0;
1731 			KQ_UNLOCK_FLUX(kq);
1732 			error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1733 			nkev = 0;
1734 			kevp = keva;
1735 			KQ_LOCK(kq);
1736 			if (error)
1737 				break;
1738 		}
1739 	}
1740 	TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1741 done:
1742 	KQ_OWNED(kq);
1743 	KQ_UNLOCK_FLUX(kq);
1744 	knote_free(marker);
1745 done_nl:
1746 	KQ_NOTOWNED(kq);
1747 	if (nkev != 0)
1748 		error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1749 	td->td_retval[0] = maxevents - count;
1750 	return (error);
1751 }
1752 
1753 /*ARGSUSED*/
1754 static int
1755 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1756 	struct ucred *active_cred, struct thread *td)
1757 {
1758 	/*
1759 	 * Enabling sigio causes two major problems:
1760 	 * 1) infinite recursion:
1761 	 * Synopsys: kevent is being used to track signals and have FIOASYNC
1762 	 * set.  On receipt of a signal this will cause a kqueue to recurse
1763 	 * into itself over and over.  Sending the sigio causes the kqueue
1764 	 * to become ready, which in turn posts sigio again, forever.
1765 	 * Solution: this can be solved by setting a flag in the kqueue that
1766 	 * we have a SIGIO in progress.
1767 	 * 2) locking problems:
1768 	 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1769 	 * us above the proc and pgrp locks.
1770 	 * Solution: Post a signal using an async mechanism, being sure to
1771 	 * record a generation count in the delivery so that we do not deliver
1772 	 * a signal to the wrong process.
1773 	 *
1774 	 * Note, these two mechanisms are somewhat mutually exclusive!
1775 	 */
1776 #if 0
1777 	struct kqueue *kq;
1778 
1779 	kq = fp->f_data;
1780 	switch (cmd) {
1781 	case FIOASYNC:
1782 		if (*(int *)data) {
1783 			kq->kq_state |= KQ_ASYNC;
1784 		} else {
1785 			kq->kq_state &= ~KQ_ASYNC;
1786 		}
1787 		return (0);
1788 
1789 	case FIOSETOWN:
1790 		return (fsetown(*(int *)data, &kq->kq_sigio));
1791 
1792 	case FIOGETOWN:
1793 		*(int *)data = fgetown(&kq->kq_sigio);
1794 		return (0);
1795 	}
1796 #endif
1797 
1798 	return (ENOTTY);
1799 }
1800 
1801 /*ARGSUSED*/
1802 static int
1803 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1804 	struct thread *td)
1805 {
1806 	struct kqueue *kq;
1807 	int revents = 0;
1808 	int error;
1809 
1810 	if ((error = kqueue_acquire(fp, &kq)))
1811 		return POLLERR;
1812 
1813 	KQ_LOCK(kq);
1814 	if (events & (POLLIN | POLLRDNORM)) {
1815 		if (kq->kq_count) {
1816 			revents |= events & (POLLIN | POLLRDNORM);
1817 		} else {
1818 			selrecord(td, &kq->kq_sel);
1819 			if (SEL_WAITING(&kq->kq_sel))
1820 				kq->kq_state |= KQ_SEL;
1821 		}
1822 	}
1823 	kqueue_release(kq, 1);
1824 	KQ_UNLOCK(kq);
1825 	return (revents);
1826 }
1827 
1828 /*ARGSUSED*/
1829 static int
1830 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1831 	struct thread *td)
1832 {
1833 
1834 	bzero((void *)st, sizeof *st);
1835 	/*
1836 	 * We no longer return kq_count because the unlocked value is useless.
1837 	 * If you spent all this time getting the count, why not spend your
1838 	 * syscall better by calling kevent?
1839 	 *
1840 	 * XXX - This is needed for libc_r.
1841 	 */
1842 	st->st_mode = S_IFIFO;
1843 	return (0);
1844 }
1845 
1846 static void
1847 kqueue_drain(struct kqueue *kq, struct thread *td)
1848 {
1849 	struct knote *kn;
1850 	int i;
1851 
1852 	KQ_LOCK(kq);
1853 
1854 	KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1855 	    ("kqueue already closing"));
1856 	kq->kq_state |= KQ_CLOSING;
1857 	if (kq->kq_refcnt > 1)
1858 		msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1859 
1860 	KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1861 
1862 	KASSERT(knlist_empty(&kq->kq_sel.si_note),
1863 	    ("kqueue's knlist not empty"));
1864 
1865 	for (i = 0; i < kq->kq_knlistsize; i++) {
1866 		while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1867 			if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1868 				kq->kq_state |= KQ_FLUXWAIT;
1869 				msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
1870 				continue;
1871 			}
1872 			kn->kn_status |= KN_INFLUX;
1873 			KQ_UNLOCK(kq);
1874 			if (!(kn->kn_status & KN_DETACHED))
1875 				kn->kn_fop->f_detach(kn);
1876 			knote_drop(kn, td);
1877 			KQ_LOCK(kq);
1878 		}
1879 	}
1880 	if (kq->kq_knhashmask != 0) {
1881 		for (i = 0; i <= kq->kq_knhashmask; i++) {
1882 			while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1883 				if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1884 					kq->kq_state |= KQ_FLUXWAIT;
1885 					msleep(kq, &kq->kq_lock, PSOCK,
1886 					       "kqclo2", 0);
1887 					continue;
1888 				}
1889 				kn->kn_status |= KN_INFLUX;
1890 				KQ_UNLOCK(kq);
1891 				if (!(kn->kn_status & KN_DETACHED))
1892 					kn->kn_fop->f_detach(kn);
1893 				knote_drop(kn, td);
1894 				KQ_LOCK(kq);
1895 			}
1896 		}
1897 	}
1898 
1899 	if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1900 		kq->kq_state |= KQ_TASKDRAIN;
1901 		msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1902 	}
1903 
1904 	if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1905 		selwakeuppri(&kq->kq_sel, PSOCK);
1906 		if (!SEL_WAITING(&kq->kq_sel))
1907 			kq->kq_state &= ~KQ_SEL;
1908 	}
1909 
1910 	KQ_UNLOCK(kq);
1911 }
1912 
1913 static void
1914 kqueue_destroy(struct kqueue *kq)
1915 {
1916 
1917 	KASSERT(kq->kq_fdp == NULL,
1918 	    ("kqueue still attached to a file descriptor"));
1919 	seldrain(&kq->kq_sel);
1920 	knlist_destroy(&kq->kq_sel.si_note);
1921 	mtx_destroy(&kq->kq_lock);
1922 
1923 	if (kq->kq_knhash != NULL)
1924 		free(kq->kq_knhash, M_KQUEUE);
1925 	if (kq->kq_knlist != NULL)
1926 		free(kq->kq_knlist, M_KQUEUE);
1927 
1928 	funsetown(&kq->kq_sigio);
1929 }
1930 
1931 /*ARGSUSED*/
1932 static int
1933 kqueue_close(struct file *fp, struct thread *td)
1934 {
1935 	struct kqueue *kq = fp->f_data;
1936 	struct filedesc *fdp;
1937 	int error;
1938 	int filedesc_unlock;
1939 
1940 	if ((error = kqueue_acquire(fp, &kq)))
1941 		return error;
1942 	kqueue_drain(kq, td);
1943 
1944 	/*
1945 	 * We could be called due to the knote_drop() doing fdrop(),
1946 	 * called from kqueue_register().  In this case the global
1947 	 * lock is owned, and filedesc sx is locked before, to not
1948 	 * take the sleepable lock after non-sleepable.
1949 	 */
1950 	fdp = kq->kq_fdp;
1951 	kq->kq_fdp = NULL;
1952 	if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
1953 		FILEDESC_XLOCK(fdp);
1954 		filedesc_unlock = 1;
1955 	} else
1956 		filedesc_unlock = 0;
1957 	TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
1958 	if (filedesc_unlock)
1959 		FILEDESC_XUNLOCK(fdp);
1960 
1961 	kqueue_destroy(kq);
1962 	chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
1963 	crfree(kq->kq_cred);
1964 	free(kq, M_KQUEUE);
1965 	fp->f_data = NULL;
1966 
1967 	return (0);
1968 }
1969 
1970 static int
1971 kqueue_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
1972 {
1973 
1974 	kif->kf_type = KF_TYPE_KQUEUE;
1975 	return (0);
1976 }
1977 
1978 static void
1979 kqueue_wakeup(struct kqueue *kq)
1980 {
1981 	KQ_OWNED(kq);
1982 
1983 	if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
1984 		kq->kq_state &= ~KQ_SLEEP;
1985 		wakeup(kq);
1986 	}
1987 	if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1988 		selwakeuppri(&kq->kq_sel, PSOCK);
1989 		if (!SEL_WAITING(&kq->kq_sel))
1990 			kq->kq_state &= ~KQ_SEL;
1991 	}
1992 	if (!knlist_empty(&kq->kq_sel.si_note))
1993 		kqueue_schedtask(kq);
1994 	if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
1995 		pgsigio(&kq->kq_sigio, SIGIO, 0);
1996 	}
1997 }
1998 
1999 /*
2000  * Walk down a list of knotes, activating them if their event has triggered.
2001  *
2002  * There is a possibility to optimize in the case of one kq watching another.
2003  * Instead of scheduling a task to wake it up, you could pass enough state
2004  * down the chain to make up the parent kqueue.  Make this code functional
2005  * first.
2006  */
2007 void
2008 knote(struct knlist *list, long hint, int lockflags)
2009 {
2010 	struct kqueue *kq;
2011 	struct knote *kn, *tkn;
2012 	int error;
2013 	bool own_influx;
2014 
2015 	if (list == NULL)
2016 		return;
2017 
2018 	KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
2019 
2020 	if ((lockflags & KNF_LISTLOCKED) == 0)
2021 		list->kl_lock(list->kl_lockarg);
2022 
2023 	/*
2024 	 * If we unlock the list lock (and set KN_INFLUX), we can
2025 	 * eliminate the kqueue scheduling, but this will introduce
2026 	 * four lock/unlock's for each knote to test.  Also, marker
2027 	 * would be needed to keep iteration position, since filters
2028 	 * or other threads could remove events.
2029 	 */
2030 	SLIST_FOREACH_SAFE(kn, &list->kl_list, kn_selnext, tkn) {
2031 		kq = kn->kn_kq;
2032 		KQ_LOCK(kq);
2033 		if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
2034 			/*
2035 			 * Do not process the influx notes, except for
2036 			 * the influx coming from the kq unlock in the
2037 			 * kqueue_scan().  In the later case, we do
2038 			 * not interfere with the scan, since the code
2039 			 * fragment in kqueue_scan() locks the knlist,
2040 			 * and cannot proceed until we finished.
2041 			 */
2042 			KQ_UNLOCK(kq);
2043 		} else if ((lockflags & KNF_NOKQLOCK) != 0) {
2044 			own_influx = (kn->kn_status & KN_INFLUX) == 0;
2045 			if (own_influx)
2046 				kn->kn_status |= KN_INFLUX;
2047 			KQ_UNLOCK(kq);
2048 			error = kn->kn_fop->f_event(kn, hint);
2049 			KQ_LOCK(kq);
2050 			if (own_influx)
2051 				kn->kn_status &= ~KN_INFLUX;
2052 			if (error)
2053 				KNOTE_ACTIVATE(kn, 1);
2054 			KQ_UNLOCK_FLUX(kq);
2055 		} else {
2056 			kn->kn_status |= KN_HASKQLOCK;
2057 			if (kn->kn_fop->f_event(kn, hint))
2058 				KNOTE_ACTIVATE(kn, 1);
2059 			kn->kn_status &= ~KN_HASKQLOCK;
2060 			KQ_UNLOCK(kq);
2061 		}
2062 	}
2063 	if ((lockflags & KNF_LISTLOCKED) == 0)
2064 		list->kl_unlock(list->kl_lockarg);
2065 }
2066 
2067 /*
2068  * add a knote to a knlist
2069  */
2070 void
2071 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
2072 {
2073 	KNL_ASSERT_LOCK(knl, islocked);
2074 	KQ_NOTOWNED(kn->kn_kq);
2075 	KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
2076 	    (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
2077 	if (!islocked)
2078 		knl->kl_lock(knl->kl_lockarg);
2079 	SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
2080 	if (!islocked)
2081 		knl->kl_unlock(knl->kl_lockarg);
2082 	KQ_LOCK(kn->kn_kq);
2083 	kn->kn_knlist = knl;
2084 	kn->kn_status &= ~KN_DETACHED;
2085 	KQ_UNLOCK(kn->kn_kq);
2086 }
2087 
2088 static void
2089 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked,
2090     int kqislocked)
2091 {
2092 	KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
2093 	KNL_ASSERT_LOCK(knl, knlislocked);
2094 	mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
2095 	if (!kqislocked)
2096 		KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
2097     ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
2098 	if (!knlislocked)
2099 		knl->kl_lock(knl->kl_lockarg);
2100 	SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
2101 	kn->kn_knlist = NULL;
2102 	if (!knlislocked)
2103 		kn_list_unlock(knl);
2104 	if (!kqislocked)
2105 		KQ_LOCK(kn->kn_kq);
2106 	kn->kn_status |= KN_DETACHED;
2107 	if (!kqislocked)
2108 		KQ_UNLOCK(kn->kn_kq);
2109 }
2110 
2111 /*
2112  * remove knote from the specified knlist
2113  */
2114 void
2115 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
2116 {
2117 
2118 	knlist_remove_kq(knl, kn, islocked, 0);
2119 }
2120 
2121 int
2122 knlist_empty(struct knlist *knl)
2123 {
2124 
2125 	KNL_ASSERT_LOCKED(knl);
2126 	return SLIST_EMPTY(&knl->kl_list);
2127 }
2128 
2129 static struct mtx	knlist_lock;
2130 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2131 	MTX_DEF);
2132 static void knlist_mtx_lock(void *arg);
2133 static void knlist_mtx_unlock(void *arg);
2134 
2135 static void
2136 knlist_mtx_lock(void *arg)
2137 {
2138 
2139 	mtx_lock((struct mtx *)arg);
2140 }
2141 
2142 static void
2143 knlist_mtx_unlock(void *arg)
2144 {
2145 
2146 	mtx_unlock((struct mtx *)arg);
2147 }
2148 
2149 static void
2150 knlist_mtx_assert_locked(void *arg)
2151 {
2152 
2153 	mtx_assert((struct mtx *)arg, MA_OWNED);
2154 }
2155 
2156 static void
2157 knlist_mtx_assert_unlocked(void *arg)
2158 {
2159 
2160 	mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2161 }
2162 
2163 static void
2164 knlist_rw_rlock(void *arg)
2165 {
2166 
2167 	rw_rlock((struct rwlock *)arg);
2168 }
2169 
2170 static void
2171 knlist_rw_runlock(void *arg)
2172 {
2173 
2174 	rw_runlock((struct rwlock *)arg);
2175 }
2176 
2177 static void
2178 knlist_rw_assert_locked(void *arg)
2179 {
2180 
2181 	rw_assert((struct rwlock *)arg, RA_LOCKED);
2182 }
2183 
2184 static void
2185 knlist_rw_assert_unlocked(void *arg)
2186 {
2187 
2188 	rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2189 }
2190 
2191 void
2192 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2193     void (*kl_unlock)(void *),
2194     void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2195 {
2196 
2197 	if (lock == NULL)
2198 		knl->kl_lockarg = &knlist_lock;
2199 	else
2200 		knl->kl_lockarg = lock;
2201 
2202 	if (kl_lock == NULL)
2203 		knl->kl_lock = knlist_mtx_lock;
2204 	else
2205 		knl->kl_lock = kl_lock;
2206 	if (kl_unlock == NULL)
2207 		knl->kl_unlock = knlist_mtx_unlock;
2208 	else
2209 		knl->kl_unlock = kl_unlock;
2210 	if (kl_assert_locked == NULL)
2211 		knl->kl_assert_locked = knlist_mtx_assert_locked;
2212 	else
2213 		knl->kl_assert_locked = kl_assert_locked;
2214 	if (kl_assert_unlocked == NULL)
2215 		knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2216 	else
2217 		knl->kl_assert_unlocked = kl_assert_unlocked;
2218 
2219 	knl->kl_autodestroy = 0;
2220 	SLIST_INIT(&knl->kl_list);
2221 }
2222 
2223 void
2224 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2225 {
2226 
2227 	knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2228 }
2229 
2230 struct knlist *
2231 knlist_alloc(struct mtx *lock)
2232 {
2233 	struct knlist *knl;
2234 
2235 	knl = malloc(sizeof(struct knlist), M_KQUEUE, M_WAITOK);
2236 	knlist_init_mtx(knl, lock);
2237 	return (knl);
2238 }
2239 
2240 void
2241 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2242 {
2243 
2244 	knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2245 	    knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2246 }
2247 
2248 void
2249 knlist_destroy(struct knlist *knl)
2250 {
2251 
2252 #ifdef INVARIANTS
2253 	/*
2254 	 * if we run across this error, we need to find the offending
2255 	 * driver and have it call knlist_clear or knlist_delete.
2256 	 */
2257 	if (!SLIST_EMPTY(&knl->kl_list))
2258 		printf("WARNING: destroying knlist w/ knotes on it!\n");
2259 #endif
2260 
2261 	knl->kl_lockarg = knl->kl_lock = knl->kl_unlock = NULL;
2262 	SLIST_INIT(&knl->kl_list);
2263 }
2264 
2265 void
2266 knlist_detach(struct knlist *knl)
2267 {
2268 
2269 	KNL_ASSERT_LOCKED(knl);
2270 	knl->kl_autodestroy = 1;
2271 	if (knlist_empty(knl)) {
2272 		knlist_destroy(knl);
2273 		free(knl, M_KQUEUE);
2274 	}
2275 }
2276 
2277 /*
2278  * Even if we are locked, we may need to drop the lock to allow any influx
2279  * knotes time to "settle".
2280  */
2281 void
2282 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2283 {
2284 	struct knote *kn, *kn2;
2285 	struct kqueue *kq;
2286 
2287 	KASSERT(!knl->kl_autodestroy, ("cleardel for autodestroy %p", knl));
2288 	if (islocked)
2289 		KNL_ASSERT_LOCKED(knl);
2290 	else {
2291 		KNL_ASSERT_UNLOCKED(knl);
2292 again:		/* need to reacquire lock since we have dropped it */
2293 		knl->kl_lock(knl->kl_lockarg);
2294 	}
2295 
2296 	SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2297 		kq = kn->kn_kq;
2298 		KQ_LOCK(kq);
2299 		if ((kn->kn_status & KN_INFLUX)) {
2300 			KQ_UNLOCK(kq);
2301 			continue;
2302 		}
2303 		knlist_remove_kq(knl, kn, 1, 1);
2304 		if (killkn) {
2305 			kn->kn_status |= KN_INFLUX | KN_DETACHED;
2306 			KQ_UNLOCK(kq);
2307 			knote_drop(kn, td);
2308 		} else {
2309 			/* Make sure cleared knotes disappear soon */
2310 			kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2311 			KQ_UNLOCK(kq);
2312 		}
2313 		kq = NULL;
2314 	}
2315 
2316 	if (!SLIST_EMPTY(&knl->kl_list)) {
2317 		/* there are still KN_INFLUX remaining */
2318 		kn = SLIST_FIRST(&knl->kl_list);
2319 		kq = kn->kn_kq;
2320 		KQ_LOCK(kq);
2321 		KASSERT(kn->kn_status & KN_INFLUX,
2322 		    ("knote removed w/o list lock"));
2323 		knl->kl_unlock(knl->kl_lockarg);
2324 		kq->kq_state |= KQ_FLUXWAIT;
2325 		msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2326 		kq = NULL;
2327 		goto again;
2328 	}
2329 
2330 	if (islocked)
2331 		KNL_ASSERT_LOCKED(knl);
2332 	else {
2333 		knl->kl_unlock(knl->kl_lockarg);
2334 		KNL_ASSERT_UNLOCKED(knl);
2335 	}
2336 }
2337 
2338 /*
2339  * Remove all knotes referencing a specified fd must be called with FILEDESC
2340  * lock.  This prevents a race where a new fd comes along and occupies the
2341  * entry and we attach a knote to the fd.
2342  */
2343 void
2344 knote_fdclose(struct thread *td, int fd)
2345 {
2346 	struct filedesc *fdp = td->td_proc->p_fd;
2347 	struct kqueue *kq;
2348 	struct knote *kn;
2349 	int influx;
2350 
2351 	FILEDESC_XLOCK_ASSERT(fdp);
2352 
2353 	/*
2354 	 * We shouldn't have to worry about new kevents appearing on fd
2355 	 * since filedesc is locked.
2356 	 */
2357 	TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2358 		KQ_LOCK(kq);
2359 
2360 again:
2361 		influx = 0;
2362 		while (kq->kq_knlistsize > fd &&
2363 		    (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2364 			if (kn->kn_status & KN_INFLUX) {
2365 				/* someone else might be waiting on our knote */
2366 				if (influx)
2367 					wakeup(kq);
2368 				kq->kq_state |= KQ_FLUXWAIT;
2369 				msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2370 				goto again;
2371 			}
2372 			kn->kn_status |= KN_INFLUX;
2373 			KQ_UNLOCK(kq);
2374 			if (!(kn->kn_status & KN_DETACHED))
2375 				kn->kn_fop->f_detach(kn);
2376 			knote_drop(kn, td);
2377 			influx = 1;
2378 			KQ_LOCK(kq);
2379 		}
2380 		KQ_UNLOCK_FLUX(kq);
2381 	}
2382 }
2383 
2384 static int
2385 knote_attach(struct knote *kn, struct kqueue *kq)
2386 {
2387 	struct klist *list;
2388 
2389 	KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
2390 	KQ_OWNED(kq);
2391 
2392 	if (kn->kn_fop->f_isfd) {
2393 		if (kn->kn_id >= kq->kq_knlistsize)
2394 			return ENOMEM;
2395 		list = &kq->kq_knlist[kn->kn_id];
2396 	} else {
2397 		if (kq->kq_knhash == NULL)
2398 			return ENOMEM;
2399 		list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2400 	}
2401 
2402 	SLIST_INSERT_HEAD(list, kn, kn_link);
2403 
2404 	return 0;
2405 }
2406 
2407 /*
2408  * knote must already have been detached using the f_detach method.
2409  * no lock need to be held, it is assumed that the KN_INFLUX flag is set
2410  * to prevent other removal.
2411  */
2412 static void
2413 knote_drop(struct knote *kn, struct thread *td)
2414 {
2415 	struct kqueue *kq;
2416 	struct klist *list;
2417 
2418 	kq = kn->kn_kq;
2419 
2420 	KQ_NOTOWNED(kq);
2421 	KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
2422 	    ("knote_drop called without KN_INFLUX set in kn_status"));
2423 
2424 	KQ_LOCK(kq);
2425 	if (kn->kn_fop->f_isfd)
2426 		list = &kq->kq_knlist[kn->kn_id];
2427 	else
2428 		list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2429 
2430 	if (!SLIST_EMPTY(list))
2431 		SLIST_REMOVE(list, kn, knote, kn_link);
2432 	if (kn->kn_status & KN_QUEUED)
2433 		knote_dequeue(kn);
2434 	KQ_UNLOCK_FLUX(kq);
2435 
2436 	if (kn->kn_fop->f_isfd) {
2437 		fdrop(kn->kn_fp, td);
2438 		kn->kn_fp = NULL;
2439 	}
2440 	kqueue_fo_release(kn->kn_kevent.filter);
2441 	kn->kn_fop = NULL;
2442 	knote_free(kn);
2443 }
2444 
2445 static void
2446 knote_enqueue(struct knote *kn)
2447 {
2448 	struct kqueue *kq = kn->kn_kq;
2449 
2450 	KQ_OWNED(kn->kn_kq);
2451 	KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2452 
2453 	TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2454 	kn->kn_status |= KN_QUEUED;
2455 	kq->kq_count++;
2456 	kqueue_wakeup(kq);
2457 }
2458 
2459 static void
2460 knote_dequeue(struct knote *kn)
2461 {
2462 	struct kqueue *kq = kn->kn_kq;
2463 
2464 	KQ_OWNED(kn->kn_kq);
2465 	KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2466 
2467 	TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2468 	kn->kn_status &= ~KN_QUEUED;
2469 	kq->kq_count--;
2470 }
2471 
2472 static void
2473 knote_init(void)
2474 {
2475 
2476 	knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2477 	    NULL, NULL, UMA_ALIGN_PTR, 0);
2478 }
2479 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2480 
2481 static struct knote *
2482 knote_alloc(int waitok)
2483 {
2484 
2485 	return (uma_zalloc(knote_zone, (waitok ? M_WAITOK : M_NOWAIT) |
2486 	    M_ZERO));
2487 }
2488 
2489 static void
2490 knote_free(struct knote *kn)
2491 {
2492 
2493 	uma_zfree(knote_zone, kn);
2494 }
2495 
2496 /*
2497  * Register the kev w/ the kq specified by fd.
2498  */
2499 int
2500 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2501 {
2502 	struct kqueue *kq;
2503 	struct file *fp;
2504 	cap_rights_t rights;
2505 	int error;
2506 
2507 	error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2508 	if (error != 0)
2509 		return (error);
2510 	if ((error = kqueue_acquire(fp, &kq)) != 0)
2511 		goto noacquire;
2512 
2513 	error = kqueue_register(kq, kev, td, waitok);
2514 
2515 	kqueue_release(kq, 0);
2516 
2517 noacquire:
2518 	fdrop(fp, td);
2519 
2520 	return error;
2521 }
2522