xref: /dflybsd-src/sys/kern/kern_event.c (revision e90a7c45c3303ed54c0fde732b2ba32dc80ffd9b)
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  * $DragonFly: src/sys/kern/kern_event.c,v 1.33 2007/02/03 17:05:57 corecode Exp $
28  */
29 
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/kernel.h>
33 #include <sys/proc.h>
34 #include <sys/malloc.h>
35 #include <sys/unistd.h>
36 #include <sys/file.h>
37 #include <sys/lock.h>
38 #include <sys/fcntl.h>
39 #include <sys/queue.h>
40 #include <sys/event.h>
41 #include <sys/eventvar.h>
42 #include <sys/protosw.h>
43 #include <sys/socket.h>
44 #include <sys/socketvar.h>
45 #include <sys/stat.h>
46 #include <sys/sysctl.h>
47 #include <sys/sysproto.h>
48 #include <sys/thread.h>
49 #include <sys/uio.h>
50 #include <sys/signalvar.h>
51 #include <sys/filio.h>
52 #include <sys/ktr.h>
53 
54 #include <sys/thread2.h>
55 #include <sys/file2.h>
56 #include <sys/mplock2.h>
57 
58 /*
59  * Global token for kqueue subsystem
60  */
61 struct lwkt_token kq_token = LWKT_TOKEN_INITIALIZER(kq_token);
62 SYSCTL_LONG(_lwkt, OID_AUTO, kq_collisions,
63     CTLFLAG_RW, &kq_token.t_collisions, 0,
64     "Collision counter of kq_token");
65 
66 MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
67 
68 struct kevent_copyin_args {
69 	struct kevent_args	*ka;
70 	int			pchanges;
71 };
72 
73 static int	kqueue_sleep(struct kqueue *kq, struct timespec *tsp);
74 static int	kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
75 		    struct knote *marker);
76 static int 	kqueue_read(struct file *fp, struct uio *uio,
77 		    struct ucred *cred, int flags);
78 static int	kqueue_write(struct file *fp, struct uio *uio,
79 		    struct ucred *cred, int flags);
80 static int	kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
81 		    struct ucred *cred, struct sysmsg *msg);
82 static int 	kqueue_kqfilter(struct file *fp, struct knote *kn);
83 static int 	kqueue_stat(struct file *fp, struct stat *st,
84 		    struct ucred *cred);
85 static int 	kqueue_close(struct file *fp);
86 static void	kqueue_wakeup(struct kqueue *kq);
87 static int	filter_attach(struct knote *kn);
88 static int	filter_event(struct knote *kn, long hint);
89 
90 /*
91  * MPSAFE
92  */
93 static struct fileops kqueueops = {
94 	.fo_read = kqueue_read,
95 	.fo_write = kqueue_write,
96 	.fo_ioctl = kqueue_ioctl,
97 	.fo_kqfilter = kqueue_kqfilter,
98 	.fo_stat = kqueue_stat,
99 	.fo_close = kqueue_close,
100 	.fo_shutdown = nofo_shutdown
101 };
102 
103 static void 	knote_attach(struct knote *kn);
104 static void 	knote_drop(struct knote *kn);
105 static void	knote_detach_and_drop(struct knote *kn);
106 static void 	knote_enqueue(struct knote *kn);
107 static void 	knote_dequeue(struct knote *kn);
108 static struct 	knote *knote_alloc(void);
109 static void 	knote_free(struct knote *kn);
110 
111 static void	filt_kqdetach(struct knote *kn);
112 static int	filt_kqueue(struct knote *kn, long hint);
113 static int	filt_procattach(struct knote *kn);
114 static void	filt_procdetach(struct knote *kn);
115 static int	filt_proc(struct knote *kn, long hint);
116 static int	filt_fileattach(struct knote *kn);
117 static void	filt_timerexpire(void *knx);
118 static int	filt_timerattach(struct knote *kn);
119 static void	filt_timerdetach(struct knote *kn);
120 static int	filt_timer(struct knote *kn, long hint);
121 
122 static struct filterops file_filtops =
123 	{ FILTEROP_ISFD, filt_fileattach, NULL, NULL };
124 static struct filterops kqread_filtops =
125 	{ FILTEROP_ISFD, NULL, filt_kqdetach, filt_kqueue };
126 static struct filterops proc_filtops =
127 	{ 0, filt_procattach, filt_procdetach, filt_proc };
128 static struct filterops timer_filtops =
129 	{ 0, filt_timerattach, filt_timerdetach, filt_timer };
130 
131 static int 		kq_ncallouts = 0;
132 static int 		kq_calloutmax = (4 * 1024);
133 SYSCTL_INT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
134     &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
135 static int		kq_checkloop = 1000000;
136 SYSCTL_INT(_kern, OID_AUTO, kq_checkloop, CTLFLAG_RW,
137     &kq_checkloop, 0, "Maximum number of callouts allocated for kqueue");
138 
139 #define KNOTE_ACTIVATE(kn) do { 					\
140 	kn->kn_status |= KN_ACTIVE;					\
141 	if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0)		\
142 		knote_enqueue(kn);					\
143 } while(0)
144 
145 #define	KN_HASHSIZE		64		/* XXX should be tunable */
146 #define KN_HASH(val, mask)	(((val) ^ (val >> 8)) & (mask))
147 
148 extern struct filterops aio_filtops;
149 extern struct filterops sig_filtops;
150 
151 /*
152  * Table for for all system-defined filters.
153  */
154 static struct filterops *sysfilt_ops[] = {
155 	&file_filtops,			/* EVFILT_READ */
156 	&file_filtops,			/* EVFILT_WRITE */
157 	&aio_filtops,			/* EVFILT_AIO */
158 	&file_filtops,			/* EVFILT_VNODE */
159 	&proc_filtops,			/* EVFILT_PROC */
160 	&sig_filtops,			/* EVFILT_SIGNAL */
161 	&timer_filtops,			/* EVFILT_TIMER */
162 	&file_filtops,			/* EVFILT_EXCEPT */
163 };
164 
165 static int
166 filt_fileattach(struct knote *kn)
167 {
168 	return (fo_kqfilter(kn->kn_fp, kn));
169 }
170 
171 /*
172  * MPSAFE
173  */
174 static int
175 kqueue_kqfilter(struct file *fp, struct knote *kn)
176 {
177 	struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
178 
179 	if (kn->kn_filter != EVFILT_READ)
180 		return (EOPNOTSUPP);
181 
182 	kn->kn_fop = &kqread_filtops;
183 	knote_insert(&kq->kq_kqinfo.ki_note, kn);
184 	return (0);
185 }
186 
187 static void
188 filt_kqdetach(struct knote *kn)
189 {
190 	struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
191 
192 	knote_remove(&kq->kq_kqinfo.ki_note, kn);
193 }
194 
195 /*ARGSUSED*/
196 static int
197 filt_kqueue(struct knote *kn, long hint)
198 {
199 	struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
200 
201 	kn->kn_data = kq->kq_count;
202 	return (kn->kn_data > 0);
203 }
204 
205 static int
206 filt_procattach(struct knote *kn)
207 {
208 	struct proc *p;
209 	int immediate;
210 
211 	immediate = 0;
212 	lwkt_gettoken(&proc_token);
213 	p = pfind(kn->kn_id);
214 	if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
215 		p = zpfind(kn->kn_id);
216 		immediate = 1;
217 	}
218 	if (p == NULL) {
219 		lwkt_reltoken(&proc_token);
220 		return (ESRCH);
221 	}
222 	if (!PRISON_CHECK(curthread->td_ucred, p->p_ucred)) {
223 		lwkt_reltoken(&proc_token);
224 		return (EACCES);
225 	}
226 
227 	kn->kn_ptr.p_proc = p;
228 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
229 
230 	/*
231 	 * internal flag indicating registration done by kernel
232 	 */
233 	if (kn->kn_flags & EV_FLAG1) {
234 		kn->kn_data = kn->kn_sdata;		/* ppid */
235 		kn->kn_fflags = NOTE_CHILD;
236 		kn->kn_flags &= ~EV_FLAG1;
237 	}
238 
239 	knote_insert(&p->p_klist, kn);
240 
241 	/*
242 	 * Immediately activate any exit notes if the target process is a
243 	 * zombie.  This is necessary to handle the case where the target
244 	 * process, e.g. a child, dies before the kevent is negistered.
245 	 */
246 	if (immediate && filt_proc(kn, NOTE_EXIT))
247 		KNOTE_ACTIVATE(kn);
248 	lwkt_reltoken(&proc_token);
249 
250 	return (0);
251 }
252 
253 /*
254  * The knote may be attached to a different process, which may exit,
255  * leaving nothing for the knote to be attached to.  So when the process
256  * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
257  * it will be deleted when read out.  However, as part of the knote deletion,
258  * this routine is called, so a check is needed to avoid actually performing
259  * a detach, because the original process does not exist any more.
260  */
261 static void
262 filt_procdetach(struct knote *kn)
263 {
264 	struct proc *p;
265 
266 	if (kn->kn_status & KN_DETACHED)
267 		return;
268 	/* XXX locking? take proc_token here? */
269 	p = kn->kn_ptr.p_proc;
270 	knote_remove(&p->p_klist, kn);
271 }
272 
273 static int
274 filt_proc(struct knote *kn, long hint)
275 {
276 	u_int event;
277 
278 	/*
279 	 * mask off extra data
280 	 */
281 	event = (u_int)hint & NOTE_PCTRLMASK;
282 
283 	/*
284 	 * if the user is interested in this event, record it.
285 	 */
286 	if (kn->kn_sfflags & event)
287 		kn->kn_fflags |= event;
288 
289 	/*
290 	 * Process is gone, so flag the event as finished.  Detach the
291 	 * knote from the process now because the process will be poof,
292 	 * gone later on.
293 	 */
294 	if (event == NOTE_EXIT) {
295 		struct proc *p = kn->kn_ptr.p_proc;
296 		if ((kn->kn_status & KN_DETACHED) == 0) {
297 			knote_remove(&p->p_klist, kn);
298 			kn->kn_status |= KN_DETACHED;
299 			kn->kn_data = p->p_xstat;
300 			kn->kn_ptr.p_proc = NULL;
301 		}
302 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
303 		return (1);
304 	}
305 
306 	/*
307 	 * process forked, and user wants to track the new process,
308 	 * so attach a new knote to it, and immediately report an
309 	 * event with the parent's pid.
310 	 */
311 	if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
312 		struct kevent kev;
313 		int error;
314 
315 		/*
316 		 * register knote with new process.
317 		 */
318 		kev.ident = hint & NOTE_PDATAMASK;	/* pid */
319 		kev.filter = kn->kn_filter;
320 		kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
321 		kev.fflags = kn->kn_sfflags;
322 		kev.data = kn->kn_id;			/* parent */
323 		kev.udata = kn->kn_kevent.udata;	/* preserve udata */
324 		error = kqueue_register(kn->kn_kq, &kev);
325 		if (error)
326 			kn->kn_fflags |= NOTE_TRACKERR;
327 	}
328 
329 	return (kn->kn_fflags != 0);
330 }
331 
332 /*
333  * The callout interlocks with callout_stop() (or should), so the
334  * knote should still be a valid structure.  However the timeout
335  * can race a deletion so if KN_DELETING is set we just don't touch
336  * the knote.
337  */
338 static void
339 filt_timerexpire(void *knx)
340 {
341 	struct knote *kn = knx;
342 	struct callout *calloutp;
343 	struct timeval tv;
344 	int tticks;
345 
346 	lwkt_gettoken(&kq_token);
347 	if ((kn->kn_status & KN_DELETING) == 0) {
348 		kn->kn_data++;
349 		KNOTE_ACTIVATE(kn);
350 
351 		if ((kn->kn_flags & EV_ONESHOT) == 0) {
352 			tv.tv_sec = kn->kn_sdata / 1000;
353 			tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
354 			tticks = tvtohz_high(&tv);
355 			calloutp = (struct callout *)kn->kn_hook;
356 			callout_reset(calloutp, tticks, filt_timerexpire, kn);
357 		}
358 	}
359 	lwkt_reltoken(&kq_token);
360 }
361 
362 /*
363  * data contains amount of time to sleep, in milliseconds
364  */
365 static int
366 filt_timerattach(struct knote *kn)
367 {
368 	struct callout *calloutp;
369 	struct timeval tv;
370 	int tticks;
371 
372 	if (kq_ncallouts >= kq_calloutmax)
373 		return (ENOMEM);
374 	kq_ncallouts++;
375 
376 	tv.tv_sec = kn->kn_sdata / 1000;
377 	tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
378 	tticks = tvtohz_high(&tv);
379 
380 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
381 	MALLOC(calloutp, struct callout *, sizeof(*calloutp),
382 	    M_KQUEUE, M_WAITOK);
383 	callout_init(calloutp);
384 	kn->kn_hook = (caddr_t)calloutp;
385 	callout_reset(calloutp, tticks, filt_timerexpire, kn);
386 
387 	return (0);
388 }
389 
390 static void
391 filt_timerdetach(struct knote *kn)
392 {
393 	struct callout *calloutp;
394 
395 	calloutp = (struct callout *)kn->kn_hook;
396 	callout_stop(calloutp);
397 	FREE(calloutp, M_KQUEUE);
398 	kq_ncallouts--;
399 }
400 
401 static int
402 filt_timer(struct knote *kn, long hint)
403 {
404 
405 	return (kn->kn_data != 0);
406 }
407 
408 /*
409  * Acquire a knote, return non-zero on success, 0 on failure.
410  *
411  * If we cannot acquire the knote we sleep and return 0.  The knote
412  * may be stale on return in this case and the caller must restart
413  * whatever loop they are in.
414  */
415 static __inline
416 int
417 knote_acquire(struct knote *kn)
418 {
419 	if (kn->kn_status & KN_PROCESSING) {
420 		kn->kn_status |= KN_WAITING | KN_REPROCESS;
421 		tsleep(kn, 0, "kqepts", hz);
422 		/* knote may be stale now */
423 		return(0);
424 	}
425 	kn->kn_status |= KN_PROCESSING;
426 	return(1);
427 }
428 
429 /*
430  * Release an acquired knote, clearing KN_PROCESSING and handling any
431  * KN_REPROCESS events.
432  *
433  * Non-zero is returned if the knote is destroyed.
434  */
435 static __inline
436 int
437 knote_release(struct knote *kn)
438 {
439 	while (kn->kn_status & KN_REPROCESS) {
440 		kn->kn_status &= ~KN_REPROCESS;
441 		if (kn->kn_status & KN_WAITING) {
442 			kn->kn_status &= ~KN_WAITING;
443 			wakeup(kn);
444 		}
445 		if (kn->kn_status & KN_DELETING) {
446 			knote_detach_and_drop(kn);
447 			return(1);
448 			/* NOT REACHED */
449 		}
450 		if (filter_event(kn, 0))
451 			KNOTE_ACTIVATE(kn);
452 	}
453 	kn->kn_status &= ~KN_PROCESSING;
454 	return(0);
455 }
456 
457 /*
458  * Initialize a kqueue.
459  *
460  * NOTE: The lwp/proc code initializes a kqueue for select/poll ops.
461  *
462  * MPSAFE
463  */
464 void
465 kqueue_init(struct kqueue *kq, struct filedesc *fdp)
466 {
467 	TAILQ_INIT(&kq->kq_knpend);
468 	TAILQ_INIT(&kq->kq_knlist);
469 	kq->kq_count = 0;
470 	kq->kq_fdp = fdp;
471 	SLIST_INIT(&kq->kq_kqinfo.ki_note);
472 }
473 
474 /*
475  * Terminate a kqueue.  Freeing the actual kq itself is left up to the
476  * caller (it might be embedded in a lwp so we don't do it here).
477  *
478  * The kq's knlist must be completely eradicated so block on any
479  * processing races.
480  */
481 void
482 kqueue_terminate(struct kqueue *kq)
483 {
484 	struct knote *kn;
485 
486 	lwkt_gettoken(&kq_token);
487 	while ((kn = TAILQ_FIRST(&kq->kq_knlist)) != NULL) {
488 		if (knote_acquire(kn))
489 			knote_detach_and_drop(kn);
490 	}
491 	if (kq->kq_knhash) {
492 		kfree(kq->kq_knhash, M_KQUEUE);
493 		kq->kq_knhash = NULL;
494 		kq->kq_knhashmask = 0;
495 	}
496 	lwkt_reltoken(&kq_token);
497 }
498 
499 /*
500  * MPSAFE
501  */
502 int
503 sys_kqueue(struct kqueue_args *uap)
504 {
505 	struct thread *td = curthread;
506 	struct kqueue *kq;
507 	struct file *fp;
508 	int fd, error;
509 
510 	error = falloc(td->td_lwp, &fp, &fd);
511 	if (error)
512 		return (error);
513 	fp->f_flag = FREAD | FWRITE;
514 	fp->f_type = DTYPE_KQUEUE;
515 	fp->f_ops = &kqueueops;
516 
517 	kq = kmalloc(sizeof(struct kqueue), M_KQUEUE, M_WAITOK | M_ZERO);
518 	kqueue_init(kq, td->td_proc->p_fd);
519 	fp->f_data = kq;
520 
521 	fsetfd(kq->kq_fdp, fp, fd);
522 	uap->sysmsg_result = fd;
523 	fdrop(fp);
524 	return (error);
525 }
526 
527 /*
528  * Copy 'count' items into the destination list pointed to by uap->eventlist.
529  */
530 static int
531 kevent_copyout(void *arg, struct kevent *kevp, int count, int *res)
532 {
533 	struct kevent_copyin_args *kap;
534 	int error;
535 
536 	kap = (struct kevent_copyin_args *)arg;
537 
538 	error = copyout(kevp, kap->ka->eventlist, count * sizeof(*kevp));
539 	if (error == 0) {
540 		kap->ka->eventlist += count;
541 		*res += count;
542 	} else {
543 		*res = -1;
544 	}
545 
546 	return (error);
547 }
548 
549 /*
550  * Copy at most 'max' items from the list pointed to by kap->changelist,
551  * return number of items in 'events'.
552  */
553 static int
554 kevent_copyin(void *arg, struct kevent *kevp, int max, int *events)
555 {
556 	struct kevent_copyin_args *kap;
557 	int error, count;
558 
559 	kap = (struct kevent_copyin_args *)arg;
560 
561 	count = min(kap->ka->nchanges - kap->pchanges, max);
562 	error = copyin(kap->ka->changelist, kevp, count * sizeof *kevp);
563 	if (error == 0) {
564 		kap->ka->changelist += count;
565 		kap->pchanges += count;
566 		*events = count;
567 	}
568 
569 	return (error);
570 }
571 
572 /*
573  * MPSAFE
574  */
575 int
576 kern_kevent(struct kqueue *kq, int nevents, int *res, void *uap,
577 	    k_copyin_fn kevent_copyinfn, k_copyout_fn kevent_copyoutfn,
578 	    struct timespec *tsp_in)
579 {
580 	struct kevent *kevp;
581 	struct timespec *tsp;
582 	int i, n, total, error, nerrors = 0;
583 	int lres;
584 	int limit = kq_checkloop;
585 	struct kevent kev[KQ_NEVENTS];
586 	struct knote marker;
587 
588 	tsp = tsp_in;
589 	*res = 0;
590 
591 	lwkt_gettoken(&kq_token);
592 	for ( ;; ) {
593 		n = 0;
594 		error = kevent_copyinfn(uap, kev, KQ_NEVENTS, &n);
595 		if (error)
596 			goto done;
597 		if (n == 0)
598 			break;
599 		for (i = 0; i < n; i++) {
600 			kevp = &kev[i];
601 			kevp->flags &= ~EV_SYSFLAGS;
602 			error = kqueue_register(kq, kevp);
603 
604 			/*
605 			 * If a registration returns an error we
606 			 * immediately post the error.  The kevent()
607 			 * call itself will fail with the error if
608 			 * no space is available for posting.
609 			 *
610 			 * Such errors normally bypass the timeout/blocking
611 			 * code.  However, if the copyoutfn function refuses
612 			 * to post the error (see sys_poll()), then we
613 			 * ignore it too.
614 			 */
615 			if (error) {
616 				kevp->flags = EV_ERROR;
617 				kevp->data = error;
618 				lres = *res;
619 				kevent_copyoutfn(uap, kevp, 1, res);
620 				if (lres != *res) {
621 					nevents--;
622 					nerrors++;
623 				}
624 			}
625 		}
626 	}
627 	if (nerrors) {
628 		error = 0;
629 		goto done;
630 	}
631 
632 	/*
633 	 * Acquire/wait for events - setup timeout
634 	 */
635 	if (tsp != NULL) {
636 		struct timespec ats;
637 
638 		if (tsp->tv_sec || tsp->tv_nsec) {
639 			nanouptime(&ats);
640 			timespecadd(tsp, &ats);		/* tsp = target time */
641 		}
642 	}
643 
644 	/*
645 	 * Loop as required.
646 	 *
647 	 * Collect as many events as we can. Sleeping on successive
648 	 * loops is disabled if copyoutfn has incremented (*res).
649 	 *
650 	 * The loop stops if an error occurs, all events have been
651 	 * scanned (the marker has been reached), or fewer than the
652 	 * maximum number of events is found.
653 	 *
654 	 * The copyoutfn function does not have to increment (*res) in
655 	 * order for the loop to continue.
656 	 *
657 	 * NOTE: doselect() usually passes 0x7FFFFFFF for nevents.
658 	 */
659 	total = 0;
660 	error = 0;
661 	marker.kn_filter = EVFILT_MARKER;
662 	marker.kn_status = KN_PROCESSING;
663 	TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
664 	while ((n = nevents - total) > 0) {
665 		if (n > KQ_NEVENTS)
666 			n = KQ_NEVENTS;
667 
668 		/*
669 		 * If no events are pending sleep until timeout (if any)
670 		 * or an event occurs.
671 		 *
672 		 * After the sleep completes the marker is moved to the
673 		 * end of the list, making any received events available
674 		 * to our scan.
675 		 */
676 		if (kq->kq_count == 0 && *res == 0) {
677 			error = kqueue_sleep(kq, tsp);
678 			if (error)
679 				break;
680 
681 			TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
682 			TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
683 		}
684 
685 		/*
686 		 * Process all received events
687 		 * Account for all non-spurious events in our total
688 		 */
689 		i = kqueue_scan(kq, kev, n, &marker);
690 		if (i) {
691 			lres = *res;
692 			error = kevent_copyoutfn(uap, kev, i, res);
693 			total += *res - lres;
694 			if (error)
695 				break;
696 		}
697 		if (limit && --limit == 0)
698 			panic("kqueue: checkloop failed i=%d", i);
699 
700 		/*
701 		 * Normally when fewer events are returned than requested
702 		 * we can stop.  However, if only spurious events were
703 		 * collected the copyout will not bump (*res) and we have
704 		 * to continue.
705 		 */
706 		if (i < n && *res)
707 			break;
708 
709 		/*
710 		 * Deal with an edge case where spurious events can cause
711 		 * a loop to occur without moving the marker.  This can
712 		 * prevent kqueue_scan() from picking up new events which
713 		 * race us.  We must be sure to move the marker for this
714 		 * case.
715 		 *
716 		 * NOTE: We do not want to move the marker if events
717 		 *	 were scanned because normal kqueue operations
718 		 *	 may reactivate events.  Moving the marker in
719 		 *	 that case could result in duplicates for the
720 		 *	 same event.
721 		 */
722 		if (i == 0) {
723 			TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
724 			TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
725 		}
726 	}
727 	TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
728 
729 	/* Timeouts do not return EWOULDBLOCK. */
730 	if (error == EWOULDBLOCK)
731 		error = 0;
732 
733 done:
734 	lwkt_reltoken(&kq_token);
735 	return (error);
736 }
737 
738 /*
739  * MPALMOSTSAFE
740  */
741 int
742 sys_kevent(struct kevent_args *uap)
743 {
744 	struct thread *td = curthread;
745 	struct proc *p = td->td_proc;
746 	struct timespec ts, *tsp;
747 	struct kqueue *kq;
748 	struct file *fp = NULL;
749 	struct kevent_copyin_args *kap, ka;
750 	int error;
751 
752 	if (uap->timeout) {
753 		error = copyin(uap->timeout, &ts, sizeof(ts));
754 		if (error)
755 			return (error);
756 		tsp = &ts;
757 	} else {
758 		tsp = NULL;
759 	}
760 
761 	fp = holdfp(p->p_fd, uap->fd, -1);
762 	if (fp == NULL)
763 		return (EBADF);
764 	if (fp->f_type != DTYPE_KQUEUE) {
765 		fdrop(fp);
766 		return (EBADF);
767 	}
768 
769 	kq = (struct kqueue *)fp->f_data;
770 
771 	kap = &ka;
772 	kap->ka = uap;
773 	kap->pchanges = 0;
774 
775 	error = kern_kevent(kq, uap->nevents, &uap->sysmsg_result, kap,
776 			    kevent_copyin, kevent_copyout, tsp);
777 
778 	fdrop(fp);
779 
780 	return (error);
781 }
782 
783 int
784 kqueue_register(struct kqueue *kq, struct kevent *kev)
785 {
786 	struct filedesc *fdp = kq->kq_fdp;
787 	struct filterops *fops;
788 	struct file *fp = NULL;
789 	struct knote *kn = NULL;
790 	int error = 0;
791 
792 	if (kev->filter < 0) {
793 		if (kev->filter + EVFILT_SYSCOUNT < 0)
794 			return (EINVAL);
795 		fops = sysfilt_ops[~kev->filter];	/* to 0-base index */
796 	} else {
797 		/*
798 		 * XXX
799 		 * filter attach routine is responsible for insuring that
800 		 * the identifier can be attached to it.
801 		 */
802 		kprintf("unknown filter: %d\n", kev->filter);
803 		return (EINVAL);
804 	}
805 
806 	lwkt_gettoken(&kq_token);
807 	if (fops->f_flags & FILTEROP_ISFD) {
808 		/* validate descriptor */
809 		fp = holdfp(fdp, kev->ident, -1);
810 		if (fp == NULL) {
811 			lwkt_reltoken(&kq_token);
812 			return (EBADF);
813 		}
814 
815 again1:
816 		SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
817 			if (kn->kn_kq == kq &&
818 			    kn->kn_filter == kev->filter &&
819 			    kn->kn_id == kev->ident) {
820 				if (knote_acquire(kn) == 0)
821 					goto again1;
822 				break;
823 			}
824 		}
825 	} else {
826 		if (kq->kq_knhashmask) {
827 			struct klist *list;
828 
829 			list = &kq->kq_knhash[
830 			    KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
831 again2:
832 			SLIST_FOREACH(kn, list, kn_link) {
833 				if (kn->kn_id == kev->ident &&
834 				    kn->kn_filter == kev->filter) {
835 					if (knote_acquire(kn) == 0)
836 						goto again2;
837 					break;
838 				}
839 			}
840 		}
841 	}
842 
843 	/*
844 	 * NOTE: At this point if kn is non-NULL we will have acquired
845 	 *	 it and set KN_PROCESSING.
846 	 */
847 	if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
848 		error = ENOENT;
849 		goto done;
850 	}
851 
852 	/*
853 	 * kn now contains the matching knote, or NULL if no match
854 	 */
855 	if (kev->flags & EV_ADD) {
856 		if (kn == NULL) {
857 			kn = knote_alloc();
858 			if (kn == NULL) {
859 				error = ENOMEM;
860 				goto done;
861 			}
862 			kn->kn_fp = fp;
863 			kn->kn_kq = kq;
864 			kn->kn_fop = fops;
865 
866 			/*
867 			 * apply reference count to knote structure, and
868 			 * do not release it at the end of this routine.
869 			 */
870 			fp = NULL;
871 
872 			kn->kn_sfflags = kev->fflags;
873 			kn->kn_sdata = kev->data;
874 			kev->fflags = 0;
875 			kev->data = 0;
876 			kn->kn_kevent = *kev;
877 
878 			/*
879 			 * KN_PROCESSING prevents the knote from getting
880 			 * ripped out from under us while we are trying
881 			 * to attach it, in case the attach blocks.
882 			 */
883 			kn->kn_status = KN_PROCESSING;
884 			knote_attach(kn);
885 			if ((error = filter_attach(kn)) != 0) {
886 				kn->kn_status |= KN_DELETING | KN_REPROCESS;
887 				knote_drop(kn);
888 				goto done;
889 			}
890 
891 			/*
892 			 * Interlock against close races which either tried
893 			 * to remove our knote while we were blocked or missed
894 			 * it entirely prior to our attachment.  We do not
895 			 * want to end up with a knote on a closed descriptor.
896 			 */
897 			if ((fops->f_flags & FILTEROP_ISFD) &&
898 			    checkfdclosed(fdp, kev->ident, kn->kn_fp)) {
899 				kn->kn_status |= KN_DELETING | KN_REPROCESS;
900 			}
901 		} else {
902 			/*
903 			 * The user may change some filter values after the
904 			 * initial EV_ADD, but doing so will not reset any
905 			 * filter which have already been triggered.
906 			 */
907 			KKASSERT(kn->kn_status & KN_PROCESSING);
908 			kn->kn_sfflags = kev->fflags;
909 			kn->kn_sdata = kev->data;
910 			kn->kn_kevent.udata = kev->udata;
911 		}
912 
913 		/*
914 		 * Execute the filter event to immediately activate the
915 		 * knote if necessary.  If reprocessing events are pending
916 		 * due to blocking above we do not run the filter here
917 		 * but instead let knote_release() do it.  Otherwise we
918 		 * might run the filter on a deleted event.
919 		 */
920 		if ((kn->kn_status & KN_REPROCESS) == 0) {
921 			if (filter_event(kn, 0))
922 				KNOTE_ACTIVATE(kn);
923 		}
924 	} else if (kev->flags & EV_DELETE) {
925 		/*
926 		 * Delete the existing knote
927 		 */
928 		knote_detach_and_drop(kn);
929 		goto done;
930 	}
931 
932 	/*
933 	 * Disablement does not deactivate a knote here.
934 	 */
935 	if ((kev->flags & EV_DISABLE) &&
936 	    ((kn->kn_status & KN_DISABLED) == 0)) {
937 		kn->kn_status |= KN_DISABLED;
938 	}
939 
940 	/*
941 	 * Re-enablement may have to immediately enqueue an active knote.
942 	 */
943 	if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
944 		kn->kn_status &= ~KN_DISABLED;
945 		if ((kn->kn_status & KN_ACTIVE) &&
946 		    ((kn->kn_status & KN_QUEUED) == 0)) {
947 			knote_enqueue(kn);
948 		}
949 	}
950 
951 	/*
952 	 * Handle any required reprocessing
953 	 */
954 	knote_release(kn);
955 	/* kn may be invalid now */
956 
957 done:
958 	lwkt_reltoken(&kq_token);
959 	if (fp != NULL)
960 		fdrop(fp);
961 	return (error);
962 }
963 
964 /*
965  * Block as necessary until the target time is reached.
966  * If tsp is NULL we block indefinitely.  If tsp->ts_secs/nsecs are both
967  * 0 we do not block at all.
968  */
969 static int
970 kqueue_sleep(struct kqueue *kq, struct timespec *tsp)
971 {
972 	int error = 0;
973 
974 	if (tsp == NULL) {
975 		kq->kq_state |= KQ_SLEEP;
976 		error = tsleep(kq, PCATCH, "kqread", 0);
977 	} else if (tsp->tv_sec == 0 && tsp->tv_nsec == 0) {
978 		error = EWOULDBLOCK;
979 	} else {
980 		struct timespec ats;
981 		struct timespec atx = *tsp;
982 		int timeout;
983 
984 		nanouptime(&ats);
985 		timespecsub(&atx, &ats);
986 		if (ats.tv_sec < 0) {
987 			error = EWOULDBLOCK;
988 		} else {
989 			timeout = atx.tv_sec > 24 * 60 * 60 ?
990 				24 * 60 * 60 * hz : tstohz_high(&atx);
991 			kq->kq_state |= KQ_SLEEP;
992 			error = tsleep(kq, PCATCH, "kqread", timeout);
993 		}
994 	}
995 
996 	/* don't restart after signals... */
997 	if (error == ERESTART)
998 		return (EINTR);
999 
1000 	return (error);
1001 }
1002 
1003 /*
1004  * Scan the kqueue, return the number of active events placed in kevp up
1005  * to count.
1006  *
1007  * Continuous mode events may get recycled, do not continue scanning past
1008  * marker unless no events have been collected.
1009  */
1010 static int
1011 kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
1012             struct knote *marker)
1013 {
1014         struct knote *kn, local_marker;
1015         int total;
1016 
1017         total = 0;
1018 	local_marker.kn_filter = EVFILT_MARKER;
1019 	local_marker.kn_status = KN_PROCESSING;
1020 
1021 	/*
1022 	 * Collect events.
1023 	 */
1024 	TAILQ_INSERT_HEAD(&kq->kq_knpend, &local_marker, kn_tqe);
1025 	while (count) {
1026 		kn = TAILQ_NEXT(&local_marker, kn_tqe);
1027 		if (kn->kn_filter == EVFILT_MARKER) {
1028 			/* Marker reached, we are done */
1029 			if (kn == marker)
1030 				break;
1031 
1032 			/* Move local marker past some other threads marker */
1033 			kn = TAILQ_NEXT(kn, kn_tqe);
1034 			TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
1035 			TAILQ_INSERT_BEFORE(kn, &local_marker, kn_tqe);
1036 			continue;
1037 		}
1038 
1039 		/*
1040 		 * We can't skip a knote undergoing processing, otherwise
1041 		 * we risk not returning it when the user process expects
1042 		 * it should be returned.  Sleep and retry.
1043 		 */
1044 		if (knote_acquire(kn) == 0)
1045 			continue;
1046 
1047 		/*
1048 		 * Remove the event for processing.
1049 		 *
1050 		 * WARNING!  We must leave KN_QUEUED set to prevent the
1051 		 *	     event from being KNOTE_ACTIVATE()d while
1052 		 *	     the queue state is in limbo, in case we
1053 		 *	     block.
1054 		 *
1055 		 * WARNING!  We must set KN_PROCESSING to avoid races
1056 		 *	     against deletion or another thread's
1057 		 *	     processing.
1058 		 */
1059 		TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
1060 		kq->kq_count--;
1061 
1062 		/*
1063 		 * We have to deal with an extremely important race against
1064 		 * file descriptor close()s here.  The file descriptor can
1065 		 * disappear MPSAFE, and there is a small window of
1066 		 * opportunity between that and the call to knote_fdclose().
1067 		 *
1068 		 * If we hit that window here while doselect or dopoll is
1069 		 * trying to delete a spurious event they will not be able
1070 		 * to match up the event against a knote and will go haywire.
1071 		 */
1072 		if ((kn->kn_fop->f_flags & FILTEROP_ISFD) &&
1073 		    checkfdclosed(kq->kq_fdp, kn->kn_kevent.ident, kn->kn_fp)) {
1074 			kn->kn_status |= KN_DELETING | KN_REPROCESS;
1075 		}
1076 
1077 		if (kn->kn_status & KN_DISABLED) {
1078 			/*
1079 			 * If disabled we ensure the event is not queued
1080 			 * but leave its active bit set.  On re-enablement
1081 			 * the event may be immediately triggered.
1082 			 */
1083 			kn->kn_status &= ~KN_QUEUED;
1084 		} else if ((kn->kn_flags & EV_ONESHOT) == 0 &&
1085 			   (kn->kn_status & KN_DELETING) == 0 &&
1086 			   filter_event(kn, 0) == 0) {
1087 			/*
1088 			 * If not running in one-shot mode and the event
1089 			 * is no longer present we ensure it is removed
1090 			 * from the queue and ignore it.
1091 			 */
1092 			kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1093 		} else {
1094 			/*
1095 			 * Post the event
1096 			 */
1097 			*kevp++ = kn->kn_kevent;
1098 			++total;
1099 			--count;
1100 
1101 			if (kn->kn_flags & EV_ONESHOT) {
1102 				kn->kn_status &= ~KN_QUEUED;
1103 				kn->kn_status |= KN_DELETING | KN_REPROCESS;
1104 			} else if (kn->kn_flags & EV_CLEAR) {
1105 				kn->kn_data = 0;
1106 				kn->kn_fflags = 0;
1107 				kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1108 			} else {
1109 				TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1110 				kq->kq_count++;
1111 			}
1112 		}
1113 
1114 		/*
1115 		 * Handle any post-processing states
1116 		 */
1117 		knote_release(kn);
1118 	}
1119 	TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
1120 
1121 	return (total);
1122 }
1123 
1124 /*
1125  * XXX
1126  * This could be expanded to call kqueue_scan, if desired.
1127  *
1128  * MPSAFE
1129  */
1130 static int
1131 kqueue_read(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1132 {
1133 	return (ENXIO);
1134 }
1135 
1136 /*
1137  * MPSAFE
1138  */
1139 static int
1140 kqueue_write(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1141 {
1142 	return (ENXIO);
1143 }
1144 
1145 /*
1146  * MPALMOSTSAFE
1147  */
1148 static int
1149 kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
1150 	     struct ucred *cred, struct sysmsg *msg)
1151 {
1152 	struct kqueue *kq;
1153 	int error;
1154 
1155 	lwkt_gettoken(&kq_token);
1156 	kq = (struct kqueue *)fp->f_data;
1157 
1158 	switch(com) {
1159 	case FIOASYNC:
1160 		if (*(int *)data)
1161 			kq->kq_state |= KQ_ASYNC;
1162 		else
1163 			kq->kq_state &= ~KQ_ASYNC;
1164 		error = 0;
1165 		break;
1166 	case FIOSETOWN:
1167 		error = fsetown(*(int *)data, &kq->kq_sigio);
1168 		break;
1169 	default:
1170 		error = ENOTTY;
1171 		break;
1172 	}
1173 	lwkt_reltoken(&kq_token);
1174 	return (error);
1175 }
1176 
1177 /*
1178  * MPSAFE
1179  */
1180 static int
1181 kqueue_stat(struct file *fp, struct stat *st, struct ucred *cred)
1182 {
1183 	struct kqueue *kq = (struct kqueue *)fp->f_data;
1184 
1185 	bzero((void *)st, sizeof(*st));
1186 	st->st_size = kq->kq_count;
1187 	st->st_blksize = sizeof(struct kevent);
1188 	st->st_mode = S_IFIFO;
1189 	return (0);
1190 }
1191 
1192 /*
1193  * MPSAFE
1194  */
1195 static int
1196 kqueue_close(struct file *fp)
1197 {
1198 	struct kqueue *kq = (struct kqueue *)fp->f_data;
1199 
1200 	kqueue_terminate(kq);
1201 
1202 	fp->f_data = NULL;
1203 	funsetown(kq->kq_sigio);
1204 
1205 	kfree(kq, M_KQUEUE);
1206 	return (0);
1207 }
1208 
1209 static void
1210 kqueue_wakeup(struct kqueue *kq)
1211 {
1212 	if (kq->kq_state & KQ_SLEEP) {
1213 		kq->kq_state &= ~KQ_SLEEP;
1214 		wakeup(kq);
1215 	}
1216 	KNOTE(&kq->kq_kqinfo.ki_note, 0);
1217 }
1218 
1219 /*
1220  * Calls filterops f_attach function, acquiring mplock if filter is not
1221  * marked as FILTEROP_MPSAFE.
1222  */
1223 static int
1224 filter_attach(struct knote *kn)
1225 {
1226 	int ret;
1227 
1228 	if (!(kn->kn_fop->f_flags & FILTEROP_MPSAFE)) {
1229 		get_mplock();
1230 		ret = kn->kn_fop->f_attach(kn);
1231 		rel_mplock();
1232 	} else {
1233 		ret = kn->kn_fop->f_attach(kn);
1234 	}
1235 
1236 	return (ret);
1237 }
1238 
1239 /*
1240  * Detach the knote and drop it, destroying the knote.
1241  *
1242  * Calls filterops f_detach function, acquiring mplock if filter is not
1243  * marked as FILTEROP_MPSAFE.
1244  */
1245 static void
1246 knote_detach_and_drop(struct knote *kn)
1247 {
1248 	kn->kn_status |= KN_DELETING | KN_REPROCESS;
1249 	if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1250 		kn->kn_fop->f_detach(kn);
1251 	} else {
1252 		get_mplock();
1253 		kn->kn_fop->f_detach(kn);
1254 		rel_mplock();
1255 	}
1256 	knote_drop(kn);
1257 }
1258 
1259 /*
1260  * Calls filterops f_event function, acquiring mplock if filter is not
1261  * marked as FILTEROP_MPSAFE.
1262  *
1263  * If the knote is in the middle of being created or deleted we cannot
1264  * safely call the filter op.
1265  */
1266 static int
1267 filter_event(struct knote *kn, long hint)
1268 {
1269 	int ret;
1270 
1271 	if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1272 		ret = kn->kn_fop->f_event(kn, hint);
1273 	} else {
1274 		get_mplock();
1275 		ret = kn->kn_fop->f_event(kn, hint);
1276 		rel_mplock();
1277 	}
1278 	return (ret);
1279 }
1280 
1281 /*
1282  * Walk down a list of knotes, activating them if their event has triggered.
1283  *
1284  * If we encounter any knotes which are undergoing processing we just mark
1285  * them for reprocessing and do not try to [re]activate the knote.  However,
1286  * if a hint is being passed we have to wait and that makes things a bit
1287  * sticky.
1288  */
1289 void
1290 knote(struct klist *list, long hint)
1291 {
1292 	struct knote *kn;
1293 
1294 	lwkt_gettoken(&kq_token);
1295 restart:
1296 	SLIST_FOREACH(kn, list, kn_next) {
1297 		if (kn->kn_status & KN_PROCESSING) {
1298 			/*
1299 			 * Someone else is processing the knote, ask the
1300 			 * other thread to reprocess it and don't mess
1301 			 * with it otherwise.
1302 			 */
1303 			if (hint == 0) {
1304 				kn->kn_status |= KN_REPROCESS;
1305 				continue;
1306 			}
1307 
1308 			/*
1309 			 * If the hint is non-zero we have to wait or risk
1310 			 * losing the state the caller is trying to update.
1311 			 *
1312 			 * XXX This is a real problem, certain process
1313 			 *     and signal filters will bump kn_data for
1314 			 *     already-processed notes more than once if
1315 			 *     we restart the list scan.  FIXME.
1316 			 */
1317 			kn->kn_status |= KN_WAITING | KN_REPROCESS;
1318 			tsleep(kn, 0, "knotec", hz);
1319 			goto restart;
1320 		}
1321 
1322 		/*
1323 		 * Become the reprocessing master ourselves.
1324 		 *
1325 		 * If hint is non-zer running the event is mandatory
1326 		 * when not deleting so do it whether reprocessing is
1327 		 * set or not.
1328 		 */
1329 		kn->kn_status |= KN_PROCESSING;
1330 		if ((kn->kn_status & KN_DELETING) == 0) {
1331 			if (filter_event(kn, hint))
1332 				KNOTE_ACTIVATE(kn);
1333 		}
1334 		if (knote_release(kn))
1335 			goto restart;
1336 	}
1337 	lwkt_reltoken(&kq_token);
1338 }
1339 
1340 /*
1341  * Insert knote at head of klist.
1342  *
1343  * This function may only be called via a filter function and thus
1344  * kq_token should already be held and marked for processing.
1345  */
1346 void
1347 knote_insert(struct klist *klist, struct knote *kn)
1348 {
1349 	KKASSERT(kn->kn_status & KN_PROCESSING);
1350 	ASSERT_LWKT_TOKEN_HELD(&kq_token);
1351 	SLIST_INSERT_HEAD(klist, kn, kn_next);
1352 }
1353 
1354 /*
1355  * Remove knote from a klist
1356  *
1357  * This function may only be called via a filter function and thus
1358  * kq_token should already be held and marked for processing.
1359  */
1360 void
1361 knote_remove(struct klist *klist, struct knote *kn)
1362 {
1363 	KKASSERT(kn->kn_status & KN_PROCESSING);
1364 	ASSERT_LWKT_TOKEN_HELD(&kq_token);
1365 	SLIST_REMOVE(klist, kn, knote, kn_next);
1366 }
1367 
1368 /*
1369  * Remove all knotes from a specified klist
1370  *
1371  * Only called from aio.
1372  */
1373 void
1374 knote_empty(struct klist *list)
1375 {
1376 	struct knote *kn;
1377 
1378 	lwkt_gettoken(&kq_token);
1379 	while ((kn = SLIST_FIRST(list)) != NULL) {
1380 		if (knote_acquire(kn))
1381 			knote_detach_and_drop(kn);
1382 	}
1383 	lwkt_reltoken(&kq_token);
1384 }
1385 
1386 void
1387 knote_assume_knotes(struct kqinfo *src, struct kqinfo *dst,
1388 		    struct filterops *ops, void *hook)
1389 {
1390 	struct knote *kn;
1391 
1392 	lwkt_gettoken(&kq_token);
1393 	while ((kn = SLIST_FIRST(&src->ki_note)) != NULL) {
1394 		if (knote_acquire(kn)) {
1395 			knote_remove(&src->ki_note, kn);
1396 			kn->kn_fop = ops;
1397 			kn->kn_hook = hook;
1398 			knote_insert(&dst->ki_note, kn);
1399 			knote_release(kn);
1400 			/* kn may be invalid now */
1401 		}
1402 	}
1403 	lwkt_reltoken(&kq_token);
1404 }
1405 
1406 /*
1407  * Remove all knotes referencing a specified fd
1408  */
1409 void
1410 knote_fdclose(struct file *fp, struct filedesc *fdp, int fd)
1411 {
1412 	struct knote *kn;
1413 
1414 	lwkt_gettoken(&kq_token);
1415 restart:
1416 	SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
1417 		if (kn->kn_kq->kq_fdp == fdp && kn->kn_id == fd) {
1418 			if (knote_acquire(kn))
1419 				knote_detach_and_drop(kn);
1420 			goto restart;
1421 		}
1422 	}
1423 	lwkt_reltoken(&kq_token);
1424 }
1425 
1426 /*
1427  * Low level attach function.
1428  *
1429  * The knote should already be marked for processing.
1430  */
1431 static void
1432 knote_attach(struct knote *kn)
1433 {
1434 	struct klist *list;
1435 	struct kqueue *kq = kn->kn_kq;
1436 
1437 	if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1438 		KKASSERT(kn->kn_fp);
1439 		list = &kn->kn_fp->f_klist;
1440 	} else {
1441 		if (kq->kq_knhashmask == 0)
1442 			kq->kq_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1443 						 &kq->kq_knhashmask);
1444 		list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1445 	}
1446 	SLIST_INSERT_HEAD(list, kn, kn_link);
1447 	TAILQ_INSERT_HEAD(&kq->kq_knlist, kn, kn_kqlink);
1448 }
1449 
1450 /*
1451  * Low level drop function.
1452  *
1453  * The knote should already be marked for processing.
1454  */
1455 static void
1456 knote_drop(struct knote *kn)
1457 {
1458 	struct kqueue *kq;
1459 	struct klist *list;
1460 
1461 	kq = kn->kn_kq;
1462 
1463 	if (kn->kn_fop->f_flags & FILTEROP_ISFD)
1464 		list = &kn->kn_fp->f_klist;
1465 	else
1466 		list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1467 
1468 	SLIST_REMOVE(list, kn, knote, kn_link);
1469 	TAILQ_REMOVE(&kq->kq_knlist, kn, kn_kqlink);
1470 	if (kn->kn_status & KN_QUEUED)
1471 		knote_dequeue(kn);
1472 	if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1473 		fdrop(kn->kn_fp);
1474 		kn->kn_fp = NULL;
1475 	}
1476 	knote_free(kn);
1477 }
1478 
1479 /*
1480  * Low level enqueue function.
1481  *
1482  * The knote should already be marked for processing.
1483  */
1484 static void
1485 knote_enqueue(struct knote *kn)
1486 {
1487 	struct kqueue *kq = kn->kn_kq;
1488 
1489 	KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
1490 	TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1491 	kn->kn_status |= KN_QUEUED;
1492 	++kq->kq_count;
1493 
1494 	/*
1495 	 * Send SIGIO on request (typically set up as a mailbox signal)
1496 	 */
1497 	if (kq->kq_sigio && (kq->kq_state & KQ_ASYNC) && kq->kq_count == 1)
1498 		pgsigio(kq->kq_sigio, SIGIO, 0);
1499 
1500 	kqueue_wakeup(kq);
1501 }
1502 
1503 /*
1504  * Low level dequeue function.
1505  *
1506  * The knote should already be marked for processing.
1507  */
1508 static void
1509 knote_dequeue(struct knote *kn)
1510 {
1511 	struct kqueue *kq = kn->kn_kq;
1512 
1513 	KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
1514 	TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
1515 	kn->kn_status &= ~KN_QUEUED;
1516 	kq->kq_count--;
1517 }
1518 
1519 static struct knote *
1520 knote_alloc(void)
1521 {
1522 	return kmalloc(sizeof(struct knote), M_KQUEUE, M_NOWAIT);
1523 }
1524 
1525 static void
1526 knote_free(struct knote *kn)
1527 {
1528 	kfree(kn, M_KQUEUE);
1529 }
1530