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