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