xref: /dflybsd-src/sys/kern/kern_event.c (revision 5b22f1a7302b644c8e417d0bf1192e953e27d3b6)
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 #include <vm/vm_zone.h>
59 
60 /*
61  * Global token for kqueue subsystem
62  */
63 struct lwkt_token kq_token = LWKT_TOKEN_UP_INITIALIZER;
64 
65 MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
66 
67 struct kevent_copyin_args {
68 	struct kevent_args	*ka;
69 	int			pchanges;
70 };
71 
72 static int	kqueue_sleep(struct kqueue *kq, struct timespec *tsp);
73 static int	kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
74 		    struct knote *marker);
75 static int 	kqueue_read(struct file *fp, struct uio *uio,
76 		    struct ucred *cred, int flags);
77 static int	kqueue_write(struct file *fp, struct uio *uio,
78 		    struct ucred *cred, int flags);
79 static int	kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
80 		    struct ucred *cred, struct sysmsg *msg);
81 static int 	kqueue_kqfilter(struct file *fp, struct knote *kn);
82 static int 	kqueue_stat(struct file *fp, struct stat *st,
83 		    struct ucred *cred);
84 static int 	kqueue_close(struct file *fp);
85 static void	kqueue_wakeup(struct kqueue *kq);
86 
87 /*
88  * MPSAFE
89  */
90 static struct fileops kqueueops = {
91 	.fo_read = kqueue_read,
92 	.fo_write = kqueue_write,
93 	.fo_ioctl = kqueue_ioctl,
94 	.fo_kqfilter = kqueue_kqfilter,
95 	.fo_stat = kqueue_stat,
96 	.fo_close = kqueue_close,
97 	.fo_shutdown = nofo_shutdown
98 };
99 
100 static void 	knote_attach(struct knote *kn);
101 static void 	knote_drop(struct knote *kn);
102 static void 	knote_enqueue(struct knote *kn);
103 static void 	knote_dequeue(struct knote *kn);
104 static void 	knote_init(void);
105 static struct 	knote *knote_alloc(void);
106 static void 	knote_free(struct knote *kn);
107 
108 static void	filt_kqdetach(struct knote *kn);
109 static int	filt_kqueue(struct knote *kn, long hint);
110 static int	filt_procattach(struct knote *kn);
111 static void	filt_procdetach(struct knote *kn);
112 static int	filt_proc(struct knote *kn, long hint);
113 static int	filt_fileattach(struct knote *kn);
114 static void	filt_timerexpire(void *knx);
115 static int	filt_timerattach(struct knote *kn);
116 static void	filt_timerdetach(struct knote *kn);
117 static int	filt_timer(struct knote *kn, long hint);
118 
119 static struct filterops file_filtops =
120 	{ 1, filt_fileattach, NULL, NULL };
121 static struct filterops kqread_filtops =
122 	{ 1, NULL, filt_kqdetach, filt_kqueue };
123 static struct filterops proc_filtops =
124 	{ 0, filt_procattach, filt_procdetach, filt_proc };
125 static struct filterops timer_filtops =
126 	{ 0, filt_timerattach, filt_timerdetach, filt_timer };
127 
128 static vm_zone_t	knote_zone;
129 static int 		kq_ncallouts = 0;
130 static int 		kq_calloutmax = (4 * 1024);
131 SYSCTL_INT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
132     &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
133 
134 #define KNOTE_ACTIVATE(kn) do { 					\
135 	kn->kn_status |= KN_ACTIVE;					\
136 	if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0)		\
137 		knote_enqueue(kn);					\
138 } while(0)
139 
140 #define	KN_HASHSIZE		64		/* XXX should be tunable */
141 #define KN_HASH(val, mask)	(((val) ^ (val >> 8)) & (mask))
142 
143 extern struct filterops aio_filtops;
144 extern struct filterops sig_filtops;
145 
146 /*
147  * Table for for all system-defined filters.
148  */
149 static struct filterops *sysfilt_ops[] = {
150 	&file_filtops,			/* EVFILT_READ */
151 	&file_filtops,			/* EVFILT_WRITE */
152 	&aio_filtops,			/* EVFILT_AIO */
153 	&file_filtops,			/* EVFILT_VNODE */
154 	&proc_filtops,			/* EVFILT_PROC */
155 	&sig_filtops,			/* EVFILT_SIGNAL */
156 	&timer_filtops,			/* EVFILT_TIMER */
157 	&file_filtops,			/* EVFILT_EXCEPT */
158 };
159 
160 static int
161 filt_fileattach(struct knote *kn)
162 {
163 	return (fo_kqfilter(kn->kn_fp, kn));
164 }
165 
166 /*
167  * MPSAFE
168  */
169 static int
170 kqueue_kqfilter(struct file *fp, struct knote *kn)
171 {
172 	struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
173 
174 	if (kn->kn_filter != EVFILT_READ)
175 		return (EOPNOTSUPP);
176 
177 	kn->kn_fop = &kqread_filtops;
178 	knote_insert(&kq->kq_kqinfo.ki_note, kn);
179 	return (0);
180 }
181 
182 static void
183 filt_kqdetach(struct knote *kn)
184 {
185 	struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
186 
187 	knote_remove(&kq->kq_kqinfo.ki_note, kn);
188 }
189 
190 /*ARGSUSED*/
191 static int
192 filt_kqueue(struct knote *kn, long hint)
193 {
194 	struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
195 
196 	kn->kn_data = kq->kq_count;
197 	return (kn->kn_data > 0);
198 }
199 
200 static int
201 filt_procattach(struct knote *kn)
202 {
203 	struct proc *p;
204 	int immediate;
205 
206 	immediate = 0;
207 	lwkt_gettoken(&proc_token);
208 	p = pfind(kn->kn_id);
209 	if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
210 		p = zpfind(kn->kn_id);
211 		immediate = 1;
212 	}
213 	if (p == NULL) {
214 		lwkt_reltoken(&proc_token);
215 		return (ESRCH);
216 	}
217 	if (!PRISON_CHECK(curthread->td_ucred, p->p_ucred)) {
218 		lwkt_reltoken(&proc_token);
219 		return (EACCES);
220 	}
221 
222 	kn->kn_ptr.p_proc = p;
223 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
224 
225 	/*
226 	 * internal flag indicating registration done by kernel
227 	 */
228 	if (kn->kn_flags & EV_FLAG1) {
229 		kn->kn_data = kn->kn_sdata;		/* ppid */
230 		kn->kn_fflags = NOTE_CHILD;
231 		kn->kn_flags &= ~EV_FLAG1;
232 	}
233 
234 	knote_insert(&p->p_klist, kn);
235 
236 	/*
237 	 * Immediately activate any exit notes if the target process is a
238 	 * zombie.  This is necessary to handle the case where the target
239 	 * process, e.g. a child, dies before the kevent is negistered.
240 	 */
241 	if (immediate && filt_proc(kn, NOTE_EXIT))
242 		KNOTE_ACTIVATE(kn);
243 	lwkt_reltoken(&proc_token);
244 
245 	return (0);
246 }
247 
248 /*
249  * The knote may be attached to a different process, which may exit,
250  * leaving nothing for the knote to be attached to.  So when the process
251  * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
252  * it will be deleted when read out.  However, as part of the knote deletion,
253  * this routine is called, so a check is needed to avoid actually performing
254  * a detach, because the original process does not exist any more.
255  */
256 static void
257 filt_procdetach(struct knote *kn)
258 {
259 	struct proc *p;
260 
261 	if (kn->kn_status & KN_DETACHED)
262 		return;
263 	/* XXX locking? take proc_token here? */
264 	p = kn->kn_ptr.p_proc;
265 	knote_remove(&p->p_klist, kn);
266 }
267 
268 static int
269 filt_proc(struct knote *kn, long hint)
270 {
271 	u_int event;
272 
273 	/*
274 	 * mask off extra data
275 	 */
276 	event = (u_int)hint & NOTE_PCTRLMASK;
277 
278 	/*
279 	 * if the user is interested in this event, record it.
280 	 */
281 	if (kn->kn_sfflags & event)
282 		kn->kn_fflags |= event;
283 
284 	/*
285 	 * Process is gone, so flag the event as finished.  Detach the
286 	 * knote from the process now because the process will be poof,
287 	 * gone later on.
288 	 */
289 	if (event == NOTE_EXIT) {
290 		struct proc *p = kn->kn_ptr.p_proc;
291 		if ((kn->kn_status & KN_DETACHED) == 0) {
292 			knote_remove(&p->p_klist, kn);
293 			kn->kn_status |= KN_DETACHED;
294 			kn->kn_data = p->p_xstat;
295 			kn->kn_ptr.p_proc = NULL;
296 		}
297 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
298 		return (1);
299 	}
300 
301 	/*
302 	 * process forked, and user wants to track the new process,
303 	 * so attach a new knote to it, and immediately report an
304 	 * event with the parent's pid.
305 	 */
306 	if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
307 		struct kevent kev;
308 		int error;
309 
310 		/*
311 		 * register knote with new process.
312 		 */
313 		kev.ident = hint & NOTE_PDATAMASK;	/* pid */
314 		kev.filter = kn->kn_filter;
315 		kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
316 		kev.fflags = kn->kn_sfflags;
317 		kev.data = kn->kn_id;			/* parent */
318 		kev.udata = kn->kn_kevent.udata;	/* preserve udata */
319 		error = kqueue_register(kn->kn_kq, &kev);
320 		if (error)
321 			kn->kn_fflags |= NOTE_TRACKERR;
322 	}
323 
324 	return (kn->kn_fflags != 0);
325 }
326 
327 static void
328 filt_timerexpire(void *knx)
329 {
330 	struct knote *kn = knx;
331 	struct callout *calloutp;
332 	struct timeval tv;
333 	int tticks;
334 
335 	kn->kn_data++;
336 	KNOTE_ACTIVATE(kn);
337 
338 	if ((kn->kn_flags & EV_ONESHOT) == 0) {
339 		tv.tv_sec = kn->kn_sdata / 1000;
340 		tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
341 		tticks = tvtohz_high(&tv);
342 		calloutp = (struct callout *)kn->kn_hook;
343 		callout_reset(calloutp, tticks, filt_timerexpire, kn);
344 	}
345 }
346 
347 /*
348  * data contains amount of time to sleep, in milliseconds
349  */
350 static int
351 filt_timerattach(struct knote *kn)
352 {
353 	struct callout *calloutp;
354 	struct timeval tv;
355 	int tticks;
356 
357 	if (kq_ncallouts >= kq_calloutmax)
358 		return (ENOMEM);
359 	kq_ncallouts++;
360 
361 	tv.tv_sec = kn->kn_sdata / 1000;
362 	tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
363 	tticks = tvtohz_high(&tv);
364 
365 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
366 	MALLOC(calloutp, struct callout *, sizeof(*calloutp),
367 	    M_KQUEUE, M_WAITOK);
368 	callout_init(calloutp);
369 	kn->kn_hook = (caddr_t)calloutp;
370 	callout_reset(calloutp, tticks, filt_timerexpire, kn);
371 
372 	return (0);
373 }
374 
375 static void
376 filt_timerdetach(struct knote *kn)
377 {
378 	struct callout *calloutp;
379 
380 	calloutp = (struct callout *)kn->kn_hook;
381 	callout_stop(calloutp);
382 	FREE(calloutp, M_KQUEUE);
383 	kq_ncallouts--;
384 }
385 
386 static int
387 filt_timer(struct knote *kn, long hint)
388 {
389 
390 	return (kn->kn_data != 0);
391 }
392 
393 /*
394  * Initialize a kqueue.
395  *
396  * NOTE: The lwp/proc code initializes a kqueue for select/poll ops.
397  *
398  * MPSAFE
399  */
400 void
401 kqueue_init(struct kqueue *kq, struct filedesc *fdp)
402 {
403 	TAILQ_INIT(&kq->kq_knpend);
404 	TAILQ_INIT(&kq->kq_knlist);
405 	kq->kq_count = 0;
406 	kq->kq_fdp = fdp;
407 	SLIST_INIT(&kq->kq_kqinfo.ki_note);
408 }
409 
410 /*
411  * Terminate a kqueue.  Freeing the actual kq itself is left up to the
412  * caller (it might be embedded in a lwp so we don't do it here).
413  */
414 void
415 kqueue_terminate(struct kqueue *kq)
416 {
417 	struct knote *kn;
418 	struct klist *list;
419 	int hv;
420 
421 	while ((kn = TAILQ_FIRST(&kq->kq_knlist)) != NULL) {
422 		kn->kn_fop->f_detach(kn);
423 		if (kn->kn_fop->f_isfd) {
424 			list = &kn->kn_fp->f_klist;
425 			SLIST_REMOVE(list, kn, knote, kn_link);
426 			fdrop(kn->kn_fp);
427 			kn->kn_fp = NULL;
428 		} else {
429 			hv = KN_HASH(kn->kn_id, kq->kq_knhashmask);
430 			list = &kq->kq_knhash[hv];
431 			SLIST_REMOVE(list, kn, knote, kn_link);
432 		}
433 		TAILQ_REMOVE(&kq->kq_knlist, kn, kn_kqlink);
434 		if (kn->kn_status & KN_QUEUED)
435 			knote_dequeue(kn);
436 		knote_free(kn);
437 	}
438 
439 	if (kq->kq_knhash) {
440 		kfree(kq->kq_knhash, M_KQUEUE);
441 		kq->kq_knhash = NULL;
442 		kq->kq_knhashmask = 0;
443 	}
444 }
445 
446 /*
447  * MPSAFE
448  */
449 int
450 sys_kqueue(struct kqueue_args *uap)
451 {
452 	struct thread *td = curthread;
453 	struct kqueue *kq;
454 	struct file *fp;
455 	int fd, error;
456 
457 	error = falloc(td->td_lwp, &fp, &fd);
458 	if (error)
459 		return (error);
460 	fp->f_flag = FREAD | FWRITE;
461 	fp->f_type = DTYPE_KQUEUE;
462 	fp->f_ops = &kqueueops;
463 
464 	kq = kmalloc(sizeof(struct kqueue), M_KQUEUE, M_WAITOK | M_ZERO);
465 	kqueue_init(kq, td->td_proc->p_fd);
466 	fp->f_data = kq;
467 
468 	fsetfd(kq->kq_fdp, fp, fd);
469 	uap->sysmsg_result = fd;
470 	fdrop(fp);
471 	return (error);
472 }
473 
474 /*
475  * Copy 'count' items into the destination list pointed to by uap->eventlist.
476  */
477 static int
478 kevent_copyout(void *arg, struct kevent *kevp, int count, int *res)
479 {
480 	struct kevent_copyin_args *kap;
481 	int error;
482 
483 	kap = (struct kevent_copyin_args *)arg;
484 
485 	error = copyout(kevp, kap->ka->eventlist, count * sizeof(*kevp));
486 	if (error == 0) {
487 		kap->ka->eventlist += count;
488 		*res += count;
489 	} else {
490 		*res = -1;
491 	}
492 
493 	return (error);
494 }
495 
496 /*
497  * Copy at most 'max' items from the list pointed to by kap->changelist,
498  * return number of items in 'events'.
499  */
500 static int
501 kevent_copyin(void *arg, struct kevent *kevp, int max, int *events)
502 {
503 	struct kevent_copyin_args *kap;
504 	int error, count;
505 
506 	kap = (struct kevent_copyin_args *)arg;
507 
508 	count = min(kap->ka->nchanges - kap->pchanges, max);
509 	error = copyin(kap->ka->changelist, kevp, count * sizeof *kevp);
510 	if (error == 0) {
511 		kap->ka->changelist += count;
512 		kap->pchanges += count;
513 		*events = count;
514 	}
515 
516 	return (error);
517 }
518 
519 /*
520  * MPSAFE
521  */
522 int
523 kern_kevent(struct kqueue *kq, int nevents, int *res, void *uap,
524 	    k_copyin_fn kevent_copyinfn, k_copyout_fn kevent_copyoutfn,
525 	    struct timespec *tsp_in)
526 {
527 	struct kevent *kevp;
528 	struct timespec *tsp;
529 	int i, n, total, error, nerrors = 0;
530 	int lres;
531 	struct kevent kev[KQ_NEVENTS];
532 	struct knote marker;
533 
534 	tsp = tsp_in;
535 	*res = 0;
536 
537 	lwkt_gettoken(&kq_token);
538 	for ( ;; ) {
539 		n = 0;
540 		error = kevent_copyinfn(uap, kev, KQ_NEVENTS, &n);
541 		if (error)
542 			goto done;
543 		if (n == 0)
544 			break;
545 		for (i = 0; i < n; i++) {
546 			kevp = &kev[i];
547 			kevp->flags &= ~EV_SYSFLAGS;
548 			error = kqueue_register(kq, kevp);
549 
550 			/*
551 			 * If a registration returns an error we
552 			 * immediately post the error.  The kevent()
553 			 * call itself will fail with the error if
554 			 * no space is available for posting.
555 			 *
556 			 * Such errors normally bypass the timeout/blocking
557 			 * code.  However, if the copyoutfn function refuses
558 			 * to post the error (see sys_poll()), then we
559 			 * ignore it too.
560 			 */
561 			if (error) {
562 				kevp->flags = EV_ERROR;
563 				kevp->data = error;
564 				lres = *res;
565 				kevent_copyoutfn(uap, kevp, 1, res);
566 				if (lres != *res) {
567 					nevents--;
568 					nerrors++;
569 				}
570 			}
571 		}
572 	}
573 	if (nerrors) {
574 		error = 0;
575 		goto done;
576 	}
577 
578 	/*
579 	 * Acquire/wait for events - setup timeout
580 	 */
581 	if (tsp != NULL) {
582 		struct timespec ats;
583 
584 		if (tsp->tv_sec || tsp->tv_nsec) {
585 			nanouptime(&ats);
586 			timespecadd(tsp, &ats);		/* tsp = target time */
587 		}
588 	}
589 
590 	/*
591 	 * Loop as required.
592 	 *
593 	 * Collect as many events as we can. Sleeping on successive
594 	 * loops is disabled if copyoutfn has incremented (*res).
595 	 *
596 	 * The loop stops if an error occurs, all events have been
597 	 * scanned (the marker has been reached), or fewer than the
598 	 * maximum number of events is found.
599 	 *
600 	 * The copyoutfn function does not have to increment (*res) in
601 	 * order for the loop to continue.
602 	 *
603 	 * NOTE: doselect() usually passes 0x7FFFFFFF for nevents.
604 	 */
605 	total = 0;
606 	error = 0;
607 	marker.kn_filter = EVFILT_MARKER;
608 	TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
609 	while ((n = nevents - total) > 0) {
610 		if (n > KQ_NEVENTS)
611 			n = KQ_NEVENTS;
612 
613 		/*
614 		 * If no events are pending sleep until timeout (if any)
615 		 * or an event occurs.
616 		 *
617 		 * After the sleep completes the marker is moved to the
618 		 * end of the list, making any received events available
619 		 * to our scan.
620 		 */
621 		if (kq->kq_count == 0 && *res == 0) {
622 			error = kqueue_sleep(kq, tsp);
623 			if (error)
624 				break;
625 
626 			TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
627 			TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
628 		}
629 
630 		/*
631 		 * Process all received events
632 		 * Account for all non-spurious events in our total
633 		 */
634 		i = kqueue_scan(kq, kev, n, &marker);
635 		if (i) {
636 			lres = *res;
637 			error = kevent_copyoutfn(uap, kev, i, res);
638 			total += *res - lres;
639 			if (error)
640 				break;
641 		}
642 
643 		/*
644 		 * Normally when fewer events are returned than requested
645 		 * we can stop.  However, if only spurious events were
646 		 * collected the copyout will not bump (*res) and we have
647 		 * to continue.
648 		 */
649 		if (i < n && *res)
650 			break;
651 
652 		/*
653 		 * Deal with an edge case where spurious events can cause
654 		 * a loop to occur without moving the marker.  This can
655 		 * prevent kqueue_scan() from picking up new events which
656 		 * race us.  We must be sure to move the marker for this
657 		 * case.
658 		 *
659 		 * NOTE: We do not want to move the marker if events
660 		 *	 were scanned because normal kqueue operations
661 		 *	 may reactivate events.  Moving the marker in
662 		 *	 that case could result in duplicates for the
663 		 *	 same event.
664 		 */
665 		if (i == 0) {
666 			TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
667 			TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
668 		}
669 	}
670 	TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
671 
672 	/* Timeouts do not return EWOULDBLOCK. */
673 	if (error == EWOULDBLOCK)
674 		error = 0;
675 
676 done:
677 	lwkt_reltoken(&kq_token);
678 	return (error);
679 }
680 
681 /*
682  * MPALMOSTSAFE
683  */
684 int
685 sys_kevent(struct kevent_args *uap)
686 {
687 	struct thread *td = curthread;
688 	struct proc *p = td->td_proc;
689 	struct timespec ts, *tsp;
690 	struct kqueue *kq;
691 	struct file *fp = NULL;
692 	struct kevent_copyin_args *kap, ka;
693 	int error;
694 
695 	if (uap->timeout) {
696 		error = copyin(uap->timeout, &ts, sizeof(ts));
697 		if (error)
698 			return (error);
699 		tsp = &ts;
700 	} else {
701 		tsp = NULL;
702 	}
703 
704 	fp = holdfp(p->p_fd, uap->fd, -1);
705 	if (fp == NULL)
706 		return (EBADF);
707 	if (fp->f_type != DTYPE_KQUEUE) {
708 		fdrop(fp);
709 		return (EBADF);
710 	}
711 
712 	kq = (struct kqueue *)fp->f_data;
713 
714 	kap = &ka;
715 	kap->ka = uap;
716 	kap->pchanges = 0;
717 
718 	error = kern_kevent(kq, uap->nevents, &uap->sysmsg_result, kap,
719 			    kevent_copyin, kevent_copyout, tsp);
720 
721 	fdrop(fp);
722 
723 	return (error);
724 }
725 
726 int
727 kqueue_register(struct kqueue *kq, struct kevent *kev)
728 {
729 	struct filedesc *fdp = kq->kq_fdp;
730 	struct filterops *fops;
731 	struct file *fp = NULL;
732 	struct knote *kn = NULL;
733 	int error = 0;
734 
735 	if (kev->filter < 0) {
736 		if (kev->filter + EVFILT_SYSCOUNT < 0)
737 			return (EINVAL);
738 		fops = sysfilt_ops[~kev->filter];	/* to 0-base index */
739 	} else {
740 		/*
741 		 * XXX
742 		 * filter attach routine is responsible for insuring that
743 		 * the identifier can be attached to it.
744 		 */
745 		kprintf("unknown filter: %d\n", kev->filter);
746 		return (EINVAL);
747 	}
748 
749 	if (fops->f_isfd) {
750 		/* validate descriptor */
751 		fp = holdfp(fdp, kev->ident, -1);
752 		if (fp == NULL)
753 			return (EBADF);
754 
755 		SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
756 			if (kn->kn_kq == kq &&
757 			    kn->kn_filter == kev->filter &&
758 			    kn->kn_id == kev->ident) {
759 				break;
760 			}
761 		}
762 	} else {
763 		if (kq->kq_knhashmask) {
764 			struct klist *list;
765 
766 			list = &kq->kq_knhash[
767 			    KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
768 			SLIST_FOREACH(kn, list, kn_link) {
769 				if (kn->kn_id == kev->ident &&
770 				    kn->kn_filter == kev->filter)
771 					break;
772 			}
773 		}
774 	}
775 
776 	if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
777 		error = ENOENT;
778 		goto done;
779 	}
780 
781 	/*
782 	 * kn now contains the matching knote, or NULL if no match
783 	 */
784 	if (kev->flags & EV_ADD) {
785 		if (kn == NULL) {
786 			kn = knote_alloc();
787 			if (kn == NULL) {
788 				error = ENOMEM;
789 				goto done;
790 			}
791 			kn->kn_fp = fp;
792 			kn->kn_kq = kq;
793 			kn->kn_fop = fops;
794 
795 			/*
796 			 * apply reference count to knote structure, and
797 			 * do not release it at the end of this routine.
798 			 */
799 			fp = NULL;
800 
801 			kn->kn_sfflags = kev->fflags;
802 			kn->kn_sdata = kev->data;
803 			kev->fflags = 0;
804 			kev->data = 0;
805 			kn->kn_kevent = *kev;
806 
807 			knote_attach(kn);
808 			if ((error = fops->f_attach(kn)) != 0) {
809 				knote_drop(kn);
810 				goto done;
811 			}
812 		} else {
813 			/*
814 			 * The user may change some filter values after the
815 			 * initial EV_ADD, but doing so will not reset any
816 			 * filter which have already been triggered.
817 			 */
818 			kn->kn_sfflags = kev->fflags;
819 			kn->kn_sdata = kev->data;
820 			kn->kn_kevent.udata = kev->udata;
821 		}
822 
823 		if (kn->kn_fop->f_event(kn, 0))
824 			KNOTE_ACTIVATE(kn);
825 	} else if (kev->flags & EV_DELETE) {
826 		kn->kn_fop->f_detach(kn);
827 		knote_drop(kn);
828 		goto done;
829 	}
830 
831 	if ((kev->flags & EV_DISABLE) &&
832 	    ((kn->kn_status & KN_DISABLED) == 0)) {
833 		kn->kn_status |= KN_DISABLED;
834 	}
835 
836 	if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
837 		kn->kn_status &= ~KN_DISABLED;
838 		if ((kn->kn_status & KN_ACTIVE) &&
839 		    ((kn->kn_status & KN_QUEUED) == 0))
840 			knote_enqueue(kn);
841 	}
842 
843 done:
844 	if (fp != NULL)
845 		fdrop(fp);
846 	return (error);
847 }
848 
849 /*
850  * Block as necessary until the target time is reached.
851  * If tsp is NULL we block indefinitely.  If tsp->ts_secs/nsecs are both
852  * 0 we do not block at all.
853  */
854 static int
855 kqueue_sleep(struct kqueue *kq, struct timespec *tsp)
856 {
857 	int error = 0;
858 
859 	if (tsp == NULL) {
860 		kq->kq_state |= KQ_SLEEP;
861 		error = tsleep(kq, PCATCH, "kqread", 0);
862 	} else if (tsp->tv_sec == 0 && tsp->tv_nsec == 0) {
863 		error = EWOULDBLOCK;
864 	} else {
865 		struct timespec ats;
866 		struct timespec atx = *tsp;
867 		int timeout;
868 
869 		nanouptime(&ats);
870 		timespecsub(&atx, &ats);
871 		if (ats.tv_sec < 0) {
872 			error = EWOULDBLOCK;
873 		} else {
874 			timeout = atx.tv_sec > 24 * 60 * 60 ?
875 				24 * 60 * 60 * hz : tstohz_high(&atx);
876 			kq->kq_state |= KQ_SLEEP;
877 			error = tsleep(kq, PCATCH, "kqread", timeout);
878 		}
879 	}
880 
881 	/* don't restart after signals... */
882 	if (error == ERESTART)
883 		return (EINTR);
884 
885 	return (error);
886 }
887 
888 /*
889  * Scan the kqueue, return the number of active events placed in kevp up
890  * to count.
891  *
892  * Continuous mode events may get recycled, do not continue scanning past
893  * marker unless no events have been collected.
894  */
895 static int
896 kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
897             struct knote *marker)
898 {
899         struct knote *kn, local_marker;
900         int total;
901 
902         total = 0;
903 	local_marker.kn_filter = EVFILT_MARKER;
904 
905 	/*
906 	 * Collect events.
907 	 */
908 	TAILQ_INSERT_HEAD(&kq->kq_knpend, &local_marker, kn_tqe);
909 	while (count) {
910 		kn = TAILQ_NEXT(&local_marker, kn_tqe);
911 		if (kn->kn_filter == EVFILT_MARKER) {
912 			/* Marker reached, we are done */
913 			if (kn == marker)
914 				break;
915 
916 			/* Move local marker past some other threads marker */
917 			kn = TAILQ_NEXT(kn, kn_tqe);
918 			TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
919 			TAILQ_INSERT_BEFORE(kn, &local_marker, kn_tqe);
920 			continue;
921 		}
922 
923 		TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
924 		if (kn->kn_status & KN_DISABLED) {
925 			kn->kn_status &= ~KN_QUEUED;
926 			kq->kq_count--;
927 			continue;
928 		}
929 		if ((kn->kn_flags & EV_ONESHOT) == 0 &&
930 		    kn->kn_fop->f_event(kn, 0) == 0) {
931 			kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
932 			kq->kq_count--;
933 			continue;
934 		}
935 		*kevp++ = kn->kn_kevent;
936 		++total;
937 		--count;
938 
939 		/*
940 		 * Post-event action on the note
941 		 */
942 		if (kn->kn_flags & EV_ONESHOT) {
943 			kn->kn_status &= ~KN_QUEUED;
944 			kq->kq_count--;
945 			kn->kn_fop->f_detach(kn);
946 			knote_drop(kn);
947 		} else if (kn->kn_flags & EV_CLEAR) {
948 			kn->kn_data = 0;
949 			kn->kn_fflags = 0;
950 			kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
951 			kq->kq_count--;
952 		} else {
953 			TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
954 		}
955 	}
956 	TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
957 
958 	return (total);
959 }
960 
961 /*
962  * XXX
963  * This could be expanded to call kqueue_scan, if desired.
964  *
965  * MPSAFE
966  */
967 static int
968 kqueue_read(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
969 {
970 	return (ENXIO);
971 }
972 
973 /*
974  * MPSAFE
975  */
976 static int
977 kqueue_write(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
978 {
979 	return (ENXIO);
980 }
981 
982 /*
983  * MPALMOSTSAFE
984  */
985 static int
986 kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
987 	     struct ucred *cred, struct sysmsg *msg)
988 {
989 	struct kqueue *kq;
990 	int error;
991 
992 	lwkt_gettoken(&kq_token);
993 	kq = (struct kqueue *)fp->f_data;
994 
995 	switch(com) {
996 	case FIOASYNC:
997 		if (*(int *)data)
998 			kq->kq_state |= KQ_ASYNC;
999 		else
1000 			kq->kq_state &= ~KQ_ASYNC;
1001 		error = 0;
1002 		break;
1003 	case FIOSETOWN:
1004 		error = fsetown(*(int *)data, &kq->kq_sigio);
1005 		break;
1006 	default:
1007 		error = ENOTTY;
1008 		break;
1009 	}
1010 	lwkt_reltoken(&kq_token);
1011 	return (error);
1012 }
1013 
1014 /*
1015  * MPSAFE
1016  */
1017 static int
1018 kqueue_stat(struct file *fp, struct stat *st, struct ucred *cred)
1019 {
1020 	struct kqueue *kq = (struct kqueue *)fp->f_data;
1021 
1022 	bzero((void *)st, sizeof(*st));
1023 	st->st_size = kq->kq_count;
1024 	st->st_blksize = sizeof(struct kevent);
1025 	st->st_mode = S_IFIFO;
1026 	return (0);
1027 }
1028 
1029 /*
1030  * MPSAFE
1031  */
1032 static int
1033 kqueue_close(struct file *fp)
1034 {
1035 	struct kqueue *kq = (struct kqueue *)fp->f_data;
1036 
1037 	lwkt_gettoken(&kq_token);
1038 
1039 	kqueue_terminate(kq);
1040 
1041 	fp->f_data = NULL;
1042 	funsetown(kq->kq_sigio);
1043 	lwkt_reltoken(&kq_token);
1044 
1045 	kfree(kq, M_KQUEUE);
1046 	return (0);
1047 }
1048 
1049 static void
1050 kqueue_wakeup(struct kqueue *kq)
1051 {
1052 	if (kq->kq_state & KQ_SLEEP) {
1053 		kq->kq_state &= ~KQ_SLEEP;
1054 		wakeup(kq);
1055 	}
1056 	KNOTE(&kq->kq_kqinfo.ki_note, 0);
1057 }
1058 
1059 /*
1060  * walk down a list of knotes, activating them if their event has triggered.
1061  */
1062 void
1063 knote(struct klist *list, long hint)
1064 {
1065 	struct knote *kn;
1066 
1067 	lwkt_gettoken(&kq_token);
1068 	SLIST_FOREACH(kn, list, kn_next)
1069 		if (kn->kn_fop->f_event(kn, hint))
1070 			KNOTE_ACTIVATE(kn);
1071 	lwkt_reltoken(&kq_token);
1072 }
1073 
1074 /*
1075  * insert knote at head of klist
1076  *
1077  * Requires: kq_token
1078  */
1079 void
1080 knote_insert(struct klist *klist, struct knote *kn)
1081 {
1082 	SLIST_INSERT_HEAD(klist, kn, kn_next);
1083 }
1084 
1085 /*
1086  * remove knote from a klist
1087  *
1088  * Requires: kq_token
1089  */
1090 void
1091 knote_remove(struct klist *klist, struct knote *kn)
1092 {
1093 	SLIST_REMOVE(klist, kn, knote, kn_next);
1094 }
1095 
1096 /*
1097  * remove all knotes from a specified klist
1098  */
1099 void
1100 knote_empty(struct klist *list)
1101 {
1102 	struct knote *kn;
1103 
1104 	lwkt_gettoken(&kq_token);
1105 	while ((kn = SLIST_FIRST(list)) != NULL) {
1106 		kn->kn_fop->f_detach(kn);
1107 		knote_drop(kn);
1108 	}
1109 	lwkt_reltoken(&kq_token);
1110 }
1111 
1112 /*
1113  * remove all knotes referencing a specified fd
1114  */
1115 void
1116 knote_fdclose(struct file *fp, struct filedesc *fdp, int fd)
1117 {
1118 	struct knote *kn;
1119 
1120 	lwkt_gettoken(&kq_token);
1121 restart:
1122 	SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
1123 		if (kn->kn_kq->kq_fdp == fdp && kn->kn_id == fd) {
1124 			kn->kn_fop->f_detach(kn);
1125 			knote_drop(kn);
1126 			goto restart;
1127 		}
1128 	}
1129 	lwkt_reltoken(&kq_token);
1130 }
1131 
1132 static void
1133 knote_attach(struct knote *kn)
1134 {
1135 	struct klist *list;
1136 	struct kqueue *kq = kn->kn_kq;
1137 
1138 	if (kn->kn_fop->f_isfd) {
1139 		KKASSERT(kn->kn_fp);
1140 		list = &kn->kn_fp->f_klist;
1141 	} else {
1142 		if (kq->kq_knhashmask == 0)
1143 			kq->kq_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1144 						 &kq->kq_knhashmask);
1145 		list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1146 	}
1147 	SLIST_INSERT_HEAD(list, kn, kn_link);
1148 	TAILQ_INSERT_HEAD(&kq->kq_knlist, kn, kn_kqlink);
1149 	kn->kn_status = 0;
1150 }
1151 
1152 static void
1153 knote_drop(struct knote *kn)
1154 {
1155 	struct kqueue *kq;
1156 	struct klist *list;
1157 
1158 	kq = kn->kn_kq;
1159 
1160 	if (kn->kn_fop->f_isfd)
1161 		list = &kn->kn_fp->f_klist;
1162 	else
1163 		list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1164 
1165 	SLIST_REMOVE(list, kn, knote, kn_link);
1166 	TAILQ_REMOVE(&kq->kq_knlist, kn, kn_kqlink);
1167 	if (kn->kn_status & KN_QUEUED)
1168 		knote_dequeue(kn);
1169 	if (kn->kn_fop->f_isfd)
1170 		fdrop(kn->kn_fp);
1171 	knote_free(kn);
1172 }
1173 
1174 
1175 static void
1176 knote_enqueue(struct knote *kn)
1177 {
1178 	struct kqueue *kq = kn->kn_kq;
1179 
1180 	KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
1181 
1182 	TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1183 	kn->kn_status |= KN_QUEUED;
1184 	++kq->kq_count;
1185 
1186 	/*
1187 	 * Send SIGIO on request (typically set up as a mailbox signal)
1188 	 */
1189 	if (kq->kq_sigio && (kq->kq_state & KQ_ASYNC) && kq->kq_count == 1)
1190 		pgsigio(kq->kq_sigio, SIGIO, 0);
1191 
1192 	kqueue_wakeup(kq);
1193 }
1194 
1195 static void
1196 knote_dequeue(struct knote *kn)
1197 {
1198 	struct kqueue *kq = kn->kn_kq;
1199 
1200 	KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
1201 
1202 	TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
1203 	kn->kn_status &= ~KN_QUEUED;
1204 	kq->kq_count--;
1205 }
1206 
1207 static void
1208 knote_init(void)
1209 {
1210 	knote_zone = zinit("KNOTE", sizeof(struct knote), 0, 0, 1);
1211 }
1212 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL)
1213 
1214 static struct knote *
1215 knote_alloc(void)
1216 {
1217 	return ((struct knote *)zalloc(knote_zone));
1218 }
1219 
1220 static void
1221 knote_free(struct knote *kn)
1222 {
1223 	zfree(knote_zone, kn);
1224 }
1225