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