xref: /dflybsd-src/sys/kern/kern_event.c (revision 14343ad3b815bafa1bcec3656de2d614fcc75bec)
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(kq_token);
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 static int	filter_attach(struct knote *kn);
87 static int	filter_event(struct knote *kn, long hint);
88 
89 /*
90  * MPSAFE
91  */
92 static struct fileops kqueueops = {
93 	.fo_read = kqueue_read,
94 	.fo_write = kqueue_write,
95 	.fo_ioctl = kqueue_ioctl,
96 	.fo_kqfilter = kqueue_kqfilter,
97 	.fo_stat = kqueue_stat,
98 	.fo_close = kqueue_close,
99 	.fo_shutdown = nofo_shutdown
100 };
101 
102 static void 	knote_attach(struct knote *kn);
103 static void 	knote_drop(struct knote *kn);
104 static void	knote_detach_and_drop(struct knote *kn);
105 static void 	knote_enqueue(struct knote *kn);
106 static void 	knote_dequeue(struct knote *kn);
107 static void 	knote_init(void);
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 vm_zone_t	knote_zone;
132 static int 		kq_ncallouts = 0;
133 static int 		kq_calloutmax = (4 * 1024);
134 SYSCTL_INT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
135     &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
136 static int		kq_checkloop = 1000000;
137 SYSCTL_INT(_kern, OID_AUTO, kq_checkloop, CTLFLAG_RW,
138     &kq_checkloop, 0, "Maximum number of callouts allocated for kqueue");
139 
140 #define KNOTE_ACTIVATE(kn) do { 					\
141 	kn->kn_status |= KN_ACTIVE;					\
142 	if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0)		\
143 		knote_enqueue(kn);					\
144 } while(0)
145 
146 #define	KN_HASHSIZE		64		/* XXX should be tunable */
147 #define KN_HASH(val, mask)	(((val) ^ (val >> 8)) & (mask))
148 
149 extern struct filterops aio_filtops;
150 extern struct filterops sig_filtops;
151 
152 /*
153  * Table for for all system-defined filters.
154  */
155 static struct filterops *sysfilt_ops[] = {
156 	&file_filtops,			/* EVFILT_READ */
157 	&file_filtops,			/* EVFILT_WRITE */
158 	&aio_filtops,			/* EVFILT_AIO */
159 	&file_filtops,			/* EVFILT_VNODE */
160 	&proc_filtops,			/* EVFILT_PROC */
161 	&sig_filtops,			/* EVFILT_SIGNAL */
162 	&timer_filtops,			/* EVFILT_TIMER */
163 	&file_filtops,			/* EVFILT_EXCEPT */
164 };
165 
166 static int
167 filt_fileattach(struct knote *kn)
168 {
169 	return (fo_kqfilter(kn->kn_fp, kn));
170 }
171 
172 /*
173  * MPSAFE
174  */
175 static int
176 kqueue_kqfilter(struct file *fp, struct knote *kn)
177 {
178 	struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
179 
180 	if (kn->kn_filter != EVFILT_READ)
181 		return (EOPNOTSUPP);
182 
183 	kn->kn_fop = &kqread_filtops;
184 	knote_insert(&kq->kq_kqinfo.ki_note, kn);
185 	return (0);
186 }
187 
188 static void
189 filt_kqdetach(struct knote *kn)
190 {
191 	struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
192 
193 	knote_remove(&kq->kq_kqinfo.ki_note, kn);
194 }
195 
196 /*ARGSUSED*/
197 static int
198 filt_kqueue(struct knote *kn, long hint)
199 {
200 	struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
201 
202 	kn->kn_data = kq->kq_count;
203 	return (kn->kn_data > 0);
204 }
205 
206 static int
207 filt_procattach(struct knote *kn)
208 {
209 	struct proc *p;
210 	int immediate;
211 
212 	immediate = 0;
213 	lwkt_gettoken(&proc_token);
214 	p = pfind(kn->kn_id);
215 	if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
216 		p = zpfind(kn->kn_id);
217 		immediate = 1;
218 	}
219 	if (p == NULL) {
220 		lwkt_reltoken(&proc_token);
221 		return (ESRCH);
222 	}
223 	if (!PRISON_CHECK(curthread->td_ucred, p->p_ucred)) {
224 		lwkt_reltoken(&proc_token);
225 		return (EACCES);
226 	}
227 
228 	kn->kn_ptr.p_proc = p;
229 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
230 
231 	/*
232 	 * internal flag indicating registration done by kernel
233 	 */
234 	if (kn->kn_flags & EV_FLAG1) {
235 		kn->kn_data = kn->kn_sdata;		/* ppid */
236 		kn->kn_fflags = NOTE_CHILD;
237 		kn->kn_flags &= ~EV_FLAG1;
238 	}
239 
240 	knote_insert(&p->p_klist, kn);
241 
242 	/*
243 	 * Immediately activate any exit notes if the target process is a
244 	 * zombie.  This is necessary to handle the case where the target
245 	 * process, e.g. a child, dies before the kevent is negistered.
246 	 */
247 	if (immediate && filt_proc(kn, NOTE_EXIT))
248 		KNOTE_ACTIVATE(kn);
249 	lwkt_reltoken(&proc_token);
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 static void
334 filt_timerexpire(void *knx)
335 {
336 	struct knote *kn = knx;
337 	struct callout *calloutp;
338 	struct timeval tv;
339 	int tticks;
340 
341 	lwkt_gettoken(&kq_token);
342 
343 	kn->kn_data++;
344 	KNOTE_ACTIVATE(kn);
345 
346 	if ((kn->kn_flags & EV_ONESHOT) == 0) {
347 		tv.tv_sec = kn->kn_sdata / 1000;
348 		tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
349 		tticks = tvtohz_high(&tv);
350 		calloutp = (struct callout *)kn->kn_hook;
351 		callout_reset(calloutp, tticks, filt_timerexpire, kn);
352 	}
353 
354 	lwkt_reltoken(&kq_token);
355 }
356 
357 /*
358  * data contains amount of time to sleep, in milliseconds
359  */
360 static int
361 filt_timerattach(struct knote *kn)
362 {
363 	struct callout *calloutp;
364 	struct timeval tv;
365 	int tticks;
366 
367 	if (kq_ncallouts >= kq_calloutmax)
368 		return (ENOMEM);
369 	kq_ncallouts++;
370 
371 	tv.tv_sec = kn->kn_sdata / 1000;
372 	tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
373 	tticks = tvtohz_high(&tv);
374 
375 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
376 	MALLOC(calloutp, struct callout *, sizeof(*calloutp),
377 	    M_KQUEUE, M_WAITOK);
378 	callout_init(calloutp);
379 	kn->kn_hook = (caddr_t)calloutp;
380 	callout_reset(calloutp, tticks, filt_timerexpire, kn);
381 
382 	return (0);
383 }
384 
385 static void
386 filt_timerdetach(struct knote *kn)
387 {
388 	struct callout *calloutp;
389 
390 	calloutp = (struct callout *)kn->kn_hook;
391 	callout_stop(calloutp);
392 	FREE(calloutp, M_KQUEUE);
393 	kq_ncallouts--;
394 }
395 
396 static int
397 filt_timer(struct knote *kn, long hint)
398 {
399 
400 	return (kn->kn_data != 0);
401 }
402 
403 /*
404  * Initialize a kqueue.
405  *
406  * NOTE: The lwp/proc code initializes a kqueue for select/poll ops.
407  *
408  * MPSAFE
409  */
410 void
411 kqueue_init(struct kqueue *kq, struct filedesc *fdp)
412 {
413 	TAILQ_INIT(&kq->kq_knpend);
414 	TAILQ_INIT(&kq->kq_knlist);
415 	kq->kq_count = 0;
416 	kq->kq_fdp = fdp;
417 	SLIST_INIT(&kq->kq_kqinfo.ki_note);
418 }
419 
420 /*
421  * Terminate a kqueue.  Freeing the actual kq itself is left up to the
422  * caller (it might be embedded in a lwp so we don't do it here).
423  */
424 void
425 kqueue_terminate(struct kqueue *kq)
426 {
427 	struct knote *kn;
428 
429 	lwkt_gettoken(&kq_token);
430 	while ((kn = TAILQ_FIRST(&kq->kq_knlist)) != NULL)
431 		knote_detach_and_drop(kn);
432 
433 	if (kq->kq_knhash) {
434 		kfree(kq->kq_knhash, M_KQUEUE);
435 		kq->kq_knhash = NULL;
436 		kq->kq_knhashmask = 0;
437 	}
438 	lwkt_reltoken(&kq_token);
439 }
440 
441 /*
442  * MPSAFE
443  */
444 int
445 sys_kqueue(struct kqueue_args *uap)
446 {
447 	struct thread *td = curthread;
448 	struct kqueue *kq;
449 	struct file *fp;
450 	int fd, error;
451 
452 	error = falloc(td->td_lwp, &fp, &fd);
453 	if (error)
454 		return (error);
455 	fp->f_flag = FREAD | FWRITE;
456 	fp->f_type = DTYPE_KQUEUE;
457 	fp->f_ops = &kqueueops;
458 
459 	kq = kmalloc(sizeof(struct kqueue), M_KQUEUE, M_WAITOK | M_ZERO);
460 	kqueue_init(kq, td->td_proc->p_fd);
461 	fp->f_data = kq;
462 
463 	fsetfd(kq->kq_fdp, fp, fd);
464 	uap->sysmsg_result = fd;
465 	fdrop(fp);
466 	return (error);
467 }
468 
469 /*
470  * Copy 'count' items into the destination list pointed to by uap->eventlist.
471  */
472 static int
473 kevent_copyout(void *arg, struct kevent *kevp, int count, int *res)
474 {
475 	struct kevent_copyin_args *kap;
476 	int error;
477 
478 	kap = (struct kevent_copyin_args *)arg;
479 
480 	error = copyout(kevp, kap->ka->eventlist, count * sizeof(*kevp));
481 	if (error == 0) {
482 		kap->ka->eventlist += count;
483 		*res += count;
484 	} else {
485 		*res = -1;
486 	}
487 
488 	return (error);
489 }
490 
491 /*
492  * Copy at most 'max' items from the list pointed to by kap->changelist,
493  * return number of items in 'events'.
494  */
495 static int
496 kevent_copyin(void *arg, struct kevent *kevp, int max, int *events)
497 {
498 	struct kevent_copyin_args *kap;
499 	int error, count;
500 
501 	kap = (struct kevent_copyin_args *)arg;
502 
503 	count = min(kap->ka->nchanges - kap->pchanges, max);
504 	error = copyin(kap->ka->changelist, kevp, count * sizeof *kevp);
505 	if (error == 0) {
506 		kap->ka->changelist += count;
507 		kap->pchanges += count;
508 		*events = count;
509 	}
510 
511 	return (error);
512 }
513 
514 /*
515  * MPSAFE
516  */
517 int
518 kern_kevent(struct kqueue *kq, int nevents, int *res, void *uap,
519 	    k_copyin_fn kevent_copyinfn, k_copyout_fn kevent_copyoutfn,
520 	    struct timespec *tsp_in)
521 {
522 	struct kevent *kevp;
523 	struct timespec *tsp;
524 	int i, n, total, error, nerrors = 0;
525 	int lres;
526 	int limit = kq_checkloop;
527 	struct kevent kev[KQ_NEVENTS];
528 	struct knote marker;
529 
530 	tsp = tsp_in;
531 	*res = 0;
532 
533 	lwkt_gettoken(&kq_token);
534 	for ( ;; ) {
535 		n = 0;
536 		error = kevent_copyinfn(uap, kev, KQ_NEVENTS, &n);
537 		if (error)
538 			goto done;
539 		if (n == 0)
540 			break;
541 		for (i = 0; i < n; i++) {
542 			kevp = &kev[i];
543 			kevp->flags &= ~EV_SYSFLAGS;
544 			error = kqueue_register(kq, kevp);
545 
546 			/*
547 			 * If a registration returns an error we
548 			 * immediately post the error.  The kevent()
549 			 * call itself will fail with the error if
550 			 * no space is available for posting.
551 			 *
552 			 * Such errors normally bypass the timeout/blocking
553 			 * code.  However, if the copyoutfn function refuses
554 			 * to post the error (see sys_poll()), then we
555 			 * ignore it too.
556 			 */
557 			if (error) {
558 				kevp->flags = EV_ERROR;
559 				kevp->data = error;
560 				lres = *res;
561 				kevent_copyoutfn(uap, kevp, 1, res);
562 				if (lres != *res) {
563 					nevents--;
564 					nerrors++;
565 				}
566 			}
567 		}
568 	}
569 	if (nerrors) {
570 		error = 0;
571 		goto done;
572 	}
573 
574 	/*
575 	 * Acquire/wait for events - setup timeout
576 	 */
577 	if (tsp != NULL) {
578 		struct timespec ats;
579 
580 		if (tsp->tv_sec || tsp->tv_nsec) {
581 			nanouptime(&ats);
582 			timespecadd(tsp, &ats);		/* tsp = target time */
583 		}
584 	}
585 
586 	/*
587 	 * Loop as required.
588 	 *
589 	 * Collect as many events as we can. Sleeping on successive
590 	 * loops is disabled if copyoutfn has incremented (*res).
591 	 *
592 	 * The loop stops if an error occurs, all events have been
593 	 * scanned (the marker has been reached), or fewer than the
594 	 * maximum number of events is found.
595 	 *
596 	 * The copyoutfn function does not have to increment (*res) in
597 	 * order for the loop to continue.
598 	 *
599 	 * NOTE: doselect() usually passes 0x7FFFFFFF for nevents.
600 	 */
601 	total = 0;
602 	error = 0;
603 	marker.kn_filter = EVFILT_MARKER;
604 	TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
605 	while ((n = nevents - total) > 0) {
606 		if (n > KQ_NEVENTS)
607 			n = KQ_NEVENTS;
608 
609 		/*
610 		 * If no events are pending sleep until timeout (if any)
611 		 * or an event occurs.
612 		 *
613 		 * After the sleep completes the marker is moved to the
614 		 * end of the list, making any received events available
615 		 * to our scan.
616 		 */
617 		if (kq->kq_count == 0 && *res == 0) {
618 			error = kqueue_sleep(kq, tsp);
619 			if (error)
620 				break;
621 
622 			TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
623 			TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
624 		}
625 
626 		/*
627 		 * Process all received events
628 		 * Account for all non-spurious events in our total
629 		 */
630 		i = kqueue_scan(kq, kev, n, &marker);
631 		if (i) {
632 			lres = *res;
633 			error = kevent_copyoutfn(uap, kev, i, res);
634 			total += *res - lres;
635 			if (error)
636 				break;
637 		}
638 		if (limit && --limit == 0)
639 			panic("kqueue: checkloop failed i=%d", i);
640 
641 		/*
642 		 * Normally when fewer events are returned than requested
643 		 * we can stop.  However, if only spurious events were
644 		 * collected the copyout will not bump (*res) and we have
645 		 * to continue.
646 		 */
647 		if (i < n && *res)
648 			break;
649 
650 		/*
651 		 * Deal with an edge case where spurious events can cause
652 		 * a loop to occur without moving the marker.  This can
653 		 * prevent kqueue_scan() from picking up new events which
654 		 * race us.  We must be sure to move the marker for this
655 		 * case.
656 		 *
657 		 * NOTE: We do not want to move the marker if events
658 		 *	 were scanned because normal kqueue operations
659 		 *	 may reactivate events.  Moving the marker in
660 		 *	 that case could result in duplicates for the
661 		 *	 same event.
662 		 */
663 		if (i == 0) {
664 			TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
665 			TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
666 		}
667 	}
668 	TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
669 
670 	/* Timeouts do not return EWOULDBLOCK. */
671 	if (error == EWOULDBLOCK)
672 		error = 0;
673 
674 done:
675 	lwkt_reltoken(&kq_token);
676 	return (error);
677 }
678 
679 /*
680  * MPALMOSTSAFE
681  */
682 int
683 sys_kevent(struct kevent_args *uap)
684 {
685 	struct thread *td = curthread;
686 	struct proc *p = td->td_proc;
687 	struct timespec ts, *tsp;
688 	struct kqueue *kq;
689 	struct file *fp = NULL;
690 	struct kevent_copyin_args *kap, ka;
691 	int error;
692 
693 	if (uap->timeout) {
694 		error = copyin(uap->timeout, &ts, sizeof(ts));
695 		if (error)
696 			return (error);
697 		tsp = &ts;
698 	} else {
699 		tsp = NULL;
700 	}
701 
702 	fp = holdfp(p->p_fd, uap->fd, -1);
703 	if (fp == NULL)
704 		return (EBADF);
705 	if (fp->f_type != DTYPE_KQUEUE) {
706 		fdrop(fp);
707 		return (EBADF);
708 	}
709 
710 	kq = (struct kqueue *)fp->f_data;
711 
712 	kap = &ka;
713 	kap->ka = uap;
714 	kap->pchanges = 0;
715 
716 	error = kern_kevent(kq, uap->nevents, &uap->sysmsg_result, kap,
717 			    kevent_copyin, kevent_copyout, tsp);
718 
719 	fdrop(fp);
720 
721 	return (error);
722 }
723 
724 int
725 kqueue_register(struct kqueue *kq, struct kevent *kev)
726 {
727 	struct filedesc *fdp = kq->kq_fdp;
728 	struct filterops *fops;
729 	struct file *fp = NULL;
730 	struct knote *kn = NULL;
731 	int error = 0;
732 
733 	if (kev->filter < 0) {
734 		if (kev->filter + EVFILT_SYSCOUNT < 0)
735 			return (EINVAL);
736 		fops = sysfilt_ops[~kev->filter];	/* to 0-base index */
737 	} else {
738 		/*
739 		 * XXX
740 		 * filter attach routine is responsible for insuring that
741 		 * the identifier can be attached to it.
742 		 */
743 		kprintf("unknown filter: %d\n", kev->filter);
744 		return (EINVAL);
745 	}
746 
747 	lwkt_gettoken(&kq_token);
748 	if (fops->f_flags & FILTEROP_ISFD) {
749 		/* validate descriptor */
750 		fp = holdfp(fdp, kev->ident, -1);
751 		if (fp == NULL) {
752 			lwkt_reltoken(&kq_token);
753 			return (EBADF);
754 		}
755 
756 		SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
757 			if (kn->kn_kq == kq &&
758 			    kn->kn_filter == kev->filter &&
759 			    kn->kn_id == kev->ident) {
760 				break;
761 			}
762 		}
763 	} else {
764 		if (kq->kq_knhashmask) {
765 			struct klist *list;
766 
767 			list = &kq->kq_knhash[
768 			    KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
769 			SLIST_FOREACH(kn, list, kn_link) {
770 				if (kn->kn_id == kev->ident &&
771 				    kn->kn_filter == kev->filter)
772 					break;
773 			}
774 		}
775 	}
776 
777 	if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
778 		error = ENOENT;
779 		goto done;
780 	}
781 
782 	/*
783 	 * kn now contains the matching knote, or NULL if no match
784 	 */
785 	if (kev->flags & EV_ADD) {
786 		if (kn == NULL) {
787 			kn = knote_alloc();
788 			if (kn == NULL) {
789 				error = ENOMEM;
790 				goto done;
791 			}
792 			kn->kn_fp = fp;
793 			kn->kn_kq = kq;
794 			kn->kn_fop = fops;
795 
796 			/*
797 			 * apply reference count to knote structure, and
798 			 * do not release it at the end of this routine.
799 			 */
800 			fp = NULL;
801 
802 			kn->kn_sfflags = kev->fflags;
803 			kn->kn_sdata = kev->data;
804 			kev->fflags = 0;
805 			kev->data = 0;
806 			kn->kn_kevent = *kev;
807 
808 			/*
809 			 * Interlock against creation/deletion races due
810 			 * to f_attach() blocking.  knote_attach() will set
811 			 * KN_CREATING.
812 			 */
813 			knote_attach(kn);
814 			if ((error = filter_attach(kn)) != 0) {
815 				kn->kn_status |= KN_DELETING;
816 				knote_drop(kn);
817 				goto done;
818 			}
819 			kn->kn_status &= ~KN_CREATING;
820 
821 			/*
822 			 * Interlock against close races which remove our
823 			 * knotes.  We do not want to end up with a knote
824 			 * on a closed descriptor.
825 			 */
826 			if ((fops->f_flags & FILTEROP_ISFD) &&
827 			    (error = checkfdclosed(fdp, kev->ident, kn->kn_fp)) != 0) {
828 				knote_detach_and_drop(kn);
829 				goto done;
830 			}
831 		} else {
832 			/*
833 			 * The user may change some filter values after the
834 			 * initial EV_ADD, but doing so will not reset any
835 			 * filter which have already been triggered.
836 			 */
837 			kn->kn_sfflags = kev->fflags;
838 			kn->kn_sdata = kev->data;
839 			kn->kn_kevent.udata = kev->udata;
840 		}
841 
842 		if (filter_event(kn, 0))
843 			KNOTE_ACTIVATE(kn);
844 	} else if (kev->flags & EV_DELETE) {
845 		knote_detach_and_drop(kn);
846 		goto done;
847 	}
848 
849 	if ((kev->flags & EV_DISABLE) &&
850 	    ((kn->kn_status & KN_DISABLED) == 0)) {
851 		kn->kn_status |= KN_DISABLED;
852 	}
853 
854 	if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
855 		kn->kn_status &= ~KN_DISABLED;
856 		if ((kn->kn_status & KN_ACTIVE) &&
857 		    ((kn->kn_status & KN_QUEUED) == 0))
858 			knote_enqueue(kn);
859 	}
860 
861 done:
862 	lwkt_reltoken(&kq_token);
863 	if (fp != NULL)
864 		fdrop(fp);
865 	return (error);
866 }
867 
868 /*
869  * Block as necessary until the target time is reached.
870  * If tsp is NULL we block indefinitely.  If tsp->ts_secs/nsecs are both
871  * 0 we do not block at all.
872  */
873 static int
874 kqueue_sleep(struct kqueue *kq, struct timespec *tsp)
875 {
876 	int error = 0;
877 
878 	if (tsp == NULL) {
879 		kq->kq_state |= KQ_SLEEP;
880 		error = tsleep(kq, PCATCH, "kqread", 0);
881 	} else if (tsp->tv_sec == 0 && tsp->tv_nsec == 0) {
882 		error = EWOULDBLOCK;
883 	} else {
884 		struct timespec ats;
885 		struct timespec atx = *tsp;
886 		int timeout;
887 
888 		nanouptime(&ats);
889 		timespecsub(&atx, &ats);
890 		if (ats.tv_sec < 0) {
891 			error = EWOULDBLOCK;
892 		} else {
893 			timeout = atx.tv_sec > 24 * 60 * 60 ?
894 				24 * 60 * 60 * hz : tstohz_high(&atx);
895 			kq->kq_state |= KQ_SLEEP;
896 			error = tsleep(kq, PCATCH, "kqread", timeout);
897 		}
898 	}
899 
900 	/* don't restart after signals... */
901 	if (error == ERESTART)
902 		return (EINTR);
903 
904 	return (error);
905 }
906 
907 /*
908  * Scan the kqueue, return the number of active events placed in kevp up
909  * to count.
910  *
911  * Continuous mode events may get recycled, do not continue scanning past
912  * marker unless no events have been collected.
913  */
914 static int
915 kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
916             struct knote *marker)
917 {
918         struct knote *kn, local_marker;
919         int total;
920 
921         total = 0;
922 	local_marker.kn_filter = EVFILT_MARKER;
923 
924 	/*
925 	 * Collect events.
926 	 */
927 	TAILQ_INSERT_HEAD(&kq->kq_knpend, &local_marker, kn_tqe);
928 	while (count) {
929 		kn = TAILQ_NEXT(&local_marker, kn_tqe);
930 		if (kn->kn_filter == EVFILT_MARKER) {
931 			/* Marker reached, we are done */
932 			if (kn == marker)
933 				break;
934 
935 			/* Move local marker past some other threads marker */
936 			kn = TAILQ_NEXT(kn, kn_tqe);
937 			TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
938 			TAILQ_INSERT_BEFORE(kn, &local_marker, kn_tqe);
939 			continue;
940 		}
941 
942 		/*
943 		 * Remove the event for processing.
944 		 *
945 		 * WARNING!  We must leave KN_QUEUED set to prevent the
946 		 *	     event from being KNOTE()d again while we
947 		 *	     potentially block in the filter function.
948 		 *
949 		 *	     This protects the knote from everything except
950 		 *	     getting dropped.
951 		 *
952 		 * WARNING!  KN_PROCESSING is meant to handle any cases
953 		 *	     that leaving KN_QUEUED set does not.
954 		 */
955 		TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
956 		kq->kq_count--;
957 		kn->kn_status |= KN_PROCESSING;
958 
959 		/*
960 		 * Even though close/dup2 will clean out pending knotes this
961 		 * code is MPSAFE and it is possible to race a close inbetween
962 		 * the removal of its descriptor and the clearing out of the
963 		 * knote(s).
964 		 *
965 		 * In this case we must ensure that the knote is not queued
966 		 * to knpend or we risk an infinite kernel loop calling
967 		 * kscan, because the select/poll code will not be able to
968 		 * delete the event.
969 		 */
970 		if ((kn->kn_fop->f_flags & FILTEROP_ISFD) &&
971 		    checkfdclosed(kq->kq_fdp, kn->kn_kevent.ident, kn->kn_fp)) {
972 			kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE |
973 					   KN_PROCESSING);
974 			continue;
975 		}
976 
977 		/*
978 		 * If disabled we ensure the event is not queued but leave
979 		 * its active bit set.  On re-enablement the event may be
980 		 * immediately triggered.
981 		 */
982 		if (kn->kn_status & KN_DISABLED) {
983 			kn->kn_status &= ~(KN_QUEUED | KN_PROCESSING);
984 			continue;
985 		}
986 
987 		/*
988 		 * If not running in one-shot mode and the event is no
989 		 * longer present we ensure it is removed from the queue and
990 		 * ignore it.
991 		 */
992 		if ((kn->kn_flags & EV_ONESHOT) == 0 &&
993 		    filter_event(kn, 0) == 0) {
994 			kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE |
995 					   KN_PROCESSING);
996 			continue;
997 		}
998 
999 		*kevp++ = kn->kn_kevent;
1000 		++total;
1001 		--count;
1002 
1003 		/*
1004 		 * Post-event action on the note
1005 		 */
1006 		if (kn->kn_flags & EV_ONESHOT) {
1007 			kn->kn_status &= ~(KN_QUEUED | KN_PROCESSING);
1008 			knote_detach_and_drop(kn);
1009 		} else if (kn->kn_flags & EV_CLEAR) {
1010 			kn->kn_data = 0;
1011 			kn->kn_fflags = 0;
1012 			kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE |
1013 					   KN_PROCESSING);
1014 		} else {
1015 			TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1016 			kq->kq_count++;
1017 			kn->kn_status &= ~KN_PROCESSING;
1018 		}
1019 	}
1020 	TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
1021 
1022 	return (total);
1023 }
1024 
1025 /*
1026  * XXX
1027  * This could be expanded to call kqueue_scan, if desired.
1028  *
1029  * MPSAFE
1030  */
1031 static int
1032 kqueue_read(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1033 {
1034 	return (ENXIO);
1035 }
1036 
1037 /*
1038  * MPSAFE
1039  */
1040 static int
1041 kqueue_write(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1042 {
1043 	return (ENXIO);
1044 }
1045 
1046 /*
1047  * MPALMOSTSAFE
1048  */
1049 static int
1050 kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
1051 	     struct ucred *cred, struct sysmsg *msg)
1052 {
1053 	struct kqueue *kq;
1054 	int error;
1055 
1056 	lwkt_gettoken(&kq_token);
1057 	kq = (struct kqueue *)fp->f_data;
1058 
1059 	switch(com) {
1060 	case FIOASYNC:
1061 		if (*(int *)data)
1062 			kq->kq_state |= KQ_ASYNC;
1063 		else
1064 			kq->kq_state &= ~KQ_ASYNC;
1065 		error = 0;
1066 		break;
1067 	case FIOSETOWN:
1068 		error = fsetown(*(int *)data, &kq->kq_sigio);
1069 		break;
1070 	default:
1071 		error = ENOTTY;
1072 		break;
1073 	}
1074 	lwkt_reltoken(&kq_token);
1075 	return (error);
1076 }
1077 
1078 /*
1079  * MPSAFE
1080  */
1081 static int
1082 kqueue_stat(struct file *fp, struct stat *st, struct ucred *cred)
1083 {
1084 	struct kqueue *kq = (struct kqueue *)fp->f_data;
1085 
1086 	bzero((void *)st, sizeof(*st));
1087 	st->st_size = kq->kq_count;
1088 	st->st_blksize = sizeof(struct kevent);
1089 	st->st_mode = S_IFIFO;
1090 	return (0);
1091 }
1092 
1093 /*
1094  * MPSAFE
1095  */
1096 static int
1097 kqueue_close(struct file *fp)
1098 {
1099 	struct kqueue *kq = (struct kqueue *)fp->f_data;
1100 
1101 	kqueue_terminate(kq);
1102 
1103 	fp->f_data = NULL;
1104 	funsetown(kq->kq_sigio);
1105 
1106 	kfree(kq, M_KQUEUE);
1107 	return (0);
1108 }
1109 
1110 static void
1111 kqueue_wakeup(struct kqueue *kq)
1112 {
1113 	if (kq->kq_state & KQ_SLEEP) {
1114 		kq->kq_state &= ~KQ_SLEEP;
1115 		wakeup(kq);
1116 	}
1117 	KNOTE(&kq->kq_kqinfo.ki_note, 0);
1118 }
1119 
1120 /*
1121  * Calls filterops f_attach function, acquiring mplock if filter is not
1122  * marked as FILTEROP_MPSAFE.
1123  */
1124 static int
1125 filter_attach(struct knote *kn)
1126 {
1127 	int ret;
1128 
1129 	if (!(kn->kn_fop->f_flags & FILTEROP_MPSAFE)) {
1130 		get_mplock();
1131 		ret = kn->kn_fop->f_attach(kn);
1132 		rel_mplock();
1133 	} else {
1134 		ret = kn->kn_fop->f_attach(kn);
1135 	}
1136 
1137 	return (ret);
1138 }
1139 
1140 /*
1141  * Detach the knote and drop it, destroying the knote.
1142  *
1143  * Calls filterops f_detach function, acquiring mplock if filter is not
1144  * marked as FILTEROP_MPSAFE.
1145  *
1146  * This can race due to the MP lock and/or locks acquired by f_detach,
1147  * so we interlock with KN_DELETING.  It is also possible to race
1148  * a create for the same reason if userland tries to delete the knote
1149  * before the create is complete.
1150  */
1151 static void
1152 knote_detach_and_drop(struct knote *kn)
1153 {
1154 	if (kn->kn_status & (KN_CREATING | KN_DELETING))
1155 		return;
1156 	kn->kn_status |= KN_DELETING;
1157 
1158 	if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1159 		kn->kn_fop->f_detach(kn);
1160 	} else {
1161 		get_mplock();
1162 		kn->kn_fop->f_detach(kn);
1163 		rel_mplock();
1164 	}
1165 	knote_drop(kn);
1166 }
1167 
1168 /*
1169  * Calls filterops f_event function, acquiring mplock if filter is not
1170  * marked as FILTEROP_MPSAFE.
1171  *
1172  * If the knote is in the middle of being created or deleted we cannot
1173  * safely call the filter op.
1174  */
1175 static int
1176 filter_event(struct knote *kn, long hint)
1177 {
1178 	int ret;
1179 
1180 	if (kn->kn_status & (KN_CREATING | KN_DELETING))
1181 		return(0);
1182 
1183 	if (!(kn->kn_fop->f_flags & FILTEROP_MPSAFE)) {
1184 		get_mplock();
1185 		ret = kn->kn_fop->f_event(kn, hint);
1186 		rel_mplock();
1187 	} else {
1188 		ret = kn->kn_fop->f_event(kn, hint);
1189 	}
1190 
1191 	return (ret);
1192 }
1193 
1194 /*
1195  * walk down a list of knotes, activating them if their event has triggered.
1196  */
1197 void
1198 knote(struct klist *list, long hint)
1199 {
1200 	struct knote *kn;
1201 
1202 	lwkt_gettoken(&kq_token);
1203 	SLIST_FOREACH(kn, list, kn_next) {
1204 		if (filter_event(kn, hint))
1205 			KNOTE_ACTIVATE(kn);
1206 	}
1207 	lwkt_reltoken(&kq_token);
1208 }
1209 
1210 /*
1211  * insert knote at head of klist
1212  *
1213  * Requires: kq_token
1214  */
1215 void
1216 knote_insert(struct klist *klist, struct knote *kn)
1217 {
1218 	lwkt_gettoken(&kq_token);
1219 	SLIST_INSERT_HEAD(klist, kn, kn_next);
1220 	lwkt_reltoken(&kq_token);
1221 }
1222 
1223 /*
1224  * remove knote from a klist
1225  *
1226  * Requires: kq_token
1227  */
1228 void
1229 knote_remove(struct klist *klist, struct knote *kn)
1230 {
1231 	lwkt_gettoken(&kq_token);
1232 	SLIST_REMOVE(klist, kn, knote, kn_next);
1233 	lwkt_reltoken(&kq_token);
1234 }
1235 
1236 /*
1237  * remove all knotes from a specified klist
1238  */
1239 void
1240 knote_empty(struct klist *list)
1241 {
1242 	struct knote *kn;
1243 
1244 	lwkt_gettoken(&kq_token);
1245 	while ((kn = SLIST_FIRST(list)) != NULL)
1246 		knote_detach_and_drop(kn);
1247 	lwkt_reltoken(&kq_token);
1248 }
1249 
1250 /*
1251  * remove all knotes referencing a specified fd
1252  */
1253 void
1254 knote_fdclose(struct file *fp, struct filedesc *fdp, int fd)
1255 {
1256 	struct knote *kn;
1257 
1258 	lwkt_gettoken(&kq_token);
1259 restart:
1260 	SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
1261 		if (kn->kn_kq->kq_fdp == fdp && kn->kn_id == fd) {
1262 			knote_detach_and_drop(kn);
1263 			goto restart;
1264 		}
1265 	}
1266 	lwkt_reltoken(&kq_token);
1267 }
1268 
1269 static void
1270 knote_attach(struct knote *kn)
1271 {
1272 	struct klist *list;
1273 	struct kqueue *kq = kn->kn_kq;
1274 
1275 	if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1276 		KKASSERT(kn->kn_fp);
1277 		list = &kn->kn_fp->f_klist;
1278 	} else {
1279 		if (kq->kq_knhashmask == 0)
1280 			kq->kq_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1281 						 &kq->kq_knhashmask);
1282 		list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1283 	}
1284 	SLIST_INSERT_HEAD(list, kn, kn_link);
1285 	TAILQ_INSERT_HEAD(&kq->kq_knlist, kn, kn_kqlink);
1286 	kn->kn_status = KN_CREATING;
1287 }
1288 
1289 static void
1290 knote_drop(struct knote *kn)
1291 {
1292 	struct kqueue *kq;
1293 	struct klist *list;
1294 
1295 	kq = kn->kn_kq;
1296 
1297 	if (kn->kn_fop->f_flags & FILTEROP_ISFD)
1298 		list = &kn->kn_fp->f_klist;
1299 	else
1300 		list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1301 
1302 	SLIST_REMOVE(list, kn, knote, kn_link);
1303 	TAILQ_REMOVE(&kq->kq_knlist, kn, kn_kqlink);
1304 	if (kn->kn_status & KN_QUEUED)
1305 		knote_dequeue(kn);
1306 	if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1307 		fdrop(kn->kn_fp);
1308 		kn->kn_fp = NULL;
1309 	}
1310 	knote_free(kn);
1311 }
1312 
1313 static void
1314 knote_enqueue(struct knote *kn)
1315 {
1316 	struct kqueue *kq = kn->kn_kq;
1317 
1318 	KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
1319 
1320 	TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1321 	kn->kn_status |= KN_QUEUED;
1322 	++kq->kq_count;
1323 
1324 	/*
1325 	 * Send SIGIO on request (typically set up as a mailbox signal)
1326 	 */
1327 	if (kq->kq_sigio && (kq->kq_state & KQ_ASYNC) && kq->kq_count == 1)
1328 		pgsigio(kq->kq_sigio, SIGIO, 0);
1329 
1330 	kqueue_wakeup(kq);
1331 }
1332 
1333 static void
1334 knote_dequeue(struct knote *kn)
1335 {
1336 	struct kqueue *kq = kn->kn_kq;
1337 
1338 	KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
1339 	KKASSERT((kn->kn_status & KN_PROCESSING) == 0);
1340 
1341 	TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
1342 	kn->kn_status &= ~KN_QUEUED;
1343 	kq->kq_count--;
1344 }
1345 
1346 static void
1347 knote_init(void)
1348 {
1349 	knote_zone = zinit("KNOTE", sizeof(struct knote), 0, 0, 1);
1350 }
1351 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL)
1352 
1353 static struct knote *
1354 knote_alloc(void)
1355 {
1356 	return ((struct knote *)zalloc(knote_zone));
1357 }
1358 
1359 static void
1360 knote_free(struct knote *kn)
1361 {
1362 	zfree(knote_zone, kn);
1363 }
1364