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