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