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