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