xref: /dragonfly/sys/kern/kern_event.c (revision 08e4ff68)
1 /*-
2  * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD: src/sys/kern/kern_event.c,v 1.2.2.10 2004/04/04 07:03:14 cperciva Exp $
27  */
28 
29 #include <sys/param.h>
30 #include <sys/systm.h>
31 #include <sys/kernel.h>
32 #include <sys/proc.h>
33 #include <sys/malloc.h>
34 #include <sys/unistd.h>
35 #include <sys/file.h>
36 #include <sys/lock.h>
37 #include <sys/fcntl.h>
38 #include <sys/queue.h>
39 #include <sys/event.h>
40 #include <sys/eventvar.h>
41 #include <sys/protosw.h>
42 #include <sys/socket.h>
43 #include <sys/socketvar.h>
44 #include <sys/stat.h>
45 #include <sys/sysctl.h>
46 #include <sys/sysmsg.h>
47 #include <sys/thread.h>
48 #include <sys/uio.h>
49 #include <sys/signalvar.h>
50 #include <sys/filio.h>
51 #include <sys/ktr.h>
52 #include <sys/spinlock.h>
53 
54 #include <sys/thread2.h>
55 #include <sys/file2.h>
56 #include <sys/mplock2.h>
57 #include <sys/spinlock2.h>
58 
59 #define EVENT_REGISTER	1
60 #define EVENT_PROCESS	2
61 
62 static MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
63 
64 struct kevent_copyin_args {
65 	const struct kevent_args *ka;
66 	struct kevent		*eventlist;
67 	const struct kevent	*changelist;
68 	int			pchanges;
69 };
70 
71 #define KNOTE_CACHE_MAX		64
72 
73 struct knote_cache_list {
74 	struct klist		knote_cache;
75 	int			knote_cache_cnt;
76 } __cachealign;
77 
78 static int	kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
79 		    struct knote *marker, int closedcounter, int scan_flags);
80 static int 	kqueue_read(struct file *fp, struct uio *uio,
81 		    struct ucred *cred, int flags);
82 static int	kqueue_write(struct file *fp, struct uio *uio,
83 		    struct ucred *cred, int flags);
84 static int	kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
85 		    struct ucred *cred, struct sysmsg *msg);
86 static int 	kqueue_kqfilter(struct file *fp, struct knote *kn);
87 static int 	kqueue_stat(struct file *fp, struct stat *st,
88 		    struct ucred *cred);
89 static int 	kqueue_close(struct file *fp);
90 static void	kqueue_wakeup(struct kqueue *kq);
91 static int	filter_attach(struct knote *kn);
92 static int	filter_event(struct knote *kn, long hint);
93 
94 /*
95  * MPSAFE
96  */
97 static struct fileops kqueueops = {
98 	.fo_read = kqueue_read,
99 	.fo_write = kqueue_write,
100 	.fo_ioctl = kqueue_ioctl,
101 	.fo_kqfilter = kqueue_kqfilter,
102 	.fo_stat = kqueue_stat,
103 	.fo_close = kqueue_close,
104 	.fo_shutdown = nofo_shutdown
105 };
106 
107 static void 	knote_attach(struct knote *kn);
108 static void 	knote_drop(struct knote *kn);
109 static void	knote_detach_and_drop(struct knote *kn);
110 static void 	knote_enqueue(struct knote *kn);
111 static void 	knote_dequeue(struct knote *kn);
112 static struct 	knote *knote_alloc(void);
113 static void 	knote_free(struct knote *kn);
114 
115 static void	precise_sleep_intr(systimer_t info, int in_ipi,
116 				   struct intrframe *frame);
117 static int	precise_sleep(void *ident, int flags, const char *wmesg,
118 			      int us);
119 
120 static void	filt_kqdetach(struct knote *kn);
121 static int	filt_kqueue(struct knote *kn, long hint);
122 static int	filt_procattach(struct knote *kn);
123 static void	filt_procdetach(struct knote *kn);
124 static int	filt_proc(struct knote *kn, long hint);
125 static int	filt_fileattach(struct knote *kn);
126 static void	filt_timerexpire(void *knx);
127 static int	filt_timerattach(struct knote *kn);
128 static void	filt_timerdetach(struct knote *kn);
129 static int	filt_timer(struct knote *kn, long hint);
130 static int	filt_userattach(struct knote *kn);
131 static void	filt_userdetach(struct knote *kn);
132 static int	filt_user(struct knote *kn, long hint);
133 static void	filt_usertouch(struct knote *kn, struct kevent *kev,
134 				u_long type);
135 static int	filt_fsattach(struct knote *kn);
136 static void	filt_fsdetach(struct knote *kn);
137 static int	filt_fs(struct knote *kn, long hint);
138 
139 static struct filterops file_filtops =
140 	{ FILTEROP_ISFD | FILTEROP_MPSAFE, filt_fileattach, NULL, NULL };
141 static struct filterops kqread_filtops =
142 	{ FILTEROP_ISFD | FILTEROP_MPSAFE, NULL, filt_kqdetach, filt_kqueue };
143 static struct filterops proc_filtops =
144 	{ FILTEROP_MPSAFE, filt_procattach, filt_procdetach, filt_proc };
145 static struct filterops timer_filtops =
146 	{ FILTEROP_MPSAFE, filt_timerattach, filt_timerdetach, filt_timer };
147 static struct filterops user_filtops =
148 	{ FILTEROP_MPSAFE, filt_userattach, filt_userdetach, filt_user };
149 static struct filterops fs_filtops =
150 	{ FILTEROP_MPSAFE, filt_fsattach, filt_fsdetach, filt_fs };
151 
152 static int 		kq_ncallouts = 0;
153 static int 		kq_calloutmax = 65536;
154 SYSCTL_INT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
155     &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
156 static int		kq_checkloop = 1000000;
157 SYSCTL_INT(_kern, OID_AUTO, kq_checkloop, CTLFLAG_RW,
158     &kq_checkloop, 0, "Maximum number of loops for kqueue scan");
159 static int		kq_sleep_threshold = 20000;
160 SYSCTL_INT(_kern, OID_AUTO, kq_sleep_threshold, CTLFLAG_RW,
161     &kq_sleep_threshold, 0, "Minimum sleep duration without busy-looping");
162 
163 #define KNOTE_ACTIVATE(kn) do { 					\
164 	kn->kn_status |= KN_ACTIVE;					\
165 	if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0)		\
166 		knote_enqueue(kn);					\
167 } while(0)
168 
169 #define	KN_HASHSIZE		64		/* XXX should be tunable */
170 #define KN_HASH(val, mask)	(((val) ^ (val >> 8)) & (mask))
171 
172 extern struct filterops aio_filtops;
173 extern struct filterops sig_filtops;
174 
175 /*
176  * Table for for all system-defined filters.
177  */
178 static struct filterops *sysfilt_ops[] = {
179 	&file_filtops,			/* EVFILT_READ */
180 	&file_filtops,			/* EVFILT_WRITE */
181 	&aio_filtops,			/* EVFILT_AIO */
182 	&file_filtops,			/* EVFILT_VNODE */
183 	&proc_filtops,			/* EVFILT_PROC */
184 	&sig_filtops,			/* EVFILT_SIGNAL */
185 	&timer_filtops,			/* EVFILT_TIMER */
186 	&file_filtops,			/* EVFILT_EXCEPT */
187 	&user_filtops,			/* EVFILT_USER */
188 	&fs_filtops,			/* EVFILT_FS */
189 };
190 
191 static struct knote_cache_list	knote_cache_lists[MAXCPU];
192 
193 /*
194  * Acquire a knote, return non-zero on success, 0 on failure.
195  *
196  * If we cannot acquire the knote we sleep and return 0.  The knote
197  * may be stale on return in this case and the caller must restart
198  * whatever loop they are in.
199  *
200  * Related kq token must be held.
201  */
202 static __inline int
203 knote_acquire(struct knote *kn)
204 {
205 	if (kn->kn_status & KN_PROCESSING) {
206 		kn->kn_status |= KN_WAITING | KN_REPROCESS;
207 		tsleep(kn, 0, "kqepts", hz);
208 		/* knote may be stale now */
209 		return(0);
210 	}
211 	kn->kn_status |= KN_PROCESSING;
212 	return(1);
213 }
214 
215 /*
216  * Release an acquired knote, clearing KN_PROCESSING and handling any
217  * KN_REPROCESS events.
218  *
219  * Caller must be holding the related kq token
220  *
221  * Non-zero is returned if the knote is destroyed or detached.
222  */
223 static __inline int
224 knote_release(struct knote *kn)
225 {
226 	int ret;
227 
228 	while (kn->kn_status & KN_REPROCESS) {
229 		kn->kn_status &= ~KN_REPROCESS;
230 		if (kn->kn_status & KN_WAITING) {
231 			kn->kn_status &= ~KN_WAITING;
232 			wakeup(kn);
233 		}
234 		if (kn->kn_status & KN_DELETING) {
235 			knote_detach_and_drop(kn);
236 			return(1);
237 			/* NOT REACHED */
238 		}
239 		if (filter_event(kn, 0))
240 			KNOTE_ACTIVATE(kn);
241 	}
242 	if (kn->kn_status & KN_DETACHED)
243 		ret = 1;
244 	else
245 		ret = 0;
246 	kn->kn_status &= ~KN_PROCESSING;
247 	/* kn should not be accessed anymore */
248 	return ret;
249 }
250 
251 static int
252 filt_fileattach(struct knote *kn)
253 {
254 	return (fo_kqfilter(kn->kn_fp, kn));
255 }
256 
257 /*
258  * MPSAFE
259  */
260 static int
261 kqueue_kqfilter(struct file *fp, struct knote *kn)
262 {
263 	struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
264 
265 	if (kn->kn_filter != EVFILT_READ)
266 		return (EOPNOTSUPP);
267 
268 	kn->kn_fop = &kqread_filtops;
269 	knote_insert(&kq->kq_kqinfo.ki_note, kn);
270 	return (0);
271 }
272 
273 static void
274 filt_kqdetach(struct knote *kn)
275 {
276 	struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
277 
278 	knote_remove(&kq->kq_kqinfo.ki_note, kn);
279 }
280 
281 /*ARGSUSED*/
282 static int
283 filt_kqueue(struct knote *kn, long hint)
284 {
285 	struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
286 
287 	kn->kn_data = kq->kq_count;
288 	return (kn->kn_data > 0);
289 }
290 
291 static int
292 filt_procattach(struct knote *kn)
293 {
294 	struct proc *p;
295 	int immediate;
296 
297 	immediate = 0;
298 	p = pfind(kn->kn_id);
299 	if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
300 		p = zpfind(kn->kn_id);
301 		immediate = 1;
302 	}
303 	if (p == NULL) {
304 		return (ESRCH);
305 	}
306 	if (!PRISON_CHECK(curthread->td_ucred, p->p_ucred)) {
307 		if (p)
308 			PRELE(p);
309 		return (EACCES);
310 	}
311 
312 	lwkt_gettoken(&p->p_token);
313 	kn->kn_ptr.p_proc = p;
314 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
315 
316 	/*
317 	 * internal flag indicating registration done by kernel
318 	 */
319 	if (kn->kn_flags & EV_FLAG1) {
320 		kn->kn_data = kn->kn_sdata;		/* ppid */
321 		kn->kn_fflags = NOTE_CHILD;
322 		kn->kn_flags &= ~EV_FLAG1;
323 	}
324 
325 	knote_insert(&p->p_klist, kn);
326 
327 	/*
328 	 * Immediately activate any exit notes if the target process is a
329 	 * zombie.  This is necessary to handle the case where the target
330 	 * process, e.g. a child, dies before the kevent is negistered.
331 	 */
332 	if (immediate && filt_proc(kn, NOTE_EXIT))
333 		KNOTE_ACTIVATE(kn);
334 	lwkt_reltoken(&p->p_token);
335 	PRELE(p);
336 
337 	return (0);
338 }
339 
340 /*
341  * The knote may be attached to a different process, which may exit,
342  * leaving nothing for the knote to be attached to.  So when the process
343  * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
344  * it will be deleted when read out.  However, as part of the knote deletion,
345  * this routine is called, so a check is needed to avoid actually performing
346  * a detach, because the original process does not exist any more.
347  */
348 static void
349 filt_procdetach(struct knote *kn)
350 {
351 	struct proc *p;
352 
353 	if (kn->kn_status & KN_DETACHED)
354 		return;
355 	p = kn->kn_ptr.p_proc;
356 	knote_remove(&p->p_klist, kn);
357 }
358 
359 static int
360 filt_proc(struct knote *kn, long hint)
361 {
362 	u_int event;
363 
364 	/*
365 	 * mask off extra data
366 	 */
367 	event = (u_int)hint & NOTE_PCTRLMASK;
368 
369 	/*
370 	 * if the user is interested in this event, record it.
371 	 */
372 	if (kn->kn_sfflags & event)
373 		kn->kn_fflags |= event;
374 
375 	/*
376 	 * Process is gone, so flag the event as finished.  Detach the
377 	 * knote from the process now because the process will be poof,
378 	 * gone later on.
379 	 */
380 	if (event == NOTE_EXIT) {
381 		struct proc *p = kn->kn_ptr.p_proc;
382 		if ((kn->kn_status & KN_DETACHED) == 0) {
383 			PHOLD(p);
384 			knote_remove(&p->p_klist, kn);
385 			kn->kn_status |= KN_DETACHED;
386 			kn->kn_data = p->p_xstat;
387 			kn->kn_ptr.p_proc = NULL;
388 			PRELE(p);
389 		}
390 		kn->kn_flags |= (EV_EOF | EV_NODATA | EV_ONESHOT);
391 		return (1);
392 	}
393 
394 	/*
395 	 * process forked, and user wants to track the new process,
396 	 * so attach a new knote to it, and immediately report an
397 	 * event with the parent's pid.
398 	 */
399 	if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
400 		struct kevent kev;
401 		int error;
402 		int n;
403 
404 		/*
405 		 * register knote with new process.
406 		 */
407 		kev.ident = hint & NOTE_PDATAMASK;	/* pid */
408 		kev.filter = kn->kn_filter;
409 		kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
410 		kev.fflags = kn->kn_sfflags;
411 		kev.data = kn->kn_id;			/* parent */
412 		kev.udata = kn->kn_kevent.udata;	/* preserve udata */
413 		n = 1;
414 		error = kqueue_register(kn->kn_kq, &kev, &n);
415 		if (error)
416 			kn->kn_fflags |= NOTE_TRACKERR;
417 	}
418 
419 	return (kn->kn_fflags != 0);
420 }
421 
422 static void
423 filt_timerreset(struct knote *kn)
424 {
425 	struct callout *calloutp;
426 	struct timeval tv;
427 	int tticks;
428 
429 	tv.tv_sec = kn->kn_sdata / 1000;
430 	tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
431 	tticks = tvtohz_high(&tv);
432 	calloutp = (struct callout *)kn->kn_hook;
433 	callout_reset(calloutp, tticks, filt_timerexpire, kn);
434 }
435 
436 /*
437  * The callout interlocks with callout_stop() but can still
438  * race a deletion so if KN_DELETING is set we just don't touch
439  * the knote.
440  */
441 static void
442 filt_timerexpire(void *knx)
443 {
444 	struct knote *kn = knx;
445 	struct kqueue *kq = kn->kn_kq;
446 
447 	lwkt_getpooltoken(kq);
448 
449 	/*
450 	 * Open knote_acquire(), since we can't sleep in callout,
451 	 * however, we do need to record this expiration.
452 	 */
453 	kn->kn_data++;
454 	if (kn->kn_status & KN_PROCESSING) {
455 		kn->kn_status |= KN_REPROCESS;
456 		if ((kn->kn_status & KN_DELETING) == 0 &&
457 		    (kn->kn_flags & EV_ONESHOT) == 0)
458 			filt_timerreset(kn);
459 		lwkt_relpooltoken(kq);
460 		return;
461 	}
462 	KASSERT((kn->kn_status & KN_DELETING) == 0,
463 	    ("acquire a deleting knote %#x", kn->kn_status));
464 	kn->kn_status |= KN_PROCESSING;
465 
466 	KNOTE_ACTIVATE(kn);
467 	if ((kn->kn_flags & EV_ONESHOT) == 0)
468 		filt_timerreset(kn);
469 
470 	knote_release(kn);
471 
472 	lwkt_relpooltoken(kq);
473 }
474 
475 /*
476  * data contains amount of time to sleep, in milliseconds
477  */
478 static int
479 filt_timerattach(struct knote *kn)
480 {
481 	struct callout *calloutp;
482 	int prev_ncallouts;
483 
484 	prev_ncallouts = atomic_fetchadd_int(&kq_ncallouts, 1);
485 	if (prev_ncallouts >= kq_calloutmax) {
486 		atomic_subtract_int(&kq_ncallouts, 1);
487 		kn->kn_hook = NULL;
488 		return (ENOMEM);
489 	}
490 
491 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
492 	calloutp = kmalloc(sizeof(*calloutp), M_KQUEUE, M_WAITOK);
493 	callout_init_mp(calloutp);
494 	kn->kn_hook = (caddr_t)calloutp;
495 
496 	filt_timerreset(kn);
497 	return (0);
498 }
499 
500 /*
501  * This function is called with the knote flagged locked but it is
502  * still possible to race a callout event due to the callback blocking.
503  */
504 static void
505 filt_timerdetach(struct knote *kn)
506 {
507 	struct callout *calloutp;
508 
509 	calloutp = (struct callout *)kn->kn_hook;
510 	callout_terminate(calloutp);
511 	kn->kn_hook = NULL;
512 	kfree(calloutp, M_KQUEUE);
513 	atomic_subtract_int(&kq_ncallouts, 1);
514 }
515 
516 static int
517 filt_timer(struct knote *kn, long hint)
518 {
519 	return (kn->kn_data != 0);
520 }
521 
522 /*
523  * EVFILT_USER
524  */
525 static int
526 filt_userattach(struct knote *kn)
527 {
528 	u_int ffctrl;
529 
530 	kn->kn_hook = NULL;
531 	if (kn->kn_sfflags & NOTE_TRIGGER)
532 		kn->kn_ptr.hookid = 1;
533 	else
534 		kn->kn_ptr.hookid = 0;
535 
536 	ffctrl = kn->kn_sfflags & NOTE_FFCTRLMASK;
537 	kn->kn_sfflags &= NOTE_FFLAGSMASK;
538 	switch (ffctrl) {
539 	case NOTE_FFNOP:
540 		break;
541 
542 	case NOTE_FFAND:
543 		kn->kn_fflags &= kn->kn_sfflags;
544 		break;
545 
546 	case NOTE_FFOR:
547 		kn->kn_fflags |= kn->kn_sfflags;
548 		break;
549 
550 	case NOTE_FFCOPY:
551 		kn->kn_fflags = kn->kn_sfflags;
552 		break;
553 
554 	default:
555 		/* XXX Return error? */
556 		break;
557 	}
558 	/* We just happen to copy this value as well. Undocumented. */
559 	kn->kn_data = kn->kn_sdata;
560 
561 	return 0;
562 }
563 
564 static void
565 filt_userdetach(struct knote *kn)
566 {
567 	/* nothing to do */
568 }
569 
570 static int
571 filt_user(struct knote *kn, long hint)
572 {
573 	return (kn->kn_ptr.hookid);
574 }
575 
576 static void
577 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
578 {
579 	u_int ffctrl;
580 
581 	switch (type) {
582 	case EVENT_REGISTER:
583 		if (kev->fflags & NOTE_TRIGGER)
584 			kn->kn_ptr.hookid = 1;
585 
586 		ffctrl = kev->fflags & NOTE_FFCTRLMASK;
587 		kev->fflags &= NOTE_FFLAGSMASK;
588 		switch (ffctrl) {
589 		case NOTE_FFNOP:
590 			break;
591 
592 		case NOTE_FFAND:
593 			kn->kn_fflags &= kev->fflags;
594 			break;
595 
596 		case NOTE_FFOR:
597 			kn->kn_fflags |= kev->fflags;
598 			break;
599 
600 		case NOTE_FFCOPY:
601 			kn->kn_fflags = kev->fflags;
602 			break;
603 
604 		default:
605 			/* XXX Return error? */
606 			break;
607 		}
608 		/* We just happen to copy this value as well. Undocumented. */
609 		kn->kn_data = kev->data;
610 
611 		/*
612 		 * This is not the correct use of EV_CLEAR in an event
613 		 * modification, it should have been passed as a NOTE instead.
614 		 * But we need to maintain compatibility with Apple & FreeBSD.
615 		 *
616 		 * Note however that EV_CLEAR can still be used when doing
617 		 * the initial registration of the event and works as expected
618 		 * (clears the event on reception).
619 		 */
620 		if (kev->flags & EV_CLEAR) {
621 			kn->kn_ptr.hookid = 0;
622 			/*
623 			 * Clearing kn->kn_data is fine, since it gets set
624 			 * every time anyway. We just shouldn't clear
625 			 * kn->kn_fflags here, since that would limit the
626 			 * possible uses of this API. NOTE_FFAND or
627 			 * NOTE_FFCOPY should be used for explicitly clearing
628 			 * kn->kn_fflags.
629 			 */
630 			kn->kn_data = 0;
631 		}
632 		break;
633 
634         case EVENT_PROCESS:
635 		*kev = kn->kn_kevent;
636 		kev->fflags = kn->kn_fflags;
637 		kev->data = kn->kn_data;
638 		if (kn->kn_flags & EV_CLEAR) {
639 			kn->kn_ptr.hookid = 0;
640 			/* kn_data, kn_fflags handled by parent */
641 		}
642 		break;
643 
644 	default:
645 		panic("filt_usertouch() - invalid type (%ld)", type);
646 		break;
647 	}
648 }
649 
650 /*
651  * EVFILT_FS
652  */
653 struct klist fs_klist = SLIST_HEAD_INITIALIZER(&fs_klist);
654 
655 static int
656 filt_fsattach(struct knote *kn)
657 {
658 	kn->kn_flags |= EV_CLEAR;
659 	knote_insert(&fs_klist, kn);
660 
661 	return (0);
662 }
663 
664 static void
665 filt_fsdetach(struct knote *kn)
666 {
667 	knote_remove(&fs_klist, kn);
668 }
669 
670 static int
671 filt_fs(struct knote *kn, long hint)
672 {
673 	kn->kn_fflags |= hint;
674 	return (kn->kn_fflags != 0);
675 }
676 
677 /*
678  * Initialize a kqueue.
679  *
680  * NOTE: The lwp/proc code initializes a kqueue for select/poll ops.
681  */
682 void
683 kqueue_init(struct kqueue *kq, struct filedesc *fdp)
684 {
685 	bzero(kq, sizeof(*kq));
686 	TAILQ_INIT(&kq->kq_knpend);
687 	TAILQ_INIT(&kq->kq_knlist);
688 	kq->kq_fdp = fdp;
689 	SLIST_INIT(&kq->kq_kqinfo.ki_note);
690 }
691 
692 /*
693  * Terminate a kqueue.  Freeing the actual kq itself is left up to the
694  * caller (it might be embedded in a lwp so we don't do it here).
695  *
696  * The kq's knlist must be completely eradicated so block on any
697  * processing races.
698  */
699 void
700 kqueue_terminate(struct kqueue *kq)
701 {
702 	struct knote *kn;
703 
704 	lwkt_getpooltoken(kq);
705 	while ((kn = TAILQ_FIRST(&kq->kq_knlist)) != NULL) {
706 		if (knote_acquire(kn))
707 			knote_detach_and_drop(kn);
708 	}
709 	lwkt_relpooltoken(kq);
710 
711 	if (kq->kq_knhash) {
712 		hashdestroy(kq->kq_knhash, M_KQUEUE, kq->kq_knhashmask);
713 		kq->kq_knhash = NULL;
714 		kq->kq_knhashmask = 0;
715 	}
716 }
717 
718 /*
719  * MPSAFE
720  */
721 int
722 sys_kqueue(struct sysmsg *sysmsg, const struct kqueue_args *uap)
723 {
724 	struct thread *td = curthread;
725 	struct kqueue *kq;
726 	struct file *fp;
727 	int fd, error;
728 
729 	error = falloc(td->td_lwp, &fp, &fd);
730 	if (error)
731 		return (error);
732 	fp->f_flag = FREAD | FWRITE;
733 	fp->f_type = DTYPE_KQUEUE;
734 	fp->f_ops = &kqueueops;
735 
736 	kq = kmalloc(sizeof(struct kqueue), M_KQUEUE, M_WAITOK | M_ZERO);
737 	kqueue_init(kq, td->td_proc->p_fd);
738 	fp->f_data = kq;
739 
740 	fsetfd(kq->kq_fdp, fp, fd);
741 	sysmsg->sysmsg_result = fd;
742 	fdrop(fp);
743 	return (error);
744 }
745 
746 /*
747  * Copy 'count' items into the destination list pointed to by uap->eventlist.
748  */
749 static int
750 kevent_copyout(void *arg, struct kevent *kevp, int count, int *res)
751 {
752 	struct kevent_copyin_args *kap;
753 	int error;
754 
755 	kap = (struct kevent_copyin_args *)arg;
756 
757 	error = copyout(kevp, kap->eventlist, count * sizeof(*kevp));
758 	if (error == 0) {
759 		kap->eventlist += count;
760 		*res += count;
761 	} else {
762 		*res = -1;
763 	}
764 
765 	return (error);
766 }
767 
768 /*
769  * Copy at most 'max' items from the list pointed to by kap->changelist,
770  * return number of items in 'events'.
771  */
772 static int
773 kevent_copyin(void *arg, struct kevent *kevp, int max, int *events)
774 {
775 	struct kevent_copyin_args *kap;
776 	int error, count;
777 
778 	kap = (struct kevent_copyin_args *)arg;
779 
780 	count = min(kap->ka->nchanges - kap->pchanges, max);
781 	error = copyin(kap->changelist, kevp, count * sizeof *kevp);
782 	if (error == 0) {
783 		kap->changelist += count;
784 		kap->pchanges += count;
785 		*events = count;
786 	}
787 
788 	return (error);
789 }
790 
791 /*
792  * MPSAFE
793  */
794 int
795 kern_kevent(struct kqueue *kq, int nevents, int *res, void *uap,
796 	    k_copyin_fn kevent_copyinfn, k_copyout_fn kevent_copyoutfn,
797 	    struct timespec *tsp_in, int flags)
798 {
799 	struct kevent *kevp;
800 	struct timespec *tsp, ats;
801 	int i, n, total, error, nerrors = 0;
802 	int gobbled;
803 	int lres;
804 	int limit = kq_checkloop;
805 	int closedcounter;
806 	int scan_flags;
807 	struct kevent kev[KQ_NEVENTS];
808 	struct knote marker;
809 	struct lwkt_token *tok;
810 
811 	if (tsp_in == NULL || tsp_in->tv_sec || tsp_in->tv_nsec)
812 		atomic_set_int(&curthread->td_mpflags, TDF_MP_BATCH_DEMARC);
813 
814 	tsp = tsp_in;
815 	*res = 0;
816 
817 	closedcounter = kq->kq_fdp->fd_closedcounter;
818 
819 	for (;;) {
820 		n = 0;
821 		error = kevent_copyinfn(uap, kev, KQ_NEVENTS, &n);
822 		if (error)
823 			return error;
824 		if (n == 0)
825 			break;
826 		for (i = 0; i < n; ++i)
827 			kev[i].flags &= ~EV_SYSFLAGS;
828 		for (i = 0; i < n; ++i) {
829 			gobbled = n - i;
830 			error = kqueue_register(kq, &kev[i], &gobbled);
831 			i += gobbled - 1;
832 			kevp = &kev[i];
833 
834 			/*
835 			 * If a registration returns an error we
836 			 * immediately post the error.  The kevent()
837 			 * call itself will fail with the error if
838 			 * no space is available for posting.
839 			 *
840 			 * Such errors normally bypass the timeout/blocking
841 			 * code.  However, if the copyoutfn function refuses
842 			 * to post the error (see sys_poll()), then we
843 			 * ignore it too.
844 			 */
845 			if (error || (kevp->flags & EV_RECEIPT)) {
846 				kevp->flags = EV_ERROR;
847 				kevp->data = error;
848 				lres = *res;
849 				kevent_copyoutfn(uap, kevp, 1, res);
850 				if (*res < 0) {
851 					return error;
852 				} else if (lres != *res) {
853 					nevents--;
854 					nerrors++;
855 				}
856 			}
857 		}
858 	}
859 	if (nerrors)
860 		return 0;
861 
862 	/*
863 	 * Acquire/wait for events - setup timeout
864 	 *
865 	 * If no timeout specified clean up the run path by clearing the
866 	 * PRECISE flag.
867 	 */
868 	if (tsp != NULL) {
869 		if (tsp->tv_sec || tsp->tv_nsec) {
870 			getnanouptime(&ats);
871 			timespecadd(tsp, &ats, tsp);	/* tsp = target time */
872 		}
873 	} else {
874 		flags &= ~KEVENT_TIMEOUT_PRECISE;
875 	}
876 
877 	/*
878 	 * Loop as required.
879 	 *
880 	 * Collect as many events as we can. Sleeping on successive
881 	 * loops is disabled if copyoutfn has incremented (*res).
882 	 *
883 	 * The loop stops if an error occurs, all events have been
884 	 * scanned (the marker has been reached), or fewer than the
885 	 * maximum number of events is found.
886 	 *
887 	 * The copyoutfn function does not have to increment (*res) in
888 	 * order for the loop to continue.
889 	 *
890 	 * NOTE: doselect() usually passes 0x7FFFFFFF for nevents.
891 	 */
892 	total = 0;
893 	error = 0;
894 	marker.kn_filter = EVFILT_MARKER;
895 	marker.kn_status = KN_PROCESSING;
896 
897 	tok = lwkt_token_pool_lookup(kq);
898 	scan_flags = KEVENT_SCAN_INSERT_MARKER;
899 
900 	while ((n = nevents - total) > 0) {
901 		if (n > KQ_NEVENTS)
902 			n = KQ_NEVENTS;
903 
904 		/*
905 		 * Process all received events
906 		 * Account for all non-spurious events in our total
907 		 */
908 		i = kqueue_scan(kq, kev, n, &marker, closedcounter, scan_flags);
909 		scan_flags = KEVENT_SCAN_KEEP_MARKER;
910 		if (i) {
911 			lres = *res;
912 			error = kevent_copyoutfn(uap, kev, i, res);
913 			total += *res - lres;
914 			if (error)
915 				break;
916 		}
917 		if (limit && --limit == 0)
918 			panic("kqueue: checkloop failed i=%d", i);
919 
920 		/*
921 		 * Normally when fewer events are returned than requested
922 		 * we can stop.  However, if only spurious events were
923 		 * collected the copyout will not bump (*res) and we have
924 		 * to continue.
925 		 */
926 		if (i < n && *res)
927 			break;
928 
929 		/*
930 		 * If no events were recorded (no events happened or the events
931 		 * that did happen were all spurious), block until an event
932 		 * occurs or the timeout occurs and reload the marker.
933 		 *
934 		 * If we saturated n (i == n) loop up without sleeping to
935 		 * continue processing the list.
936 		 */
937 		if (i != n && kq->kq_count == 0 && *res == 0) {
938 			int timeout;
939 			int ustimeout;
940 
941 			if (tsp == NULL) {
942 				timeout = 0;
943 				ustimeout = 0;
944 			} else if (tsp->tv_sec == 0 && tsp->tv_nsec == 0) {
945 				error = EWOULDBLOCK;
946 				break;
947 			} else {
948 				struct timespec atx = *tsp;
949 
950 				getnanouptime(&ats);
951 				timespecsub(&atx, &ats, &atx);
952 				if (atx.tv_sec < 0 ||
953 				    (atx.tv_sec == 0 && atx.tv_nsec <= 0)) {
954 					error = EWOULDBLOCK;
955 					break;
956 				}
957 				if (flags & KEVENT_TIMEOUT_PRECISE) {
958 					if (atx.tv_sec == 0 &&
959 					    atx.tv_nsec < kq_sleep_threshold) {
960 						ustimeout = kq_sleep_threshold /
961 							    1000;
962 					} else if (atx.tv_sec < 60) {
963 						ustimeout =
964 							atx.tv_sec * 1000000 +
965 							atx.tv_nsec / 1000;
966 					} else {
967 						ustimeout = 60 * 1000000;
968 					}
969 					if (ustimeout == 0)
970 						ustimeout = 1;
971 					timeout = 0;
972 				} else if (atx.tv_sec > 60 * 60) {
973 					timeout = 60 * 60 * hz;
974 					ustimeout = 0;
975 				} else {
976 					timeout = tstohz_high(&atx);
977 					ustimeout = 0;
978 				}
979 			}
980 
981 			lwkt_gettoken(tok);
982 			if (kq->kq_count == 0) {
983 				kq->kq_sleep_cnt++;
984 				if (__predict_false(kq->kq_sleep_cnt == 0)) {
985 					/*
986 					 * Guard against possible wrapping.  And
987 					 * set it to 2, so that kqueue_wakeup()
988 					 * can wake everyone up.
989 					 */
990 					kq->kq_sleep_cnt = 2;
991 				}
992 				if (flags & KEVENT_TIMEOUT_PRECISE) {
993 					error = precise_sleep(kq, PCATCH,
994 							"kqread", ustimeout);
995 				} else {
996 					error = tsleep(kq, PCATCH,
997 							"kqread", timeout);
998 				}
999 
1000 				/* don't restart after signals... */
1001 				if (error == ERESTART)
1002 					error = EINTR;
1003 				if (error == EWOULDBLOCK)
1004 					error = 0;
1005 				if (error) {
1006 					lwkt_reltoken(tok);
1007 					break;
1008 				}
1009 				scan_flags = KEVENT_SCAN_RELOAD_MARKER;
1010 			}
1011 			lwkt_reltoken(tok);
1012 		}
1013 
1014 		/*
1015 		 * Deal with an edge case where spurious events can cause
1016 		 * a loop to occur without moving the marker.  This can
1017 		 * prevent kqueue_scan() from picking up new events which
1018 		 * race us.  We must be sure to move the marker for this
1019 		 * case.
1020 		 *
1021 		 * NOTE: We do not want to move the marker if events
1022 		 *	 were scanned because normal kqueue operations
1023 		 *	 may reactivate events.  Moving the marker in
1024 		 *	 that case could result in duplicates for the
1025 		 *	 same event.
1026 		 */
1027 		if (i == 0)
1028 			scan_flags = KEVENT_SCAN_RELOAD_MARKER;
1029 	}
1030 
1031 	/*
1032 	 * Remove the marker
1033 	 */
1034 	if (scan_flags != KEVENT_SCAN_INSERT_MARKER) {
1035 		lwkt_gettoken(tok);
1036 		TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
1037 		lwkt_reltoken(tok);
1038 	}
1039 
1040 	/* Timeouts do not return EWOULDBLOCK. */
1041 	if (error == EWOULDBLOCK)
1042 		error = 0;
1043 	return error;
1044 }
1045 
1046 /*
1047  * MPALMOSTSAFE
1048  */
1049 int
1050 sys_kevent(struct sysmsg *sysmsg, const struct kevent_args *uap)
1051 {
1052 	struct thread *td = curthread;
1053 	struct timespec ts, *tsp;
1054 	struct kqueue *kq;
1055 	struct file *fp = NULL;
1056 	struct kevent_copyin_args *kap, ka;
1057 	int error;
1058 
1059 	if (uap->timeout) {
1060 		error = copyin(uap->timeout, &ts, sizeof(ts));
1061 		if (error)
1062 			return (error);
1063 		tsp = &ts;
1064 	} else {
1065 		tsp = NULL;
1066 	}
1067 	fp = holdfp(td, uap->fd, -1);
1068 	if (fp == NULL)
1069 		return (EBADF);
1070 	if (fp->f_type != DTYPE_KQUEUE) {
1071 		fdrop(fp);
1072 		return (EBADF);
1073 	}
1074 
1075 	kq = (struct kqueue *)fp->f_data;
1076 
1077 	kap = &ka;
1078 	kap->ka = uap;
1079 	kap->pchanges = 0;
1080 	kap->eventlist = uap->eventlist;
1081 	kap->changelist = uap->changelist;
1082 
1083 	error = kern_kevent(kq, uap->nevents, &sysmsg->sysmsg_result, kap,
1084 			    kevent_copyin, kevent_copyout, tsp, 0);
1085 
1086 	dropfp(td, uap->fd, fp);
1087 
1088 	return (error);
1089 }
1090 
1091 /*
1092  * Efficiently load multiple file pointers.  This significantly reduces
1093  * threaded overhead.  When doing simple polling we can depend on the
1094  * per-thread (fd,fp) cache.  With more descriptors, we batch.
1095  */
1096 static
1097 void
1098 floadkevfps(thread_t td, struct filedesc *fdp, struct kevent *kev,
1099 	    struct file **fp, int climit)
1100 {
1101 	struct filterops *fops;
1102 	int tdcache;
1103 
1104 	if (climit <= 2 && td->td_proc && td->td_proc->p_fd == fdp) {
1105 		tdcache = 1;
1106 	} else {
1107 		tdcache = 0;
1108 		spin_lock_shared(&fdp->fd_spin);
1109 	}
1110 
1111 	while (climit) {
1112 		*fp = NULL;
1113 		if (kev->filter < 0 &&
1114 		    kev->filter + EVFILT_SYSCOUNT >= 0) {
1115 			fops = sysfilt_ops[~kev->filter];
1116 			if (fops->f_flags & FILTEROP_ISFD) {
1117 				if (tdcache) {
1118 					*fp = holdfp(td, kev->ident, -1);
1119 				} else {
1120 					*fp = holdfp_fdp_locked(fdp,
1121 								kev->ident, -1);
1122 				}
1123 			}
1124 		}
1125 		--climit;
1126 		++fp;
1127 		++kev;
1128 	}
1129 	if (tdcache == 0)
1130 		spin_unlock_shared(&fdp->fd_spin);
1131 }
1132 
1133 /*
1134  * Register up to *countp kev's.  Always registers at least 1.
1135  *
1136  * The number registered is returned in *countp.
1137  *
1138  * If an error occurs or a kev is flagged EV_RECEIPT, it is
1139  * processed and included in *countp, and processing then
1140  * stops.
1141  */
1142 int
1143 kqueue_register(struct kqueue *kq, struct kevent *kev, int *countp)
1144 {
1145 	struct filedesc *fdp = kq->kq_fdp;
1146 	struct klist *list = NULL;
1147 	struct filterops *fops;
1148 	struct file *fp[KQ_NEVENTS];
1149 	struct knote *kn = NULL;
1150 	struct thread *td;
1151 	int error;
1152 	int count;
1153 	int climit;
1154 	int closedcounter;
1155 	struct knote_cache_list *cache_list;
1156 
1157 	td = curthread;
1158 	climit = *countp;
1159 	if (climit > KQ_NEVENTS)
1160 		climit = KQ_NEVENTS;
1161 	closedcounter = fdp->fd_closedcounter;
1162 	floadkevfps(td, fdp, kev, fp, climit);
1163 
1164 	lwkt_getpooltoken(kq);
1165 	count = 0;
1166 
1167 	/*
1168 	 * To avoid races, only one thread can register events on this
1169 	 * kqueue at a time.
1170 	 */
1171 	while (__predict_false(kq->kq_regtd != NULL && kq->kq_regtd != td)) {
1172 		kq->kq_state |= KQ_REGWAIT;
1173 		tsleep(&kq->kq_regtd, 0, "kqreg", 0);
1174 	}
1175 	if (__predict_false(kq->kq_regtd != NULL)) {
1176 		/* Recursive calling of kqueue_register() */
1177 		td = NULL;
1178 	} else {
1179 		/* Owner of the kq_regtd, i.e. td != NULL */
1180 		kq->kq_regtd = td;
1181 	}
1182 
1183 loop:
1184 	if (kev->filter < 0) {
1185 		if (kev->filter + EVFILT_SYSCOUNT < 0) {
1186 			error = EINVAL;
1187 			++count;
1188 			goto done;
1189 		}
1190 		fops = sysfilt_ops[~kev->filter];	/* to 0-base index */
1191 	} else {
1192 		/*
1193 		 * XXX
1194 		 * filter attach routine is responsible for insuring that
1195 		 * the identifier can be attached to it.
1196 		 */
1197 		error = EINVAL;
1198 		++count;
1199 		goto done;
1200 	}
1201 
1202 	if (fops->f_flags & FILTEROP_ISFD) {
1203 		/* validate descriptor */
1204 		if (fp[count] == NULL) {
1205 			error = EBADF;
1206 			++count;
1207 			goto done;
1208 		}
1209 	}
1210 
1211 	cache_list = &knote_cache_lists[mycpuid];
1212 	if (SLIST_EMPTY(&cache_list->knote_cache)) {
1213 		struct knote *new_kn;
1214 
1215 		new_kn = knote_alloc();
1216 		crit_enter();
1217 		SLIST_INSERT_HEAD(&cache_list->knote_cache, new_kn, kn_link);
1218 		cache_list->knote_cache_cnt++;
1219 		crit_exit();
1220 	}
1221 
1222 	if (fp[count] != NULL) {
1223 		list = &fp[count]->f_klist;
1224 	} else if (kq->kq_knhashmask) {
1225 		list = &kq->kq_knhash[
1226 			    KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1227 	}
1228 	if (list != NULL) {
1229 		lwkt_getpooltoken(list);
1230 again:
1231 		SLIST_FOREACH(kn, list, kn_link) {
1232 			if (kn->kn_kq == kq &&
1233 			    kn->kn_filter == kev->filter &&
1234 			    kn->kn_id == kev->ident) {
1235 				if (knote_acquire(kn) == 0)
1236 					goto again;
1237 				break;
1238 			}
1239 		}
1240 		lwkt_relpooltoken(list);
1241 	}
1242 
1243 	/*
1244 	 * NOTE: At this point if kn is non-NULL we will have acquired
1245 	 *	 it and set KN_PROCESSING.
1246 	 */
1247 	if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
1248 		error = ENOENT;
1249 		++count;
1250 		goto done;
1251 	}
1252 
1253 	/*
1254 	 * kn now contains the matching knote, or NULL if no match
1255 	 */
1256 	if (kev->flags & EV_ADD) {
1257 		if (kn == NULL) {
1258 			crit_enter();
1259 			kn = SLIST_FIRST(&cache_list->knote_cache);
1260 			if (kn == NULL) {
1261 				crit_exit();
1262 				kn = knote_alloc();
1263 			} else {
1264 				SLIST_REMOVE_HEAD(&cache_list->knote_cache,
1265 				    kn_link);
1266 				cache_list->knote_cache_cnt--;
1267 				crit_exit();
1268 			}
1269 			kn->kn_fp = fp[count];
1270 			kn->kn_kq = kq;
1271 			kn->kn_fop = fops;
1272 
1273 			/*
1274 			 * apply reference count to knote structure, and
1275 			 * do not release it at the end of this routine.
1276 			 */
1277 			fp[count] = NULL;	/* safety */
1278 
1279 			kn->kn_sfflags = kev->fflags;
1280 			kn->kn_sdata = kev->data;
1281 			kev->fflags = 0;
1282 			kev->data = 0;
1283 			kn->kn_kevent = *kev;
1284 
1285 			/*
1286 			 * KN_PROCESSING prevents the knote from getting
1287 			 * ripped out from under us while we are trying
1288 			 * to attach it, in case the attach blocks.
1289 			 */
1290 			kn->kn_status = KN_PROCESSING;
1291 			knote_attach(kn);
1292 			if ((error = filter_attach(kn)) != 0) {
1293 				kn->kn_status |= KN_DELETING | KN_REPROCESS;
1294 				knote_drop(kn);
1295 				++count;
1296 				goto done;
1297 			}
1298 
1299 			/*
1300 			 * Interlock against close races which either tried
1301 			 * to remove our knote while we were blocked or missed
1302 			 * it entirely prior to our attachment.  We do not
1303 			 * want to end up with a knote on a closed descriptor.
1304 			 */
1305 			if ((fops->f_flags & FILTEROP_ISFD) &&
1306 			    checkfdclosed(curthread, fdp, kev->ident, kn->kn_fp,
1307 					  closedcounter)) {
1308 				kn->kn_status |= KN_DELETING | KN_REPROCESS;
1309 			}
1310 		} else {
1311 			/*
1312 			 * The user may change some filter values after the
1313 			 * initial EV_ADD, but doing so will not reset any
1314 			 * filter which have already been triggered.
1315 			 */
1316 			KKASSERT(kn->kn_status & KN_PROCESSING);
1317 			if (fops == &user_filtops) {
1318 				filt_usertouch(kn, kev, EVENT_REGISTER);
1319 			} else {
1320 				kn->kn_sfflags = kev->fflags;
1321 				kn->kn_sdata = kev->data;
1322 				kn->kn_kevent.udata = kev->udata;
1323 			}
1324 		}
1325 
1326 		/*
1327 		 * Execute the filter event to immediately activate the
1328 		 * knote if necessary.  If reprocessing events are pending
1329 		 * due to blocking above we do not run the filter here
1330 		 * but instead let knote_release() do it.  Otherwise we
1331 		 * might run the filter on a deleted event.
1332 		 */
1333 		if ((kn->kn_status & KN_REPROCESS) == 0) {
1334 			if (filter_event(kn, 0))
1335 				KNOTE_ACTIVATE(kn);
1336 		}
1337 	} else if (kev->flags & EV_DELETE) {
1338 		/*
1339 		 * Delete the existing knote
1340 		 */
1341 		knote_detach_and_drop(kn);
1342 		error = 0;
1343 		++count;
1344 		goto done;
1345 	} else {
1346 		/*
1347 		 * Modify an existing event.
1348 		 *
1349 		 * The user may change some filter values after the
1350 		 * initial EV_ADD, but doing so will not reset any
1351 		 * filter which have already been triggered.
1352 		 */
1353 		KKASSERT(kn->kn_status & KN_PROCESSING);
1354 		if (fops == &user_filtops) {
1355 			filt_usertouch(kn, kev, EVENT_REGISTER);
1356 		} else {
1357 			kn->kn_sfflags = kev->fflags;
1358 			kn->kn_sdata = kev->data;
1359 			kn->kn_kevent.udata = kev->udata;
1360 		}
1361 
1362 		/*
1363 		 * Execute the filter event to immediately activate the
1364 		 * knote if necessary.  If reprocessing events are pending
1365 		 * due to blocking above we do not run the filter here
1366 		 * but instead let knote_release() do it.  Otherwise we
1367 		 * might run the filter on a deleted event.
1368 		 */
1369 		if ((kn->kn_status & KN_REPROCESS) == 0) {
1370 			if (filter_event(kn, 0))
1371 				KNOTE_ACTIVATE(kn);
1372 		}
1373 	}
1374 
1375 	/*
1376 	 * Disablement does not deactivate a knote here.
1377 	 */
1378 	if ((kev->flags & EV_DISABLE) &&
1379 	    ((kn->kn_status & KN_DISABLED) == 0)) {
1380 		kn->kn_status |= KN_DISABLED;
1381 	}
1382 
1383 	/*
1384 	 * Re-enablement may have to immediately enqueue an active knote.
1385 	 */
1386 	if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
1387 		kn->kn_status &= ~KN_DISABLED;
1388 		if ((kn->kn_status & KN_ACTIVE) &&
1389 		    ((kn->kn_status & KN_QUEUED) == 0)) {
1390 			knote_enqueue(kn);
1391 		}
1392 	}
1393 
1394 	/*
1395 	 * Handle any required reprocessing
1396 	 */
1397 	knote_release(kn);
1398 	/* kn may be invalid now */
1399 
1400 	/*
1401 	 * Loop control.  We stop on errors (above), and also stop after
1402 	 * processing EV_RECEIPT, so the caller can process it.
1403 	 */
1404 	++count;
1405 	if (kev->flags & EV_RECEIPT) {
1406 		error = 0;
1407 		goto done;
1408 	}
1409 	++kev;
1410 	if (count < climit) {
1411 		if (fp[count-1])		/* drop unprocessed fp */
1412 			fdrop(fp[count-1]);
1413 		goto loop;
1414 	}
1415 
1416 	/*
1417 	 * Cleanup
1418 	 */
1419 done:
1420 	if (td != NULL) { /* Owner of the kq_regtd */
1421 		kq->kq_regtd = NULL;
1422 		if (__predict_false(kq->kq_state & KQ_REGWAIT)) {
1423 			kq->kq_state &= ~KQ_REGWAIT;
1424 			wakeup(&kq->kq_regtd);
1425 		}
1426 	}
1427 	lwkt_relpooltoken(kq);
1428 
1429 	/*
1430 	 * Drop unprocessed file pointers
1431 	 */
1432 	*countp = count;
1433 	if (count && fp[count-1])
1434 		fdrop(fp[count-1]);
1435 	while (count < climit) {
1436 		if (fp[count])
1437 			fdrop(fp[count]);
1438 		++count;
1439 	}
1440 	return (error);
1441 }
1442 
1443 /*
1444  * Scan the kqueue, return the number of active events placed in kevp up
1445  * to count.
1446  *
1447  * Continuous mode events may get recycled, do not continue scanning past
1448  * marker unless no events have been collected.
1449  */
1450 static int
1451 kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
1452             struct knote *marker, int closedcounter, int scan_flags)
1453 {
1454 	struct knote *kn, local_marker;
1455 	thread_t td = curthread;
1456 	int total;
1457 
1458 	total = 0;
1459 	local_marker.kn_filter = EVFILT_MARKER;
1460 	local_marker.kn_status = KN_PROCESSING;
1461 
1462 	lwkt_getpooltoken(kq);
1463 
1464 	/*
1465 	 * Adjust marker, insert initial marker, or leave the marker alone.
1466 	 *
1467 	 * Also setup our local_marker.
1468 	 */
1469 	switch(scan_flags) {
1470 	case KEVENT_SCAN_RELOAD_MARKER:
1471 		TAILQ_REMOVE(&kq->kq_knpend, marker, kn_tqe);
1472 		/* fall through */
1473 	case KEVENT_SCAN_INSERT_MARKER:
1474 		TAILQ_INSERT_TAIL(&kq->kq_knpend, marker, kn_tqe);
1475 		break;
1476 	}
1477 	TAILQ_INSERT_HEAD(&kq->kq_knpend, &local_marker, kn_tqe);
1478 
1479 	/*
1480 	 * Collect events.
1481 	 */
1482 	while (count) {
1483 		kn = TAILQ_NEXT(&local_marker, kn_tqe);
1484 		if (kn->kn_filter == EVFILT_MARKER) {
1485 			/* Marker reached, we are done */
1486 			if (kn == marker)
1487 				break;
1488 
1489 			/* Move local marker past some other threads marker */
1490 			kn = TAILQ_NEXT(kn, kn_tqe);
1491 			TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
1492 			TAILQ_INSERT_BEFORE(kn, &local_marker, kn_tqe);
1493 			continue;
1494 		}
1495 
1496 		/*
1497 		 * We can't skip a knote undergoing processing, otherwise
1498 		 * we risk not returning it when the user process expects
1499 		 * it should be returned.  Sleep and retry.
1500 		 */
1501 		if (knote_acquire(kn) == 0)
1502 			continue;
1503 
1504 		/*
1505 		 * Remove the event for processing.
1506 		 *
1507 		 * WARNING!  We must leave KN_QUEUED set to prevent the
1508 		 *	     event from being KNOTE_ACTIVATE()d while
1509 		 *	     the queue state is in limbo, in case we
1510 		 *	     block.
1511 		 */
1512 		TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
1513 		kq->kq_count--;
1514 
1515 		/*
1516 		 * We have to deal with an extremely important race against
1517 		 * file descriptor close()s here.  The file descriptor can
1518 		 * disappear MPSAFE, and there is a small window of
1519 		 * opportunity between that and the call to knote_fdclose().
1520 		 *
1521 		 * If we hit that window here while doselect or dopoll is
1522 		 * trying to delete a spurious event they will not be able
1523 		 * to match up the event against a knote and will go haywire.
1524 		 */
1525 		if ((kn->kn_fop->f_flags & FILTEROP_ISFD) &&
1526 		    checkfdclosed(td, kq->kq_fdp, kn->kn_kevent.ident,
1527 				  kn->kn_fp, closedcounter)) {
1528 			kn->kn_status |= KN_DELETING | KN_REPROCESS;
1529 		}
1530 
1531 		if (kn->kn_status & KN_DISABLED) {
1532 			/*
1533 			 * If disabled we ensure the event is not queued
1534 			 * but leave its active bit set.  On re-enablement
1535 			 * the event may be immediately triggered.
1536 			 */
1537 			kn->kn_status &= ~KN_QUEUED;
1538 		} else if ((kn->kn_flags & EV_ONESHOT) == 0 &&
1539 			   (kn->kn_status & KN_DELETING) == 0 &&
1540 			   filter_event(kn, 0) == 0) {
1541 			/*
1542 			 * If not running in one-shot mode and the event
1543 			 * is no longer present we ensure it is removed
1544 			 * from the queue and ignore it.
1545 			 */
1546 			kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1547 		} else {
1548 			/*
1549 			 * Post the event
1550 			 */
1551 			if (kn->kn_fop == &user_filtops)
1552 				filt_usertouch(kn, kevp, EVENT_PROCESS);
1553 			else
1554 				*kevp = kn->kn_kevent;
1555 			++kevp;
1556 			++total;
1557 			--count;
1558 
1559 			if (kn->kn_flags & EV_ONESHOT) {
1560 				kn->kn_status &= ~KN_QUEUED;
1561 				kn->kn_status |= KN_DELETING | KN_REPROCESS;
1562 			} else {
1563 				if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1564 					if (kn->kn_flags & EV_CLEAR) {
1565 						kn->kn_data = 0;
1566 						kn->kn_fflags = 0;
1567 					}
1568 					if (kn->kn_flags & EV_DISPATCH) {
1569 						kn->kn_status |= KN_DISABLED;
1570 					}
1571 					kn->kn_status &= ~(KN_QUEUED |
1572 							   KN_ACTIVE);
1573 				} else {
1574 					TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1575 					kq->kq_count++;
1576 				}
1577 			}
1578 		}
1579 
1580 		/*
1581 		 * Handle any post-processing states
1582 		 */
1583 		knote_release(kn);
1584 	}
1585 	TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
1586 
1587 	lwkt_relpooltoken(kq);
1588 	return (total);
1589 }
1590 
1591 /*
1592  * XXX
1593  * This could be expanded to call kqueue_scan, if desired.
1594  *
1595  * MPSAFE
1596  */
1597 static int
1598 kqueue_read(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1599 {
1600 	return (ENXIO);
1601 }
1602 
1603 /*
1604  * MPSAFE
1605  */
1606 static int
1607 kqueue_write(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1608 {
1609 	return (ENXIO);
1610 }
1611 
1612 /*
1613  * MPALMOSTSAFE
1614  */
1615 static int
1616 kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
1617 	     struct ucred *cred, struct sysmsg *msg)
1618 {
1619 	struct kqueue *kq;
1620 	int error;
1621 
1622 	kq = (struct kqueue *)fp->f_data;
1623 	lwkt_getpooltoken(kq);
1624 	switch(com) {
1625 	case FIOASYNC:
1626 		if (*(int *)data)
1627 			kq->kq_state |= KQ_ASYNC;
1628 		else
1629 			kq->kq_state &= ~KQ_ASYNC;
1630 		error = 0;
1631 		break;
1632 	case FIOSETOWN:
1633 		error = fsetown(*(int *)data, &kq->kq_sigio);
1634 		break;
1635 	default:
1636 		error = ENOTTY;
1637 		break;
1638 	}
1639 	lwkt_relpooltoken(kq);
1640 	return (error);
1641 }
1642 
1643 /*
1644  * MPSAFE
1645  */
1646 static int
1647 kqueue_stat(struct file *fp, struct stat *st, struct ucred *cred)
1648 {
1649 	struct kqueue *kq = (struct kqueue *)fp->f_data;
1650 
1651 	bzero((void *)st, sizeof(*st));
1652 	st->st_size = kq->kq_count;
1653 	st->st_blksize = sizeof(struct kevent);
1654 	st->st_mode = S_IFIFO;
1655 	return (0);
1656 }
1657 
1658 /*
1659  * MPSAFE
1660  */
1661 static int
1662 kqueue_close(struct file *fp)
1663 {
1664 	struct kqueue *kq = (struct kqueue *)fp->f_data;
1665 
1666 	kqueue_terminate(kq);
1667 
1668 	fp->f_data = NULL;
1669 	funsetown(&kq->kq_sigio);
1670 
1671 	kfree(kq, M_KQUEUE);
1672 	return (0);
1673 }
1674 
1675 static void
1676 kqueue_wakeup(struct kqueue *kq)
1677 {
1678 	if (kq->kq_sleep_cnt) {
1679 		u_int sleep_cnt = kq->kq_sleep_cnt;
1680 
1681 		kq->kq_sleep_cnt = 0;
1682 		if (sleep_cnt == 1)
1683 			wakeup_one(kq);
1684 		else
1685 			wakeup(kq);
1686 	}
1687 	KNOTE(&kq->kq_kqinfo.ki_note, 0);
1688 }
1689 
1690 /*
1691  * Calls filterops f_attach function, acquiring mplock if filter is not
1692  * marked as FILTEROP_MPSAFE.
1693  *
1694  * Caller must be holding the related kq token
1695  */
1696 static int
1697 filter_attach(struct knote *kn)
1698 {
1699 	int ret;
1700 
1701 	if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1702 		ret = kn->kn_fop->f_attach(kn);
1703 	} else {
1704 		get_mplock();
1705 		ret = kn->kn_fop->f_attach(kn);
1706 		rel_mplock();
1707 	}
1708 	return (ret);
1709 }
1710 
1711 /*
1712  * Detach the knote and drop it, destroying the knote.
1713  *
1714  * Calls filterops f_detach function, acquiring mplock if filter is not
1715  * marked as FILTEROP_MPSAFE.
1716  *
1717  * Caller must be holding the related kq token
1718  */
1719 static void
1720 knote_detach_and_drop(struct knote *kn)
1721 {
1722 	kn->kn_status |= KN_DELETING | KN_REPROCESS;
1723 	if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1724 		kn->kn_fop->f_detach(kn);
1725 	} else {
1726 		get_mplock();
1727 		kn->kn_fop->f_detach(kn);
1728 		rel_mplock();
1729 	}
1730 	knote_drop(kn);
1731 }
1732 
1733 /*
1734  * Calls filterops f_event function, acquiring mplock if filter is not
1735  * marked as FILTEROP_MPSAFE.
1736  *
1737  * If the knote is in the middle of being created or deleted we cannot
1738  * safely call the filter op.
1739  *
1740  * Caller must be holding the related kq token
1741  */
1742 static int
1743 filter_event(struct knote *kn, long hint)
1744 {
1745 	int ret;
1746 
1747 	if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1748 		ret = kn->kn_fop->f_event(kn, hint);
1749 	} else {
1750 		get_mplock();
1751 		ret = kn->kn_fop->f_event(kn, hint);
1752 		rel_mplock();
1753 	}
1754 	return (ret);
1755 }
1756 
1757 /*
1758  * Walk down a list of knotes, activating them if their event has triggered.
1759  *
1760  * If we encounter any knotes which are undergoing processing we just mark
1761  * them for reprocessing and do not try to [re]activate the knote.  However,
1762  * if a hint is being passed we have to wait and that makes things a bit
1763  * sticky.
1764  */
1765 void
1766 knote(struct klist *list, long hint)
1767 {
1768 	struct kqueue *kq;
1769 	struct knote *kn;
1770 	struct knote *kntmp;
1771 
1772 	lwkt_getpooltoken(list);
1773 restart:
1774 	SLIST_FOREACH(kn, list, kn_next) {
1775 		kq = kn->kn_kq;
1776 		lwkt_getpooltoken(kq);
1777 
1778 		/* temporary verification hack */
1779 		SLIST_FOREACH(kntmp, list, kn_next) {
1780 			if (kn == kntmp)
1781 				break;
1782 		}
1783 		if (kn != kntmp || kn->kn_kq != kq) {
1784 			lwkt_relpooltoken(kq);
1785 			goto restart;
1786 		}
1787 
1788 		if (kn->kn_status & KN_PROCESSING) {
1789 			/*
1790 			 * Someone else is processing the knote, ask the
1791 			 * other thread to reprocess it and don't mess
1792 			 * with it otherwise.
1793 			 */
1794 			if (hint == 0) {
1795 				kn->kn_status |= KN_REPROCESS;
1796 				lwkt_relpooltoken(kq);
1797 				continue;
1798 			}
1799 
1800 			/*
1801 			 * If the hint is non-zero we have to wait or risk
1802 			 * losing the state the caller is trying to update.
1803 			 *
1804 			 * XXX This is a real problem, certain process
1805 			 *     and signal filters will bump kn_data for
1806 			 *     already-processed notes more than once if
1807 			 *     we restart the list scan.  FIXME.
1808 			 */
1809 			kn->kn_status |= KN_WAITING | KN_REPROCESS;
1810 			tsleep(kn, 0, "knotec", hz);
1811 			lwkt_relpooltoken(kq);
1812 			goto restart;
1813 		}
1814 
1815 		/*
1816 		 * Become the reprocessing master ourselves.
1817 		 *
1818 		 * If hint is non-zero running the event is mandatory
1819 		 * when not deleting so do it whether reprocessing is
1820 		 * set or not.
1821 		 */
1822 		kn->kn_status |= KN_PROCESSING;
1823 		if ((kn->kn_status & KN_DELETING) == 0) {
1824 			if (filter_event(kn, hint))
1825 				KNOTE_ACTIVATE(kn);
1826 		}
1827 		if (knote_release(kn)) {
1828 			lwkt_relpooltoken(kq);
1829 			goto restart;
1830 		}
1831 		lwkt_relpooltoken(kq);
1832 	}
1833 	lwkt_relpooltoken(list);
1834 }
1835 
1836 /*
1837  * Insert knote at head of klist.
1838  *
1839  * This function may only be called via a filter function and thus
1840  * kq_token should already be held and marked for processing.
1841  */
1842 void
1843 knote_insert(struct klist *klist, struct knote *kn)
1844 {
1845 	lwkt_getpooltoken(klist);
1846 	KKASSERT(kn->kn_status & KN_PROCESSING);
1847 	SLIST_INSERT_HEAD(klist, kn, kn_next);
1848 	lwkt_relpooltoken(klist);
1849 }
1850 
1851 /*
1852  * Remove knote from a klist
1853  *
1854  * This function may only be called via a filter function and thus
1855  * kq_token should already be held and marked for processing.
1856  */
1857 void
1858 knote_remove(struct klist *klist, struct knote *kn)
1859 {
1860 	lwkt_getpooltoken(klist);
1861 	KKASSERT(kn->kn_status & KN_PROCESSING);
1862 	SLIST_REMOVE(klist, kn, knote, kn_next);
1863 	lwkt_relpooltoken(klist);
1864 }
1865 
1866 void
1867 knote_assume_knotes(struct kqinfo *src, struct kqinfo *dst,
1868 		    struct filterops *ops, void *hook)
1869 {
1870 	struct kqueue *kq;
1871 	struct knote *kn;
1872 
1873 	lwkt_getpooltoken(&src->ki_note);
1874 	lwkt_getpooltoken(&dst->ki_note);
1875 	while ((kn = SLIST_FIRST(&src->ki_note)) != NULL) {
1876 		kq = kn->kn_kq;
1877 		lwkt_getpooltoken(kq);
1878 		if (SLIST_FIRST(&src->ki_note) != kn || kn->kn_kq != kq) {
1879 			lwkt_relpooltoken(kq);
1880 			continue;
1881 		}
1882 		if (knote_acquire(kn)) {
1883 			knote_remove(&src->ki_note, kn);
1884 			kn->kn_fop = ops;
1885 			kn->kn_hook = hook;
1886 			knote_insert(&dst->ki_note, kn);
1887 			knote_release(kn);
1888 			/* kn may be invalid now */
1889 		}
1890 		lwkt_relpooltoken(kq);
1891 	}
1892 	lwkt_relpooltoken(&dst->ki_note);
1893 	lwkt_relpooltoken(&src->ki_note);
1894 }
1895 
1896 /*
1897  * Remove all knotes referencing a specified fd
1898  */
1899 void
1900 knote_fdclose(struct file *fp, struct filedesc *fdp, int fd)
1901 {
1902 	struct kqueue *kq;
1903 	struct knote *kn;
1904 	struct knote *kntmp;
1905 
1906 	lwkt_getpooltoken(&fp->f_klist);
1907 restart:
1908 	SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
1909 		if (kn->kn_kq->kq_fdp == fdp && kn->kn_id == fd) {
1910 			kq = kn->kn_kq;
1911 			lwkt_getpooltoken(kq);
1912 
1913 			/* temporary verification hack */
1914 			SLIST_FOREACH(kntmp, &fp->f_klist, kn_link) {
1915 				if (kn == kntmp)
1916 					break;
1917 			}
1918 			if (kn != kntmp || kn->kn_kq->kq_fdp != fdp ||
1919 			    kn->kn_id != fd || kn->kn_kq != kq) {
1920 				lwkt_relpooltoken(kq);
1921 				goto restart;
1922 			}
1923 			if (knote_acquire(kn))
1924 				knote_detach_and_drop(kn);
1925 			lwkt_relpooltoken(kq);
1926 			goto restart;
1927 		}
1928 	}
1929 	lwkt_relpooltoken(&fp->f_klist);
1930 }
1931 
1932 /*
1933  * Low level attach function.
1934  *
1935  * The knote should already be marked for processing.
1936  * Caller must hold the related kq token.
1937  */
1938 static void
1939 knote_attach(struct knote *kn)
1940 {
1941 	struct klist *list;
1942 	struct kqueue *kq = kn->kn_kq;
1943 
1944 	if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1945 		KKASSERT(kn->kn_fp);
1946 		list = &kn->kn_fp->f_klist;
1947 	} else {
1948 		if (kq->kq_knhashmask == 0)
1949 			kq->kq_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1950 						 &kq->kq_knhashmask);
1951 		list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1952 	}
1953 	lwkt_getpooltoken(list);
1954 	SLIST_INSERT_HEAD(list, kn, kn_link);
1955 	lwkt_relpooltoken(list);
1956 	TAILQ_INSERT_HEAD(&kq->kq_knlist, kn, kn_kqlink);
1957 }
1958 
1959 /*
1960  * Low level drop function.
1961  *
1962  * The knote should already be marked for processing.
1963  * Caller must hold the related kq token.
1964  */
1965 static void
1966 knote_drop(struct knote *kn)
1967 {
1968 	struct kqueue *kq;
1969 	struct klist *list;
1970 
1971 	kq = kn->kn_kq;
1972 
1973 	if (kn->kn_fop->f_flags & FILTEROP_ISFD)
1974 		list = &kn->kn_fp->f_klist;
1975 	else
1976 		list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1977 
1978 	lwkt_getpooltoken(list);
1979 	SLIST_REMOVE(list, kn, knote, kn_link);
1980 	lwkt_relpooltoken(list);
1981 	TAILQ_REMOVE(&kq->kq_knlist, kn, kn_kqlink);
1982 	if (kn->kn_status & KN_QUEUED)
1983 		knote_dequeue(kn);
1984 	if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1985 		fdrop(kn->kn_fp);
1986 		kn->kn_fp = NULL;
1987 	}
1988 	knote_free(kn);
1989 }
1990 
1991 /*
1992  * Low level enqueue function.
1993  *
1994  * The knote should already be marked for processing.
1995  * Caller must be holding the kq token
1996  */
1997 static void
1998 knote_enqueue(struct knote *kn)
1999 {
2000 	struct kqueue *kq = kn->kn_kq;
2001 
2002 	KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2003 	TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
2004 	kn->kn_status |= KN_QUEUED;
2005 	++kq->kq_count;
2006 
2007 	/*
2008 	 * Send SIGIO on request (typically set up as a mailbox signal)
2009 	 */
2010 	if (kq->kq_sigio && (kq->kq_state & KQ_ASYNC) && kq->kq_count == 1)
2011 		pgsigio(kq->kq_sigio, SIGIO, 0);
2012 
2013 	kqueue_wakeup(kq);
2014 }
2015 
2016 /*
2017  * Low level dequeue function.
2018  *
2019  * The knote should already be marked for processing.
2020  * Caller must be holding the kq token
2021  */
2022 static void
2023 knote_dequeue(struct knote *kn)
2024 {
2025 	struct kqueue *kq = kn->kn_kq;
2026 
2027 	KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2028 	TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
2029 	kn->kn_status &= ~KN_QUEUED;
2030 	kq->kq_count--;
2031 }
2032 
2033 static struct knote *
2034 knote_alloc(void)
2035 {
2036 	return kmalloc(sizeof(struct knote), M_KQUEUE, M_WAITOK);
2037 }
2038 
2039 static void
2040 knote_free(struct knote *kn)
2041 {
2042 	struct knote_cache_list *cache_list;
2043 
2044 	cache_list = &knote_cache_lists[mycpuid];
2045 	if (cache_list->knote_cache_cnt < KNOTE_CACHE_MAX) {
2046 		crit_enter();
2047 		SLIST_INSERT_HEAD(&cache_list->knote_cache, kn, kn_link);
2048 		cache_list->knote_cache_cnt++;
2049 		crit_exit();
2050 		return;
2051 	}
2052 	kfree(kn, M_KQUEUE);
2053 }
2054 
2055 struct sleepinfo {
2056 	void *ident;
2057 	int timedout;
2058 };
2059 
2060 static void
2061 precise_sleep_intr(systimer_t info, int in_ipi, struct intrframe *frame)
2062 {
2063 	struct sleepinfo *si;
2064 
2065 	si = info->data;
2066 	si->timedout = 1;
2067 	wakeup(si->ident);
2068 }
2069 
2070 static int
2071 precise_sleep(void *ident, int flags, const char *wmesg, int us)
2072 {
2073 	struct systimer info;
2074 	struct sleepinfo si = {
2075 		.ident = ident,
2076 		.timedout = 0,
2077 	};
2078 	int r;
2079 
2080 	tsleep_interlock(ident, flags);
2081 	systimer_init_oneshot(&info, precise_sleep_intr, &si, us);
2082 	r = tsleep(ident, flags | PINTERLOCKED, wmesg, 0);
2083 	systimer_del(&info);
2084 	if (si.timedout)
2085 		r = EWOULDBLOCK;
2086 
2087 	return r;
2088 }
2089