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