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