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