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