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