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