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