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