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