xref: /dragonfly/sys/kern/kern_event.c (revision 7d3e9a5b)
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 (0);
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 	error = 0;
1167 
1168 	/*
1169 	 * To avoid races, only one thread can register events on this
1170 	 * kqueue at a time.
1171 	 */
1172 	while (__predict_false(kq->kq_regtd != NULL && kq->kq_regtd != td)) {
1173 		kq->kq_state |= KQ_REGWAIT;
1174 		tsleep(&kq->kq_regtd, 0, "kqreg", 0);
1175 	}
1176 	if (__predict_false(kq->kq_regtd != NULL)) {
1177 		/* Recursive calling of kqueue_register() */
1178 		td = NULL;
1179 	} else {
1180 		/* Owner of the kq_regtd, i.e. td != NULL */
1181 		kq->kq_regtd = td;
1182 	}
1183 
1184 loop:
1185 	if (kev->filter < 0) {
1186 		if (kev->filter + EVFILT_SYSCOUNT < 0) {
1187 			error = EINVAL;
1188 			++count;
1189 			goto done;
1190 		}
1191 		fops = sysfilt_ops[~kev->filter];	/* to 0-base index */
1192 	} else {
1193 		/*
1194 		 * XXX
1195 		 * filter attach routine is responsible for insuring that
1196 		 * the identifier can be attached to it.
1197 		 */
1198 		error = EINVAL;
1199 		++count;
1200 		goto done;
1201 	}
1202 
1203 	if (fops->f_flags & FILTEROP_ISFD) {
1204 		/* validate descriptor */
1205 		if (fp[count] == NULL) {
1206 			error = EBADF;
1207 			++count;
1208 			goto done;
1209 		}
1210 	}
1211 
1212 	cache_list = &knote_cache_lists[mycpuid];
1213 	if (SLIST_EMPTY(&cache_list->knote_cache)) {
1214 		struct knote *new_kn;
1215 
1216 		new_kn = knote_alloc();
1217 		crit_enter();
1218 		SLIST_INSERT_HEAD(&cache_list->knote_cache, new_kn, kn_link);
1219 		cache_list->knote_cache_cnt++;
1220 		crit_exit();
1221 	}
1222 
1223 	if (fp[count] != NULL) {
1224 		list = &fp[count]->f_klist;
1225 	} else if (kq->kq_knhashmask) {
1226 		list = &kq->kq_knhash[
1227 			    KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1228 	}
1229 	if (list != NULL) {
1230 		lwkt_getpooltoken(list);
1231 again:
1232 		SLIST_FOREACH(kn, list, kn_link) {
1233 			if (kn->kn_kq == kq &&
1234 			    kn->kn_filter == kev->filter &&
1235 			    kn->kn_id == kev->ident) {
1236 				if (knote_acquire(kn) == 0)
1237 					goto again;
1238 				break;
1239 			}
1240 		}
1241 		lwkt_relpooltoken(list);
1242 	}
1243 
1244 	/*
1245 	 * NOTE: At this point if kn is non-NULL we will have acquired
1246 	 *	 it and set KN_PROCESSING.
1247 	 */
1248 	if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
1249 		error = ENOENT;
1250 		++count;
1251 		goto done;
1252 	}
1253 
1254 	/*
1255 	 * kn now contains the matching knote, or NULL if no match
1256 	 */
1257 	if (kev->flags & EV_ADD) {
1258 		if (kn == NULL) {
1259 			crit_enter();
1260 			kn = SLIST_FIRST(&cache_list->knote_cache);
1261 			if (kn == NULL) {
1262 				crit_exit();
1263 				kn = knote_alloc();
1264 			} else {
1265 				SLIST_REMOVE_HEAD(&cache_list->knote_cache,
1266 				    kn_link);
1267 				cache_list->knote_cache_cnt--;
1268 				crit_exit();
1269 			}
1270 			kn->kn_fp = fp[count];
1271 			kn->kn_kq = kq;
1272 			kn->kn_fop = fops;
1273 
1274 			/*
1275 			 * apply reference count to knote structure, and
1276 			 * do not release it at the end of this routine.
1277 			 */
1278 			fp[count] = NULL;	/* safety */
1279 
1280 			kn->kn_sfflags = kev->fflags;
1281 			kn->kn_sdata = kev->data;
1282 			kev->fflags = 0;
1283 			kev->data = 0;
1284 			kn->kn_kevent = *kev;
1285 
1286 			/*
1287 			 * KN_PROCESSING prevents the knote from getting
1288 			 * ripped out from under us while we are trying
1289 			 * to attach it, in case the attach blocks.
1290 			 */
1291 			kn->kn_status = KN_PROCESSING;
1292 			knote_attach(kn);
1293 			if ((error = filter_attach(kn)) != 0) {
1294 				kn->kn_status |= KN_DELETING | KN_REPROCESS;
1295 				knote_drop(kn);
1296 				++count;
1297 				goto done;
1298 			}
1299 
1300 			/*
1301 			 * Interlock against close races which either tried
1302 			 * to remove our knote while we were blocked or missed
1303 			 * it entirely prior to our attachment.  We do not
1304 			 * want to end up with a knote on a closed descriptor.
1305 			 */
1306 			if ((fops->f_flags & FILTEROP_ISFD) &&
1307 			    checkfdclosed(curthread, fdp, kev->ident, kn->kn_fp,
1308 					  closedcounter)) {
1309 				kn->kn_status |= KN_DELETING | KN_REPROCESS;
1310 			}
1311 		} else {
1312 			/*
1313 			 * The user may change some filter values after the
1314 			 * initial EV_ADD, but doing so will not reset any
1315 			 * filter which have already been triggered.
1316 			 */
1317 			KKASSERT(kn->kn_status & KN_PROCESSING);
1318 			if (fops == &user_filtops) {
1319 				filt_usertouch(kn, kev, EVENT_REGISTER);
1320 			} else {
1321 				kn->kn_sfflags = kev->fflags;
1322 				kn->kn_sdata = kev->data;
1323 				kn->kn_kevent.udata = kev->udata;
1324 			}
1325 		}
1326 
1327 		/*
1328 		 * Execute the filter event to immediately activate the
1329 		 * knote if necessary.  If reprocessing events are pending
1330 		 * due to blocking above we do not run the filter here
1331 		 * but instead let knote_release() do it.  Otherwise we
1332 		 * might run the filter on a deleted event.
1333 		 */
1334 		if ((kn->kn_status & KN_REPROCESS) == 0) {
1335 			if (filter_event(kn, 0))
1336 				KNOTE_ACTIVATE(kn);
1337 		}
1338 	} else if (kev->flags & EV_DELETE) {
1339 		/*
1340 		 * Delete the existing knote
1341 		 */
1342 		knote_detach_and_drop(kn);
1343 		error = 0;
1344 		++count;
1345 		goto done;
1346 	} else {
1347 		/*
1348 		 * Modify an existing event.
1349 		 *
1350 		 * The user may change some filter values after the
1351 		 * initial EV_ADD, but doing so will not reset any
1352 		 * filter which have already been triggered.
1353 		 */
1354 		KKASSERT(kn->kn_status & KN_PROCESSING);
1355 		if (fops == &user_filtops) {
1356 			filt_usertouch(kn, kev, EVENT_REGISTER);
1357 		} else {
1358 			kn->kn_sfflags = kev->fflags;
1359 			kn->kn_sdata = kev->data;
1360 			kn->kn_kevent.udata = kev->udata;
1361 		}
1362 
1363 		/*
1364 		 * Execute the filter event to immediately activate the
1365 		 * knote if necessary.  If reprocessing events are pending
1366 		 * due to blocking above we do not run the filter here
1367 		 * but instead let knote_release() do it.  Otherwise we
1368 		 * might run the filter on a deleted event.
1369 		 */
1370 		if ((kn->kn_status & KN_REPROCESS) == 0) {
1371 			if (filter_event(kn, 0))
1372 				KNOTE_ACTIVATE(kn);
1373 		}
1374 	}
1375 
1376 	/*
1377 	 * Disablement does not deactivate a knote here.
1378 	 */
1379 	if ((kev->flags & EV_DISABLE) &&
1380 	    ((kn->kn_status & KN_DISABLED) == 0)) {
1381 		kn->kn_status |= KN_DISABLED;
1382 	}
1383 
1384 	/*
1385 	 * Re-enablement may have to immediately enqueue an active knote.
1386 	 */
1387 	if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
1388 		kn->kn_status &= ~KN_DISABLED;
1389 		if ((kn->kn_status & KN_ACTIVE) &&
1390 		    ((kn->kn_status & KN_QUEUED) == 0)) {
1391 			knote_enqueue(kn);
1392 		}
1393 	}
1394 
1395 	/*
1396 	 * Handle any required reprocessing
1397 	 */
1398 	knote_release(kn);
1399 	/* kn may be invalid now */
1400 
1401 	/*
1402 	 * Loop control.  We stop on errors (above), and also stop after
1403 	 * processing EV_RECEIPT, so the caller can process it.
1404 	 */
1405 	++count;
1406 	if (kev->flags & EV_RECEIPT) {
1407 		error = 0;
1408 		goto done;
1409 	}
1410 	++kev;
1411 	if (count < climit) {
1412 		if (fp[count-1])		/* drop unprocessed fp */
1413 			fdrop(fp[count-1]);
1414 		goto loop;
1415 	}
1416 
1417 	/*
1418 	 * Cleanup
1419 	 */
1420 done:
1421 	if (td != NULL) { /* Owner of the kq_regtd */
1422 		kq->kq_regtd = NULL;
1423 		if (__predict_false(kq->kq_state & KQ_REGWAIT)) {
1424 			kq->kq_state &= ~KQ_REGWAIT;
1425 			wakeup(&kq->kq_regtd);
1426 		}
1427 	}
1428 	lwkt_relpooltoken(kq);
1429 
1430 	/*
1431 	 * Drop unprocessed file pointers
1432 	 */
1433 	*countp = count;
1434 	if (count && fp[count-1])
1435 		fdrop(fp[count-1]);
1436 	while (count < climit) {
1437 		if (fp[count])
1438 			fdrop(fp[count]);
1439 		++count;
1440 	}
1441 	return (error);
1442 }
1443 
1444 /*
1445  * Scan the kqueue, return the number of active events placed in kevp up
1446  * to count.
1447  *
1448  * Continuous mode events may get recycled, do not continue scanning past
1449  * marker unless no events have been collected.
1450  */
1451 static int
1452 kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
1453             struct knote *marker, int closedcounter, int scan_flags)
1454 {
1455 	struct knote *kn, local_marker;
1456 	thread_t td = curthread;
1457 	int total;
1458 
1459 	total = 0;
1460 	local_marker.kn_filter = EVFILT_MARKER;
1461 	local_marker.kn_status = KN_PROCESSING;
1462 
1463 	lwkt_getpooltoken(kq);
1464 
1465 	/*
1466 	 * Adjust marker, insert initial marker, or leave the marker alone.
1467 	 *
1468 	 * Also setup our local_marker.
1469 	 */
1470 	switch(scan_flags) {
1471 	case KEVENT_SCAN_RELOAD_MARKER:
1472 		TAILQ_REMOVE(&kq->kq_knpend, marker, kn_tqe);
1473 		/* fall through */
1474 	case KEVENT_SCAN_INSERT_MARKER:
1475 		TAILQ_INSERT_TAIL(&kq->kq_knpend, marker, kn_tqe);
1476 		break;
1477 	}
1478 	TAILQ_INSERT_HEAD(&kq->kq_knpend, &local_marker, kn_tqe);
1479 
1480 	/*
1481 	 * Collect events.
1482 	 */
1483 	while (count) {
1484 		kn = TAILQ_NEXT(&local_marker, kn_tqe);
1485 		if (kn->kn_filter == EVFILT_MARKER) {
1486 			/* Marker reached, we are done */
1487 			if (kn == marker)
1488 				break;
1489 
1490 			/* Move local marker past some other threads marker */
1491 			kn = TAILQ_NEXT(kn, kn_tqe);
1492 			TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
1493 			TAILQ_INSERT_BEFORE(kn, &local_marker, kn_tqe);
1494 			continue;
1495 		}
1496 
1497 		/*
1498 		 * We can't skip a knote undergoing processing, otherwise
1499 		 * we risk not returning it when the user process expects
1500 		 * it should be returned.  Sleep and retry.
1501 		 */
1502 		if (knote_acquire(kn) == 0)
1503 			continue;
1504 
1505 		/*
1506 		 * Remove the event for processing.
1507 		 *
1508 		 * WARNING!  We must leave KN_QUEUED set to prevent the
1509 		 *	     event from being KNOTE_ACTIVATE()d while
1510 		 *	     the queue state is in limbo, in case we
1511 		 *	     block.
1512 		 */
1513 		TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
1514 		kq->kq_count--;
1515 
1516 		/*
1517 		 * We have to deal with an extremely important race against
1518 		 * file descriptor close()s here.  The file descriptor can
1519 		 * disappear MPSAFE, and there is a small window of
1520 		 * opportunity between that and the call to knote_fdclose().
1521 		 *
1522 		 * If we hit that window here while doselect or dopoll is
1523 		 * trying to delete a spurious event they will not be able
1524 		 * to match up the event against a knote and will go haywire.
1525 		 */
1526 		if ((kn->kn_fop->f_flags & FILTEROP_ISFD) &&
1527 		    checkfdclosed(td, kq->kq_fdp, kn->kn_kevent.ident,
1528 				  kn->kn_fp, closedcounter)) {
1529 			kn->kn_status |= KN_DELETING | KN_REPROCESS;
1530 		}
1531 
1532 		if (kn->kn_status & KN_DISABLED) {
1533 			/*
1534 			 * If disabled we ensure the event is not queued
1535 			 * but leave its active bit set.  On re-enablement
1536 			 * the event may be immediately triggered.
1537 			 */
1538 			kn->kn_status &= ~KN_QUEUED;
1539 		} else if ((kn->kn_flags & EV_ONESHOT) == 0 &&
1540 			   (kn->kn_status & KN_DELETING) == 0 &&
1541 			   filter_event(kn, 0) == 0) {
1542 			/*
1543 			 * If not running in one-shot mode and the event
1544 			 * is no longer present we ensure it is removed
1545 			 * from the queue and ignore it.
1546 			 */
1547 			kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1548 		} else {
1549 			/*
1550 			 * Post the event
1551 			 */
1552 			if (kn->kn_fop == &user_filtops)
1553 				filt_usertouch(kn, kevp, EVENT_PROCESS);
1554 			else
1555 				*kevp = kn->kn_kevent;
1556 			++kevp;
1557 			++total;
1558 			--count;
1559 
1560 			if (kn->kn_flags & EV_ONESHOT) {
1561 				kn->kn_status &= ~KN_QUEUED;
1562 				kn->kn_status |= KN_DELETING | KN_REPROCESS;
1563 			} else {
1564 				if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1565 					if (kn->kn_flags & EV_CLEAR) {
1566 						kn->kn_data = 0;
1567 						kn->kn_fflags = 0;
1568 					}
1569 					if (kn->kn_flags & EV_DISPATCH) {
1570 						kn->kn_status |= KN_DISABLED;
1571 					}
1572 					kn->kn_status &= ~(KN_QUEUED |
1573 							   KN_ACTIVE);
1574 				} else {
1575 					TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1576 					kq->kq_count++;
1577 				}
1578 			}
1579 		}
1580 
1581 		/*
1582 		 * Handle any post-processing states
1583 		 */
1584 		knote_release(kn);
1585 	}
1586 	TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
1587 
1588 	lwkt_relpooltoken(kq);
1589 	return (total);
1590 }
1591 
1592 /*
1593  * XXX
1594  * This could be expanded to call kqueue_scan, if desired.
1595  *
1596  * MPSAFE
1597  */
1598 static int
1599 kqueue_read(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1600 {
1601 	return (ENXIO);
1602 }
1603 
1604 /*
1605  * MPSAFE
1606  */
1607 static int
1608 kqueue_write(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1609 {
1610 	return (ENXIO);
1611 }
1612 
1613 /*
1614  * MPALMOSTSAFE
1615  */
1616 static int
1617 kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
1618 	     struct ucred *cred, struct sysmsg *msg)
1619 {
1620 	struct kqueue *kq;
1621 	int error;
1622 
1623 	kq = (struct kqueue *)fp->f_data;
1624 	lwkt_getpooltoken(kq);
1625 	switch(com) {
1626 	case FIOASYNC:
1627 		if (*(int *)data)
1628 			kq->kq_state |= KQ_ASYNC;
1629 		else
1630 			kq->kq_state &= ~KQ_ASYNC;
1631 		error = 0;
1632 		break;
1633 	case FIOSETOWN:
1634 		error = fsetown(*(int *)data, &kq->kq_sigio);
1635 		break;
1636 	default:
1637 		error = ENOTTY;
1638 		break;
1639 	}
1640 	lwkt_relpooltoken(kq);
1641 	return (error);
1642 }
1643 
1644 /*
1645  * MPSAFE
1646  */
1647 static int
1648 kqueue_stat(struct file *fp, struct stat *st, struct ucred *cred)
1649 {
1650 	struct kqueue *kq = (struct kqueue *)fp->f_data;
1651 
1652 	bzero((void *)st, sizeof(*st));
1653 	st->st_size = kq->kq_count;
1654 	st->st_blksize = sizeof(struct kevent);
1655 	st->st_mode = S_IFIFO;
1656 	return (0);
1657 }
1658 
1659 /*
1660  * MPSAFE
1661  */
1662 static int
1663 kqueue_close(struct file *fp)
1664 {
1665 	struct kqueue *kq = (struct kqueue *)fp->f_data;
1666 
1667 	kqueue_terminate(kq);
1668 
1669 	fp->f_data = NULL;
1670 	funsetown(&kq->kq_sigio);
1671 
1672 	kfree(kq, M_KQUEUE);
1673 	return (0);
1674 }
1675 
1676 static void
1677 kqueue_wakeup(struct kqueue *kq)
1678 {
1679 	if (kq->kq_sleep_cnt) {
1680 		u_int sleep_cnt = kq->kq_sleep_cnt;
1681 
1682 		kq->kq_sleep_cnt = 0;
1683 		if (sleep_cnt == 1)
1684 			wakeup_one(kq);
1685 		else
1686 			wakeup(kq);
1687 	}
1688 	KNOTE(&kq->kq_kqinfo.ki_note, 0);
1689 }
1690 
1691 /*
1692  * Calls filterops f_attach function, acquiring mplock if filter is not
1693  * marked as FILTEROP_MPSAFE.
1694  *
1695  * Caller must be holding the related kq token
1696  */
1697 static int
1698 filter_attach(struct knote *kn)
1699 {
1700 	int ret;
1701 
1702 	if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1703 		ret = kn->kn_fop->f_attach(kn);
1704 	} else {
1705 		get_mplock();
1706 		ret = kn->kn_fop->f_attach(kn);
1707 		rel_mplock();
1708 	}
1709 	return (ret);
1710 }
1711 
1712 /*
1713  * Detach the knote and drop it, destroying the knote.
1714  *
1715  * Calls filterops f_detach function, acquiring mplock if filter is not
1716  * marked as FILTEROP_MPSAFE.
1717  *
1718  * Caller must be holding the related kq token
1719  */
1720 static void
1721 knote_detach_and_drop(struct knote *kn)
1722 {
1723 	kn->kn_status |= KN_DELETING | KN_REPROCESS;
1724 	if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1725 		kn->kn_fop->f_detach(kn);
1726 	} else {
1727 		get_mplock();
1728 		kn->kn_fop->f_detach(kn);
1729 		rel_mplock();
1730 	}
1731 	knote_drop(kn);
1732 }
1733 
1734 /*
1735  * Calls filterops f_event function, acquiring mplock if filter is not
1736  * marked as FILTEROP_MPSAFE.
1737  *
1738  * If the knote is in the middle of being created or deleted we cannot
1739  * safely call the filter op.
1740  *
1741  * Caller must be holding the related kq token
1742  */
1743 static int
1744 filter_event(struct knote *kn, long hint)
1745 {
1746 	int ret;
1747 
1748 	if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1749 		ret = kn->kn_fop->f_event(kn, hint);
1750 	} else {
1751 		get_mplock();
1752 		ret = kn->kn_fop->f_event(kn, hint);
1753 		rel_mplock();
1754 	}
1755 	return (ret);
1756 }
1757 
1758 /*
1759  * Walk down a list of knotes, activating them if their event has triggered.
1760  *
1761  * If we encounter any knotes which are undergoing processing we just mark
1762  * them for reprocessing and do not try to [re]activate the knote.  However,
1763  * if a hint is being passed we have to wait and that makes things a bit
1764  * sticky.
1765  */
1766 void
1767 knote(struct klist *list, long hint)
1768 {
1769 	struct kqueue *kq;
1770 	struct knote *kn;
1771 	struct knote *kntmp;
1772 
1773 	lwkt_getpooltoken(list);
1774 restart:
1775 	SLIST_FOREACH(kn, list, kn_next) {
1776 		kq = kn->kn_kq;
1777 		lwkt_getpooltoken(kq);
1778 
1779 		/* temporary verification hack */
1780 		SLIST_FOREACH(kntmp, list, kn_next) {
1781 			if (kn == kntmp)
1782 				break;
1783 		}
1784 		if (kn != kntmp || kn->kn_kq != kq) {
1785 			lwkt_relpooltoken(kq);
1786 			goto restart;
1787 		}
1788 
1789 		if (kn->kn_status & KN_PROCESSING) {
1790 			/*
1791 			 * Someone else is processing the knote, ask the
1792 			 * other thread to reprocess it and don't mess
1793 			 * with it otherwise.
1794 			 */
1795 			if (hint == 0) {
1796 				kn->kn_status |= KN_REPROCESS;
1797 				lwkt_relpooltoken(kq);
1798 				continue;
1799 			}
1800 
1801 			/*
1802 			 * If the hint is non-zero we have to wait or risk
1803 			 * losing the state the caller is trying to update.
1804 			 *
1805 			 * XXX This is a real problem, certain process
1806 			 *     and signal filters will bump kn_data for
1807 			 *     already-processed notes more than once if
1808 			 *     we restart the list scan.  FIXME.
1809 			 */
1810 			kn->kn_status |= KN_WAITING | KN_REPROCESS;
1811 			tsleep(kn, 0, "knotec", hz);
1812 			lwkt_relpooltoken(kq);
1813 			goto restart;
1814 		}
1815 
1816 		/*
1817 		 * Become the reprocessing master ourselves.
1818 		 *
1819 		 * If hint is non-zero running the event is mandatory
1820 		 * when not deleting so do it whether reprocessing is
1821 		 * set or not.
1822 		 */
1823 		kn->kn_status |= KN_PROCESSING;
1824 		if ((kn->kn_status & KN_DELETING) == 0) {
1825 			if (filter_event(kn, hint))
1826 				KNOTE_ACTIVATE(kn);
1827 		}
1828 		if (knote_release(kn)) {
1829 			lwkt_relpooltoken(kq);
1830 			goto restart;
1831 		}
1832 		lwkt_relpooltoken(kq);
1833 	}
1834 	lwkt_relpooltoken(list);
1835 }
1836 
1837 /*
1838  * Insert knote at head of klist.
1839  *
1840  * This function may only be called via a filter function and thus
1841  * kq_token should already be held and marked for processing.
1842  */
1843 void
1844 knote_insert(struct klist *klist, struct knote *kn)
1845 {
1846 	lwkt_getpooltoken(klist);
1847 	KKASSERT(kn->kn_status & KN_PROCESSING);
1848 	SLIST_INSERT_HEAD(klist, kn, kn_next);
1849 	lwkt_relpooltoken(klist);
1850 }
1851 
1852 /*
1853  * Remove knote from a klist
1854  *
1855  * This function may only be called via a filter function and thus
1856  * kq_token should already be held and marked for processing.
1857  */
1858 void
1859 knote_remove(struct klist *klist, struct knote *kn)
1860 {
1861 	lwkt_getpooltoken(klist);
1862 	KKASSERT(kn->kn_status & KN_PROCESSING);
1863 	SLIST_REMOVE(klist, kn, knote, kn_next);
1864 	lwkt_relpooltoken(klist);
1865 }
1866 
1867 void
1868 knote_assume_knotes(struct kqinfo *src, struct kqinfo *dst,
1869 		    struct filterops *ops, void *hook)
1870 {
1871 	struct kqueue *kq;
1872 	struct knote *kn;
1873 
1874 	lwkt_getpooltoken(&src->ki_note);
1875 	lwkt_getpooltoken(&dst->ki_note);
1876 	while ((kn = SLIST_FIRST(&src->ki_note)) != NULL) {
1877 		kq = kn->kn_kq;
1878 		lwkt_getpooltoken(kq);
1879 		if (SLIST_FIRST(&src->ki_note) != kn || kn->kn_kq != kq) {
1880 			lwkt_relpooltoken(kq);
1881 			continue;
1882 		}
1883 		if (knote_acquire(kn)) {
1884 			knote_remove(&src->ki_note, kn);
1885 			kn->kn_fop = ops;
1886 			kn->kn_hook = hook;
1887 			knote_insert(&dst->ki_note, kn);
1888 			knote_release(kn);
1889 			/* kn may be invalid now */
1890 		}
1891 		lwkt_relpooltoken(kq);
1892 	}
1893 	lwkt_relpooltoken(&dst->ki_note);
1894 	lwkt_relpooltoken(&src->ki_note);
1895 }
1896 
1897 /*
1898  * Remove all knotes referencing a specified fd
1899  */
1900 void
1901 knote_fdclose(struct file *fp, struct filedesc *fdp, int fd)
1902 {
1903 	struct kqueue *kq;
1904 	struct knote *kn;
1905 	struct knote *kntmp;
1906 
1907 	lwkt_getpooltoken(&fp->f_klist);
1908 restart:
1909 	SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
1910 		if (kn->kn_kq->kq_fdp == fdp && kn->kn_id == fd) {
1911 			kq = kn->kn_kq;
1912 			lwkt_getpooltoken(kq);
1913 
1914 			/* temporary verification hack */
1915 			SLIST_FOREACH(kntmp, &fp->f_klist, kn_link) {
1916 				if (kn == kntmp)
1917 					break;
1918 			}
1919 			if (kn != kntmp || kn->kn_kq->kq_fdp != fdp ||
1920 			    kn->kn_id != fd || kn->kn_kq != kq) {
1921 				lwkt_relpooltoken(kq);
1922 				goto restart;
1923 			}
1924 			if (knote_acquire(kn))
1925 				knote_detach_and_drop(kn);
1926 			lwkt_relpooltoken(kq);
1927 			goto restart;
1928 		}
1929 	}
1930 	lwkt_relpooltoken(&fp->f_klist);
1931 }
1932 
1933 /*
1934  * Low level attach function.
1935  *
1936  * The knote should already be marked for processing.
1937  * Caller must hold the related kq token.
1938  */
1939 static void
1940 knote_attach(struct knote *kn)
1941 {
1942 	struct klist *list;
1943 	struct kqueue *kq = kn->kn_kq;
1944 
1945 	if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1946 		KKASSERT(kn->kn_fp);
1947 		list = &kn->kn_fp->f_klist;
1948 	} else {
1949 		if (kq->kq_knhashmask == 0)
1950 			kq->kq_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1951 						 &kq->kq_knhashmask);
1952 		list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1953 	}
1954 	lwkt_getpooltoken(list);
1955 	SLIST_INSERT_HEAD(list, kn, kn_link);
1956 	lwkt_relpooltoken(list);
1957 	TAILQ_INSERT_HEAD(&kq->kq_knlist, kn, kn_kqlink);
1958 }
1959 
1960 /*
1961  * Low level drop function.
1962  *
1963  * The knote should already be marked for processing.
1964  * Caller must hold the related kq token.
1965  */
1966 static void
1967 knote_drop(struct knote *kn)
1968 {
1969 	struct kqueue *kq;
1970 	struct klist *list;
1971 
1972 	kq = kn->kn_kq;
1973 
1974 	if (kn->kn_fop->f_flags & FILTEROP_ISFD)
1975 		list = &kn->kn_fp->f_klist;
1976 	else
1977 		list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1978 
1979 	lwkt_getpooltoken(list);
1980 	SLIST_REMOVE(list, kn, knote, kn_link);
1981 	lwkt_relpooltoken(list);
1982 	TAILQ_REMOVE(&kq->kq_knlist, kn, kn_kqlink);
1983 	if (kn->kn_status & KN_QUEUED)
1984 		knote_dequeue(kn);
1985 	if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1986 		fdrop(kn->kn_fp);
1987 		kn->kn_fp = NULL;
1988 	}
1989 	knote_free(kn);
1990 }
1991 
1992 /*
1993  * Low level enqueue function.
1994  *
1995  * The knote should already be marked for processing.
1996  * Caller must be holding the kq token
1997  */
1998 static void
1999 knote_enqueue(struct knote *kn)
2000 {
2001 	struct kqueue *kq = kn->kn_kq;
2002 
2003 	KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2004 	TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
2005 	kn->kn_status |= KN_QUEUED;
2006 	++kq->kq_count;
2007 
2008 	/*
2009 	 * Send SIGIO on request (typically set up as a mailbox signal)
2010 	 */
2011 	if (kq->kq_sigio && (kq->kq_state & KQ_ASYNC) && kq->kq_count == 1)
2012 		pgsigio(kq->kq_sigio, SIGIO, 0);
2013 
2014 	kqueue_wakeup(kq);
2015 }
2016 
2017 /*
2018  * Low level dequeue function.
2019  *
2020  * The knote should already be marked for processing.
2021  * Caller must be holding the kq token
2022  */
2023 static void
2024 knote_dequeue(struct knote *kn)
2025 {
2026 	struct kqueue *kq = kn->kn_kq;
2027 
2028 	KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2029 	TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
2030 	kn->kn_status &= ~KN_QUEUED;
2031 	kq->kq_count--;
2032 }
2033 
2034 static struct knote *
2035 knote_alloc(void)
2036 {
2037 	return kmalloc(sizeof(struct knote), M_KQUEUE, M_WAITOK);
2038 }
2039 
2040 static void
2041 knote_free(struct knote *kn)
2042 {
2043 	struct knote_cache_list *cache_list;
2044 
2045 	cache_list = &knote_cache_lists[mycpuid];
2046 	if (cache_list->knote_cache_cnt < KNOTE_CACHE_MAX) {
2047 		crit_enter();
2048 		SLIST_INSERT_HEAD(&cache_list->knote_cache, kn, kn_link);
2049 		cache_list->knote_cache_cnt++;
2050 		crit_exit();
2051 		return;
2052 	}
2053 	kfree(kn, M_KQUEUE);
2054 }
2055 
2056 struct sleepinfo {
2057 	void *ident;
2058 	int timedout;
2059 };
2060 
2061 static void
2062 precise_sleep_intr(systimer_t info, int in_ipi, struct intrframe *frame)
2063 {
2064 	struct sleepinfo *si;
2065 
2066 	si = info->data;
2067 	si->timedout = 1;
2068 	wakeup(si->ident);
2069 }
2070 
2071 static int
2072 precise_sleep(void *ident, int flags, const char *wmesg, int us)
2073 {
2074 	struct systimer info;
2075 	struct sleepinfo si = {
2076 		.ident = ident,
2077 		.timedout = 0,
2078 	};
2079 	int r;
2080 
2081 	tsleep_interlock(ident, flags);
2082 	systimer_init_oneshot(&info, precise_sleep_intr, &si, us);
2083 	r = tsleep(ident, flags | PINTERLOCKED, wmesg, 0);
2084 	systimer_del(&info);
2085 	if (si.timedout)
2086 		r = EWOULDBLOCK;
2087 
2088 	return r;
2089 }
2090