]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/kern/kern_event.c
Copy head (r256279) to stable/10 as part of the 10.0-RELEASE cycle.
[FreeBSD/stable/10.git] / sys / kern / kern_event.c
1 /*-
2  * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon@FreeBSD.org>
3  * Copyright 2004 John-Mark Gurney <jmg@FreeBSD.org>
4  * Copyright (c) 2009 Apple, Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31
32 #include "opt_ktrace.h"
33
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/capability.h>
37 #include <sys/kernel.h>
38 #include <sys/lock.h>
39 #include <sys/mutex.h>
40 #include <sys/rwlock.h>
41 #include <sys/proc.h>
42 #include <sys/malloc.h>
43 #include <sys/unistd.h>
44 #include <sys/file.h>
45 #include <sys/filedesc.h>
46 #include <sys/filio.h>
47 #include <sys/fcntl.h>
48 #include <sys/kthread.h>
49 #include <sys/selinfo.h>
50 #include <sys/stdatomic.h>
51 #include <sys/queue.h>
52 #include <sys/event.h>
53 #include <sys/eventvar.h>
54 #include <sys/poll.h>
55 #include <sys/protosw.h>
56 #include <sys/sigio.h>
57 #include <sys/signalvar.h>
58 #include <sys/socket.h>
59 #include <sys/socketvar.h>
60 #include <sys/stat.h>
61 #include <sys/sysctl.h>
62 #include <sys/sysproto.h>
63 #include <sys/syscallsubr.h>
64 #include <sys/taskqueue.h>
65 #include <sys/uio.h>
66 #ifdef KTRACE
67 #include <sys/ktrace.h>
68 #endif
69
70 #include <vm/uma.h>
71
72 static MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
73
74 /*
75  * This lock is used if multiple kq locks are required.  This possibly
76  * should be made into a per proc lock.
77  */
78 static struct mtx       kq_global;
79 MTX_SYSINIT(kq_global, &kq_global, "kqueue order", MTX_DEF);
80 #define KQ_GLOBAL_LOCK(lck, haslck)     do {    \
81         if (!haslck)                            \
82                 mtx_lock(lck);                  \
83         haslck = 1;                             \
84 } while (0)
85 #define KQ_GLOBAL_UNLOCK(lck, haslck)   do {    \
86         if (haslck)                             \
87                 mtx_unlock(lck);                        \
88         haslck = 0;                             \
89 } while (0)
90
91 TASKQUEUE_DEFINE_THREAD(kqueue);
92
93 static int      kevent_copyout(void *arg, struct kevent *kevp, int count);
94 static int      kevent_copyin(void *arg, struct kevent *kevp, int count);
95 static int      kqueue_register(struct kqueue *kq, struct kevent *kev,
96                     struct thread *td, int waitok);
97 static int      kqueue_acquire(struct file *fp, struct kqueue **kqp);
98 static void     kqueue_release(struct kqueue *kq, int locked);
99 static int      kqueue_expand(struct kqueue *kq, struct filterops *fops,
100                     uintptr_t ident, int waitok);
101 static void     kqueue_task(void *arg, int pending);
102 static int      kqueue_scan(struct kqueue *kq, int maxevents,
103                     struct kevent_copyops *k_ops,
104                     const struct timespec *timeout,
105                     struct kevent *keva, struct thread *td);
106 static void     kqueue_wakeup(struct kqueue *kq);
107 static struct filterops *kqueue_fo_find(int filt);
108 static void     kqueue_fo_release(int filt);
109
110 static fo_rdwr_t        kqueue_read;
111 static fo_rdwr_t        kqueue_write;
112 static fo_truncate_t    kqueue_truncate;
113 static fo_ioctl_t       kqueue_ioctl;
114 static fo_poll_t        kqueue_poll;
115 static fo_kqfilter_t    kqueue_kqfilter;
116 static fo_stat_t        kqueue_stat;
117 static fo_close_t       kqueue_close;
118
119 static struct fileops kqueueops = {
120         .fo_read = kqueue_read,
121         .fo_write = kqueue_write,
122         .fo_truncate = kqueue_truncate,
123         .fo_ioctl = kqueue_ioctl,
124         .fo_poll = kqueue_poll,
125         .fo_kqfilter = kqueue_kqfilter,
126         .fo_stat = kqueue_stat,
127         .fo_close = kqueue_close,
128         .fo_chmod = invfo_chmod,
129         .fo_chown = invfo_chown,
130         .fo_sendfile = invfo_sendfile,
131 };
132
133 static int      knote_attach(struct knote *kn, struct kqueue *kq);
134 static void     knote_drop(struct knote *kn, struct thread *td);
135 static void     knote_enqueue(struct knote *kn);
136 static void     knote_dequeue(struct knote *kn);
137 static void     knote_init(void);
138 static struct   knote *knote_alloc(int waitok);
139 static void     knote_free(struct knote *kn);
140
141 static void     filt_kqdetach(struct knote *kn);
142 static int      filt_kqueue(struct knote *kn, long hint);
143 static int      filt_procattach(struct knote *kn);
144 static void     filt_procdetach(struct knote *kn);
145 static int      filt_proc(struct knote *kn, long hint);
146 static int      filt_fileattach(struct knote *kn);
147 static void     filt_timerexpire(void *knx);
148 static int      filt_timerattach(struct knote *kn);
149 static void     filt_timerdetach(struct knote *kn);
150 static int      filt_timer(struct knote *kn, long hint);
151 static int      filt_userattach(struct knote *kn);
152 static void     filt_userdetach(struct knote *kn);
153 static int      filt_user(struct knote *kn, long hint);
154 static void     filt_usertouch(struct knote *kn, struct kevent *kev,
155                     u_long type);
156
157 static struct filterops file_filtops = {
158         .f_isfd = 1,
159         .f_attach = filt_fileattach,
160 };
161 static struct filterops kqread_filtops = {
162         .f_isfd = 1,
163         .f_detach = filt_kqdetach,
164         .f_event = filt_kqueue,
165 };
166 /* XXX - move to kern_proc.c?  */
167 static struct filterops proc_filtops = {
168         .f_isfd = 0,
169         .f_attach = filt_procattach,
170         .f_detach = filt_procdetach,
171         .f_event = filt_proc,
172 };
173 static struct filterops timer_filtops = {
174         .f_isfd = 0,
175         .f_attach = filt_timerattach,
176         .f_detach = filt_timerdetach,
177         .f_event = filt_timer,
178 };
179 static struct filterops user_filtops = {
180         .f_attach = filt_userattach,
181         .f_detach = filt_userdetach,
182         .f_event = filt_user,
183         .f_touch = filt_usertouch,
184 };
185
186 static uma_zone_t       knote_zone;
187 static atomic_uint      kq_ncallouts = ATOMIC_VAR_INIT(0);
188 static unsigned int     kq_calloutmax = 4 * 1024;
189 SYSCTL_UINT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
190     &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
191
192 /* XXX - ensure not KN_INFLUX?? */
193 #define KNOTE_ACTIVATE(kn, islock) do {                                 \
194         if ((islock))                                                   \
195                 mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED);            \
196         else                                                            \
197                 KQ_LOCK((kn)->kn_kq);                                   \
198         (kn)->kn_status |= KN_ACTIVE;                                   \
199         if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0)         \
200                 knote_enqueue((kn));                                    \
201         if (!(islock))                                                  \
202                 KQ_UNLOCK((kn)->kn_kq);                                 \
203 } while(0)
204 #define KQ_LOCK(kq) do {                                                \
205         mtx_lock(&(kq)->kq_lock);                                       \
206 } while (0)
207 #define KQ_FLUX_WAKEUP(kq) do {                                         \
208         if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) {            \
209                 (kq)->kq_state &= ~KQ_FLUXWAIT;                         \
210                 wakeup((kq));                                           \
211         }                                                               \
212 } while (0)
213 #define KQ_UNLOCK_FLUX(kq) do {                                         \
214         KQ_FLUX_WAKEUP(kq);                                             \
215         mtx_unlock(&(kq)->kq_lock);                                     \
216 } while (0)
217 #define KQ_UNLOCK(kq) do {                                              \
218         mtx_unlock(&(kq)->kq_lock);                                     \
219 } while (0)
220 #define KQ_OWNED(kq) do {                                               \
221         mtx_assert(&(kq)->kq_lock, MA_OWNED);                           \
222 } while (0)
223 #define KQ_NOTOWNED(kq) do {                                            \
224         mtx_assert(&(kq)->kq_lock, MA_NOTOWNED);                        \
225 } while (0)
226 #define KN_LIST_LOCK(kn) do {                                           \
227         if (kn->kn_knlist != NULL)                                      \
228                 kn->kn_knlist->kl_lock(kn->kn_knlist->kl_lockarg);      \
229 } while (0)
230 #define KN_LIST_UNLOCK(kn) do {                                         \
231         if (kn->kn_knlist != NULL)                                      \
232                 kn->kn_knlist->kl_unlock(kn->kn_knlist->kl_lockarg);    \
233 } while (0)
234 #define KNL_ASSERT_LOCK(knl, islocked) do {                             \
235         if (islocked)                                                   \
236                 KNL_ASSERT_LOCKED(knl);                         \
237         else                                                            \
238                 KNL_ASSERT_UNLOCKED(knl);                               \
239 } while (0)
240 #ifdef INVARIANTS
241 #define KNL_ASSERT_LOCKED(knl) do {                                     \
242         knl->kl_assert_locked((knl)->kl_lockarg);                       \
243 } while (0)
244 #define KNL_ASSERT_UNLOCKED(knl) do {                                   \
245         knl->kl_assert_unlocked((knl)->kl_lockarg);                     \
246 } while (0)
247 #else /* !INVARIANTS */
248 #define KNL_ASSERT_LOCKED(knl) do {} while(0)
249 #define KNL_ASSERT_UNLOCKED(knl) do {} while (0)
250 #endif /* INVARIANTS */
251
252 #define KN_HASHSIZE             64              /* XXX should be tunable */
253 #define KN_HASH(val, mask)      (((val) ^ (val >> 8)) & (mask))
254
255 static int
256 filt_nullattach(struct knote *kn)
257 {
258
259         return (ENXIO);
260 };
261
262 struct filterops null_filtops = {
263         .f_isfd = 0,
264         .f_attach = filt_nullattach,
265 };
266
267 /* XXX - make SYSINIT to add these, and move into respective modules. */
268 extern struct filterops sig_filtops;
269 extern struct filterops fs_filtops;
270
271 /*
272  * Table for for all system-defined filters.
273  */
274 static struct mtx       filterops_lock;
275 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops",
276         MTX_DEF);
277 static struct {
278         struct filterops *for_fop;
279         int for_refcnt;
280 } sysfilt_ops[EVFILT_SYSCOUNT] = {
281         { &file_filtops },                      /* EVFILT_READ */
282         { &file_filtops },                      /* EVFILT_WRITE */
283         { &null_filtops },                      /* EVFILT_AIO */
284         { &file_filtops },                      /* EVFILT_VNODE */
285         { &proc_filtops },                      /* EVFILT_PROC */
286         { &sig_filtops },                       /* EVFILT_SIGNAL */
287         { &timer_filtops },                     /* EVFILT_TIMER */
288         { &null_filtops },                      /* former EVFILT_NETDEV */
289         { &fs_filtops },                        /* EVFILT_FS */
290         { &null_filtops },                      /* EVFILT_LIO */
291         { &user_filtops },                      /* EVFILT_USER */
292 };
293
294 /*
295  * Simple redirection for all cdevsw style objects to call their fo_kqfilter
296  * method.
297  */
298 static int
299 filt_fileattach(struct knote *kn)
300 {
301
302         return (fo_kqfilter(kn->kn_fp, kn));
303 }
304
305 /*ARGSUSED*/
306 static int
307 kqueue_kqfilter(struct file *fp, struct knote *kn)
308 {
309         struct kqueue *kq = kn->kn_fp->f_data;
310
311         if (kn->kn_filter != EVFILT_READ)
312                 return (EINVAL);
313
314         kn->kn_status |= KN_KQUEUE;
315         kn->kn_fop = &kqread_filtops;
316         knlist_add(&kq->kq_sel.si_note, kn, 0);
317
318         return (0);
319 }
320
321 static void
322 filt_kqdetach(struct knote *kn)
323 {
324         struct kqueue *kq = kn->kn_fp->f_data;
325
326         knlist_remove(&kq->kq_sel.si_note, kn, 0);
327 }
328
329 /*ARGSUSED*/
330 static int
331 filt_kqueue(struct knote *kn, long hint)
332 {
333         struct kqueue *kq = kn->kn_fp->f_data;
334
335         kn->kn_data = kq->kq_count;
336         return (kn->kn_data > 0);
337 }
338
339 /* XXX - move to kern_proc.c?  */
340 static int
341 filt_procattach(struct knote *kn)
342 {
343         struct proc *p;
344         int immediate;
345         int error;
346
347         immediate = 0;
348         p = pfind(kn->kn_id);
349         if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
350                 p = zpfind(kn->kn_id);
351                 immediate = 1;
352         } else if (p != NULL && (p->p_flag & P_WEXIT)) {
353                 immediate = 1;
354         }
355
356         if (p == NULL)
357                 return (ESRCH);
358         if ((error = p_cansee(curthread, p))) {
359                 PROC_UNLOCK(p);
360                 return (error);
361         }
362
363         kn->kn_ptr.p_proc = p;
364         kn->kn_flags |= EV_CLEAR;               /* automatically set */
365
366         /*
367          * internal flag indicating registration done by kernel
368          */
369         if (kn->kn_flags & EV_FLAG1) {
370                 kn->kn_data = kn->kn_sdata;             /* ppid */
371                 kn->kn_fflags = NOTE_CHILD;
372                 kn->kn_flags &= ~EV_FLAG1;
373         }
374
375         if (immediate == 0)
376                 knlist_add(&p->p_klist, kn, 1);
377
378         /*
379          * Immediately activate any exit notes if the target process is a
380          * zombie.  This is necessary to handle the case where the target
381          * process, e.g. a child, dies before the kevent is registered.
382          */
383         if (immediate && filt_proc(kn, NOTE_EXIT))
384                 KNOTE_ACTIVATE(kn, 0);
385
386         PROC_UNLOCK(p);
387
388         return (0);
389 }
390
391 /*
392  * The knote may be attached to a different process, which may exit,
393  * leaving nothing for the knote to be attached to.  So when the process
394  * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
395  * it will be deleted when read out.  However, as part of the knote deletion,
396  * this routine is called, so a check is needed to avoid actually performing
397  * a detach, because the original process does not exist any more.
398  */
399 /* XXX - move to kern_proc.c?  */
400 static void
401 filt_procdetach(struct knote *kn)
402 {
403         struct proc *p;
404
405         p = kn->kn_ptr.p_proc;
406         knlist_remove(&p->p_klist, kn, 0);
407         kn->kn_ptr.p_proc = NULL;
408 }
409
410 /* XXX - move to kern_proc.c?  */
411 static int
412 filt_proc(struct knote *kn, long hint)
413 {
414         struct proc *p = kn->kn_ptr.p_proc;
415         u_int event;
416
417         /*
418          * mask off extra data
419          */
420         event = (u_int)hint & NOTE_PCTRLMASK;
421
422         /*
423          * if the user is interested in this event, record it.
424          */
425         if (kn->kn_sfflags & event)
426                 kn->kn_fflags |= event;
427
428         /*
429          * process is gone, so flag the event as finished.
430          */
431         if (event == NOTE_EXIT) {
432                 if (!(kn->kn_status & KN_DETACHED))
433                         knlist_remove_inevent(&p->p_klist, kn);
434                 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
435                 kn->kn_ptr.p_proc = NULL;
436                 if (kn->kn_fflags & NOTE_EXIT)
437                         kn->kn_data = p->p_xstat;
438                 if (kn->kn_fflags == 0)
439                         kn->kn_flags |= EV_DROP;
440                 return (1);
441         }
442
443         return (kn->kn_fflags != 0);
444 }
445
446 /*
447  * Called when the process forked. It mostly does the same as the
448  * knote(), activating all knotes registered to be activated when the
449  * process forked. Additionally, for each knote attached to the
450  * parent, check whether user wants to track the new process. If so
451  * attach a new knote to it, and immediately report an event with the
452  * child's pid.
453  */
454 void
455 knote_fork(struct knlist *list, int pid)
456 {
457         struct kqueue *kq;
458         struct knote *kn;
459         struct kevent kev;
460         int error;
461
462         if (list == NULL)
463                 return;
464         list->kl_lock(list->kl_lockarg);
465
466         SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
467                 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX)
468                         continue;
469                 kq = kn->kn_kq;
470                 KQ_LOCK(kq);
471                 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
472                         KQ_UNLOCK(kq);
473                         continue;
474                 }
475
476                 /*
477                  * The same as knote(), activate the event.
478                  */
479                 if ((kn->kn_sfflags & NOTE_TRACK) == 0) {
480                         kn->kn_status |= KN_HASKQLOCK;
481                         if (kn->kn_fop->f_event(kn, NOTE_FORK))
482                                 KNOTE_ACTIVATE(kn, 1);
483                         kn->kn_status &= ~KN_HASKQLOCK;
484                         KQ_UNLOCK(kq);
485                         continue;
486                 }
487
488                 /*
489                  * The NOTE_TRACK case. In addition to the activation
490                  * of the event, we need to register new event to
491                  * track the child. Drop the locks in preparation for
492                  * the call to kqueue_register().
493                  */
494                 kn->kn_status |= KN_INFLUX;
495                 KQ_UNLOCK(kq);
496                 list->kl_unlock(list->kl_lockarg);
497
498                 /*
499                  * Activate existing knote and register a knote with
500                  * new process.
501                  */
502                 kev.ident = pid;
503                 kev.filter = kn->kn_filter;
504                 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
505                 kev.fflags = kn->kn_sfflags;
506                 kev.data = kn->kn_id;           /* parent */
507                 kev.udata = kn->kn_kevent.udata;/* preserve udata */
508                 error = kqueue_register(kq, &kev, NULL, 0);
509                 if (error)
510                         kn->kn_fflags |= NOTE_TRACKERR;
511                 if (kn->kn_fop->f_event(kn, NOTE_FORK))
512                         KNOTE_ACTIVATE(kn, 0);
513                 KQ_LOCK(kq);
514                 kn->kn_status &= ~KN_INFLUX;
515                 KQ_UNLOCK_FLUX(kq);
516                 list->kl_lock(list->kl_lockarg);
517         }
518         list->kl_unlock(list->kl_lockarg);
519 }
520
521 /*
522  * XXX: EVFILT_TIMER should perhaps live in kern_time.c beside the
523  * interval timer support code.
524  */
525 static __inline sbintime_t 
526 timer2sbintime(intptr_t data)
527 {
528
529         return (SBT_1MS * data);
530 }
531
532 static void
533 filt_timerexpire(void *knx)
534 {
535         struct callout *calloutp;
536         struct knote *kn;
537
538         kn = knx;
539         kn->kn_data++;
540         KNOTE_ACTIVATE(kn, 0);  /* XXX - handle locking */
541
542         if ((kn->kn_flags & EV_ONESHOT) != EV_ONESHOT) {
543                 calloutp = (struct callout *)kn->kn_hook;
544                 callout_reset_sbt_on(calloutp,
545                     timer2sbintime(kn->kn_sdata), 0 /* 1ms? */,
546                     filt_timerexpire, kn, PCPU_GET(cpuid), 0);
547         }
548 }
549
550 /*
551  * data contains amount of time to sleep, in milliseconds
552  */
553 static int
554 filt_timerattach(struct knote *kn)
555 {
556         struct callout *calloutp;
557         sbintime_t to;
558         unsigned int ncallouts;
559
560         if ((intptr_t)kn->kn_sdata < 0)
561                 return (EINVAL);
562         if ((intptr_t)kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
563                 kn->kn_sdata = 1;
564         to = timer2sbintime(kn->kn_sdata);
565         if (to < 0)
566                 return (EINVAL);
567
568         ncallouts = atomic_load_explicit(&kq_ncallouts, memory_order_relaxed);
569         do {
570                 if (ncallouts >= kq_calloutmax)
571                         return (ENOMEM);
572         } while (!atomic_compare_exchange_weak_explicit(&kq_ncallouts,
573             &ncallouts, ncallouts + 1, memory_order_relaxed,
574             memory_order_relaxed));
575
576         kn->kn_flags |= EV_CLEAR;               /* automatically set */
577         kn->kn_status &= ~KN_DETACHED;          /* knlist_add clears it */
578         calloutp = malloc(sizeof(*calloutp), M_KQUEUE, M_WAITOK);
579         callout_init(calloutp, CALLOUT_MPSAFE);
580         kn->kn_hook = calloutp;
581         callout_reset_sbt_on(calloutp, to, 0 /* 1ms? */,
582             filt_timerexpire, kn, PCPU_GET(cpuid), 0);
583
584         return (0);
585 }
586
587 static void
588 filt_timerdetach(struct knote *kn)
589 {
590         struct callout *calloutp;
591         unsigned int old;
592
593         calloutp = (struct callout *)kn->kn_hook;
594         callout_drain(calloutp);
595         free(calloutp, M_KQUEUE);
596         old = atomic_fetch_sub_explicit(&kq_ncallouts, 1, memory_order_relaxed);
597         KASSERT(old > 0, ("Number of callouts cannot become negative"));
598         kn->kn_status |= KN_DETACHED;   /* knlist_remove sets it */
599 }
600
601 static int
602 filt_timer(struct knote *kn, long hint)
603 {
604
605         return (kn->kn_data != 0);
606 }
607
608 static int
609 filt_userattach(struct knote *kn)
610 {
611
612         /* 
613          * EVFILT_USER knotes are not attached to anything in the kernel.
614          */ 
615         kn->kn_hook = NULL;
616         if (kn->kn_fflags & NOTE_TRIGGER)
617                 kn->kn_hookid = 1;
618         else
619                 kn->kn_hookid = 0;
620         return (0);
621 }
622
623 static void
624 filt_userdetach(__unused struct knote *kn)
625 {
626
627         /*
628          * EVFILT_USER knotes are not attached to anything in the kernel.
629          */
630 }
631
632 static int
633 filt_user(struct knote *kn, __unused long hint)
634 {
635
636         return (kn->kn_hookid);
637 }
638
639 static void
640 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
641 {
642         u_int ffctrl;
643
644         switch (type) {
645         case EVENT_REGISTER:
646                 if (kev->fflags & NOTE_TRIGGER)
647                         kn->kn_hookid = 1;
648
649                 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
650                 kev->fflags &= NOTE_FFLAGSMASK;
651                 switch (ffctrl) {
652                 case NOTE_FFNOP:
653                         break;
654
655                 case NOTE_FFAND:
656                         kn->kn_sfflags &= kev->fflags;
657                         break;
658
659                 case NOTE_FFOR:
660                         kn->kn_sfflags |= kev->fflags;
661                         break;
662
663                 case NOTE_FFCOPY:
664                         kn->kn_sfflags = kev->fflags;
665                         break;
666
667                 default:
668                         /* XXX Return error? */
669                         break;
670                 }
671                 kn->kn_sdata = kev->data;
672                 if (kev->flags & EV_CLEAR) {
673                         kn->kn_hookid = 0;
674                         kn->kn_data = 0;
675                         kn->kn_fflags = 0;
676                 }
677                 break;
678
679         case EVENT_PROCESS:
680                 *kev = kn->kn_kevent;
681                 kev->fflags = kn->kn_sfflags;
682                 kev->data = kn->kn_sdata;
683                 if (kn->kn_flags & EV_CLEAR) {
684                         kn->kn_hookid = 0;
685                         kn->kn_data = 0;
686                         kn->kn_fflags = 0;
687                 }
688                 break;
689
690         default:
691                 panic("filt_usertouch() - invalid type (%ld)", type);
692                 break;
693         }
694 }
695
696 int
697 sys_kqueue(struct thread *td, struct kqueue_args *uap)
698 {
699         struct filedesc *fdp;
700         struct kqueue *kq;
701         struct file *fp;
702         int fd, error;
703
704         fdp = td->td_proc->p_fd;
705         error = falloc(td, &fp, &fd, 0);
706         if (error)
707                 goto done2;
708
709         /* An extra reference on `fp' has been held for us by falloc(). */
710         kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
711         mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF|MTX_DUPOK);
712         TAILQ_INIT(&kq->kq_head);
713         kq->kq_fdp = fdp;
714         knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
715         TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
716
717         FILEDESC_XLOCK(fdp);
718         TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
719         FILEDESC_XUNLOCK(fdp);
720
721         finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
722         fdrop(fp, td);
723
724         td->td_retval[0] = fd;
725 done2:
726         return (error);
727 }
728
729 #ifndef _SYS_SYSPROTO_H_
730 struct kevent_args {
731         int     fd;
732         const struct kevent *changelist;
733         int     nchanges;
734         struct  kevent *eventlist;
735         int     nevents;
736         const struct timespec *timeout;
737 };
738 #endif
739 int
740 sys_kevent(struct thread *td, struct kevent_args *uap)
741 {
742         struct timespec ts, *tsp;
743         struct kevent_copyops k_ops = { uap,
744                                         kevent_copyout,
745                                         kevent_copyin};
746         int error;
747 #ifdef KTRACE
748         struct uio ktruio;
749         struct iovec ktriov;
750         struct uio *ktruioin = NULL;
751         struct uio *ktruioout = NULL;
752 #endif
753
754         if (uap->timeout != NULL) {
755                 error = copyin(uap->timeout, &ts, sizeof(ts));
756                 if (error)
757                         return (error);
758                 tsp = &ts;
759         } else
760                 tsp = NULL;
761
762 #ifdef KTRACE
763         if (KTRPOINT(td, KTR_GENIO)) {
764                 ktriov.iov_base = uap->changelist;
765                 ktriov.iov_len = uap->nchanges * sizeof(struct kevent);
766                 ktruio = (struct uio){ .uio_iov = &ktriov, .uio_iovcnt = 1,
767                     .uio_segflg = UIO_USERSPACE, .uio_rw = UIO_READ,
768                     .uio_td = td };
769                 ktruioin = cloneuio(&ktruio);
770                 ktriov.iov_base = uap->eventlist;
771                 ktriov.iov_len = uap->nevents * sizeof(struct kevent);
772                 ktruioout = cloneuio(&ktruio);
773         }
774 #endif
775
776         error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
777             &k_ops, tsp);
778
779 #ifdef KTRACE
780         if (ktruioin != NULL) {
781                 ktruioin->uio_resid = uap->nchanges * sizeof(struct kevent);
782                 ktrgenio(uap->fd, UIO_WRITE, ktruioin, 0);
783                 ktruioout->uio_resid = td->td_retval[0] * sizeof(struct kevent);
784                 ktrgenio(uap->fd, UIO_READ, ktruioout, error);
785         }
786 #endif
787
788         return (error);
789 }
790
791 /*
792  * Copy 'count' items into the destination list pointed to by uap->eventlist.
793  */
794 static int
795 kevent_copyout(void *arg, struct kevent *kevp, int count)
796 {
797         struct kevent_args *uap;
798         int error;
799
800         KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
801         uap = (struct kevent_args *)arg;
802
803         error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
804         if (error == 0)
805                 uap->eventlist += count;
806         return (error);
807 }
808
809 /*
810  * Copy 'count' items from the list pointed to by uap->changelist.
811  */
812 static int
813 kevent_copyin(void *arg, struct kevent *kevp, int count)
814 {
815         struct kevent_args *uap;
816         int error;
817
818         KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
819         uap = (struct kevent_args *)arg;
820
821         error = copyin(uap->changelist, kevp, count * sizeof *kevp);
822         if (error == 0)
823                 uap->changelist += count;
824         return (error);
825 }
826
827 int
828 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
829     struct kevent_copyops *k_ops, const struct timespec *timeout)
830 {
831         struct kevent keva[KQ_NEVENTS];
832         struct kevent *kevp, *changes;
833         struct kqueue *kq;
834         struct file *fp;
835         cap_rights_t rights;
836         int i, n, nerrors, error;
837
838         error = fget(td, fd, cap_rights_init(&rights, CAP_POST_EVENT), &fp);
839         if (error != 0)
840                 return (error);
841         if ((error = kqueue_acquire(fp, &kq)) != 0)
842                 goto done_norel;
843
844         nerrors = 0;
845
846         while (nchanges > 0) {
847                 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
848                 error = k_ops->k_copyin(k_ops->arg, keva, n);
849                 if (error)
850                         goto done;
851                 changes = keva;
852                 for (i = 0; i < n; i++) {
853                         kevp = &changes[i];
854                         if (!kevp->filter)
855                                 continue;
856                         kevp->flags &= ~EV_SYSFLAGS;
857                         error = kqueue_register(kq, kevp, td, 1);
858                         if (error || (kevp->flags & EV_RECEIPT)) {
859                                 if (nevents != 0) {
860                                         kevp->flags = EV_ERROR;
861                                         kevp->data = error;
862                                         (void) k_ops->k_copyout(k_ops->arg,
863                                             kevp, 1);
864                                         nevents--;
865                                         nerrors++;
866                                 } else {
867                                         goto done;
868                                 }
869                         }
870                 }
871                 nchanges -= n;
872         }
873         if (nerrors) {
874                 td->td_retval[0] = nerrors;
875                 error = 0;
876                 goto done;
877         }
878
879         error = kqueue_scan(kq, nevents, k_ops, timeout, keva, td);
880 done:
881         kqueue_release(kq, 0);
882 done_norel:
883         fdrop(fp, td);
884         return (error);
885 }
886
887 int
888 kqueue_add_filteropts(int filt, struct filterops *filtops)
889 {
890         int error;
891
892         error = 0;
893         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
894                 printf(
895 "trying to add a filterop that is out of range: %d is beyond %d\n",
896                     ~filt, EVFILT_SYSCOUNT);
897                 return EINVAL;
898         }
899         mtx_lock(&filterops_lock);
900         if (sysfilt_ops[~filt].for_fop != &null_filtops &&
901             sysfilt_ops[~filt].for_fop != NULL)
902                 error = EEXIST;
903         else {
904                 sysfilt_ops[~filt].for_fop = filtops;
905                 sysfilt_ops[~filt].for_refcnt = 0;
906         }
907         mtx_unlock(&filterops_lock);
908
909         return (error);
910 }
911
912 int
913 kqueue_del_filteropts(int filt)
914 {
915         int error;
916
917         error = 0;
918         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
919                 return EINVAL;
920
921         mtx_lock(&filterops_lock);
922         if (sysfilt_ops[~filt].for_fop == &null_filtops ||
923             sysfilt_ops[~filt].for_fop == NULL)
924                 error = EINVAL;
925         else if (sysfilt_ops[~filt].for_refcnt != 0)
926                 error = EBUSY;
927         else {
928                 sysfilt_ops[~filt].for_fop = &null_filtops;
929                 sysfilt_ops[~filt].for_refcnt = 0;
930         }
931         mtx_unlock(&filterops_lock);
932
933         return error;
934 }
935
936 static struct filterops *
937 kqueue_fo_find(int filt)
938 {
939
940         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
941                 return NULL;
942
943         mtx_lock(&filterops_lock);
944         sysfilt_ops[~filt].for_refcnt++;
945         if (sysfilt_ops[~filt].for_fop == NULL)
946                 sysfilt_ops[~filt].for_fop = &null_filtops;
947         mtx_unlock(&filterops_lock);
948
949         return sysfilt_ops[~filt].for_fop;
950 }
951
952 static void
953 kqueue_fo_release(int filt)
954 {
955
956         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
957                 return;
958
959         mtx_lock(&filterops_lock);
960         KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
961             ("filter object refcount not valid on release"));
962         sysfilt_ops[~filt].for_refcnt--;
963         mtx_unlock(&filterops_lock);
964 }
965
966 /*
967  * A ref to kq (obtained via kqueue_acquire) must be held.  waitok will
968  * influence if memory allocation should wait.  Make sure it is 0 if you
969  * hold any mutexes.
970  */
971 static int
972 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
973 {
974         struct filterops *fops;
975         struct file *fp;
976         struct knote *kn, *tkn;
977         cap_rights_t rights;
978         int error, filt, event;
979         int haskqglobal, filedesc_unlock;
980
981         fp = NULL;
982         kn = NULL;
983         error = 0;
984         haskqglobal = 0;
985         filedesc_unlock = 0;
986
987         filt = kev->filter;
988         fops = kqueue_fo_find(filt);
989         if (fops == NULL)
990                 return EINVAL;
991
992         tkn = knote_alloc(waitok);              /* prevent waiting with locks */
993
994 findkn:
995         if (fops->f_isfd) {
996                 KASSERT(td != NULL, ("td is NULL"));
997                 error = fget(td, kev->ident,
998                     cap_rights_init(&rights, CAP_POLL_EVENT), &fp);
999                 if (error)
1000                         goto done;
1001
1002                 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1003                     kev->ident, 0) != 0) {
1004                         /* try again */
1005                         fdrop(fp, td);
1006                         fp = NULL;
1007                         error = kqueue_expand(kq, fops, kev->ident, waitok);
1008                         if (error)
1009                                 goto done;
1010                         goto findkn;
1011                 }
1012
1013                 if (fp->f_type == DTYPE_KQUEUE) {
1014                         /*
1015                          * if we add some inteligence about what we are doing,
1016                          * we should be able to support events on ourselves.
1017                          * We need to know when we are doing this to prevent
1018                          * getting both the knlist lock and the kq lock since
1019                          * they are the same thing.
1020                          */
1021                         if (fp->f_data == kq) {
1022                                 error = EINVAL;
1023                                 goto done;
1024                         }
1025
1026                         /*
1027                          * Pre-lock the filedesc before the global
1028                          * lock mutex, see the comment in
1029                          * kqueue_close().
1030                          */
1031                         FILEDESC_XLOCK(td->td_proc->p_fd);
1032                         filedesc_unlock = 1;
1033                         KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1034                 }
1035
1036                 KQ_LOCK(kq);
1037                 if (kev->ident < kq->kq_knlistsize) {
1038                         SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1039                                 if (kev->filter == kn->kn_filter)
1040                                         break;
1041                 }
1042         } else {
1043                 if ((kev->flags & EV_ADD) == EV_ADD)
1044                         kqueue_expand(kq, fops, kev->ident, waitok);
1045
1046                 KQ_LOCK(kq);
1047                 if (kq->kq_knhashmask != 0) {
1048                         struct klist *list;
1049
1050                         list = &kq->kq_knhash[
1051                             KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1052                         SLIST_FOREACH(kn, list, kn_link)
1053                                 if (kev->ident == kn->kn_id &&
1054                                     kev->filter == kn->kn_filter)
1055                                         break;
1056                 }
1057         }
1058
1059         /* knote is in the process of changing, wait for it to stablize. */
1060         if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1061                 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1062                 if (filedesc_unlock) {
1063                         FILEDESC_XUNLOCK(td->td_proc->p_fd);
1064                         filedesc_unlock = 0;
1065                 }
1066                 kq->kq_state |= KQ_FLUXWAIT;
1067                 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1068                 if (fp != NULL) {
1069                         fdrop(fp, td);
1070                         fp = NULL;
1071                 }
1072                 goto findkn;
1073         }
1074
1075         /*
1076          * kn now contains the matching knote, or NULL if no match
1077          */
1078         if (kn == NULL) {
1079                 if (kev->flags & EV_ADD) {
1080                         kn = tkn;
1081                         tkn = NULL;
1082                         if (kn == NULL) {
1083                                 KQ_UNLOCK(kq);
1084                                 error = ENOMEM;
1085                                 goto done;
1086                         }
1087                         kn->kn_fp = fp;
1088                         kn->kn_kq = kq;
1089                         kn->kn_fop = fops;
1090                         /*
1091                          * apply reference counts to knote structure, and
1092                          * do not release it at the end of this routine.
1093                          */
1094                         fops = NULL;
1095                         fp = NULL;
1096
1097                         kn->kn_sfflags = kev->fflags;
1098                         kn->kn_sdata = kev->data;
1099                         kev->fflags = 0;
1100                         kev->data = 0;
1101                         kn->kn_kevent = *kev;
1102                         kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1103                             EV_ENABLE | EV_DISABLE);
1104                         kn->kn_status = KN_INFLUX|KN_DETACHED;
1105
1106                         error = knote_attach(kn, kq);
1107                         KQ_UNLOCK(kq);
1108                         if (error != 0) {
1109                                 tkn = kn;
1110                                 goto done;
1111                         }
1112
1113                         if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1114                                 knote_drop(kn, td);
1115                                 goto done;
1116                         }
1117                         KN_LIST_LOCK(kn);
1118                         goto done_ev_add;
1119                 } else {
1120                         /* No matching knote and the EV_ADD flag is not set. */
1121                         KQ_UNLOCK(kq);
1122                         error = ENOENT;
1123                         goto done;
1124                 }
1125         }
1126         
1127         if (kev->flags & EV_DELETE) {
1128                 kn->kn_status |= KN_INFLUX;
1129                 KQ_UNLOCK(kq);
1130                 if (!(kn->kn_status & KN_DETACHED))
1131                         kn->kn_fop->f_detach(kn);
1132                 knote_drop(kn, td);
1133                 goto done;
1134         }
1135
1136         /*
1137          * The user may change some filter values after the initial EV_ADD,
1138          * but doing so will not reset any filter which has already been
1139          * triggered.
1140          */
1141         kn->kn_status |= KN_INFLUX;
1142         KQ_UNLOCK(kq);
1143         KN_LIST_LOCK(kn);
1144         kn->kn_kevent.udata = kev->udata;
1145         if (!fops->f_isfd && fops->f_touch != NULL) {
1146                 fops->f_touch(kn, kev, EVENT_REGISTER);
1147         } else {
1148                 kn->kn_sfflags = kev->fflags;
1149                 kn->kn_sdata = kev->data;
1150         }
1151
1152         /*
1153          * We can get here with kn->kn_knlist == NULL.  This can happen when
1154          * the initial attach event decides that the event is "completed" 
1155          * already.  i.e. filt_procattach is called on a zombie process.  It
1156          * will call filt_proc which will remove it from the list, and NULL
1157          * kn_knlist.
1158          */
1159 done_ev_add:
1160         event = kn->kn_fop->f_event(kn, 0);
1161         KQ_LOCK(kq);
1162         if (event)
1163                 KNOTE_ACTIVATE(kn, 1);
1164         kn->kn_status &= ~KN_INFLUX;
1165         KN_LIST_UNLOCK(kn);
1166
1167         if ((kev->flags & EV_DISABLE) &&
1168             ((kn->kn_status & KN_DISABLED) == 0)) {
1169                 kn->kn_status |= KN_DISABLED;
1170         }
1171
1172         if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
1173                 kn->kn_status &= ~KN_DISABLED;
1174                 if ((kn->kn_status & KN_ACTIVE) &&
1175                     ((kn->kn_status & KN_QUEUED) == 0))
1176                         knote_enqueue(kn);
1177         }
1178         KQ_UNLOCK_FLUX(kq);
1179
1180 done:
1181         KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1182         if (filedesc_unlock)
1183                 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1184         if (fp != NULL)
1185                 fdrop(fp, td);
1186         if (tkn != NULL)
1187                 knote_free(tkn);
1188         if (fops != NULL)
1189                 kqueue_fo_release(filt);
1190         return (error);
1191 }
1192
1193 static int
1194 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1195 {
1196         int error;
1197         struct kqueue *kq;
1198
1199         error = 0;
1200
1201         kq = fp->f_data;
1202         if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1203                 return (EBADF);
1204         *kqp = kq;
1205         KQ_LOCK(kq);
1206         if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1207                 KQ_UNLOCK(kq);
1208                 return (EBADF);
1209         }
1210         kq->kq_refcnt++;
1211         KQ_UNLOCK(kq);
1212
1213         return error;
1214 }
1215
1216 static void
1217 kqueue_release(struct kqueue *kq, int locked)
1218 {
1219         if (locked)
1220                 KQ_OWNED(kq);
1221         else
1222                 KQ_LOCK(kq);
1223         kq->kq_refcnt--;
1224         if (kq->kq_refcnt == 1)
1225                 wakeup(&kq->kq_refcnt);
1226         if (!locked)
1227                 KQ_UNLOCK(kq);
1228 }
1229
1230 static void
1231 kqueue_schedtask(struct kqueue *kq)
1232 {
1233
1234         KQ_OWNED(kq);
1235         KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1236             ("scheduling kqueue task while draining"));
1237
1238         if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1239                 taskqueue_enqueue(taskqueue_kqueue, &kq->kq_task);
1240                 kq->kq_state |= KQ_TASKSCHED;
1241         }
1242 }
1243
1244 /*
1245  * Expand the kq to make sure we have storage for fops/ident pair.
1246  *
1247  * Return 0 on success (or no work necessary), return errno on failure.
1248  *
1249  * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1250  * If kqueue_register is called from a non-fd context, there usually/should
1251  * be no locks held.
1252  */
1253 static int
1254 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1255         int waitok)
1256 {
1257         struct klist *list, *tmp_knhash, *to_free;
1258         u_long tmp_knhashmask;
1259         int size;
1260         int fd;
1261         int mflag = waitok ? M_WAITOK : M_NOWAIT;
1262
1263         KQ_NOTOWNED(kq);
1264
1265         to_free = NULL;
1266         if (fops->f_isfd) {
1267                 fd = ident;
1268                 if (kq->kq_knlistsize <= fd) {
1269                         size = kq->kq_knlistsize;
1270                         while (size <= fd)
1271                                 size += KQEXTENT;
1272                         list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1273                         if (list == NULL)
1274                                 return ENOMEM;
1275                         KQ_LOCK(kq);
1276                         if (kq->kq_knlistsize > fd) {
1277                                 to_free = list;
1278                                 list = NULL;
1279                         } else {
1280                                 if (kq->kq_knlist != NULL) {
1281                                         bcopy(kq->kq_knlist, list,
1282                                             kq->kq_knlistsize * sizeof(*list));
1283                                         to_free = kq->kq_knlist;
1284                                         kq->kq_knlist = NULL;
1285                                 }
1286                                 bzero((caddr_t)list +
1287                                     kq->kq_knlistsize * sizeof(*list),
1288                                     (size - kq->kq_knlistsize) * sizeof(*list));
1289                                 kq->kq_knlistsize = size;
1290                                 kq->kq_knlist = list;
1291                         }
1292                         KQ_UNLOCK(kq);
1293                 }
1294         } else {
1295                 if (kq->kq_knhashmask == 0) {
1296                         tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1297                             &tmp_knhashmask);
1298                         if (tmp_knhash == NULL)
1299                                 return ENOMEM;
1300                         KQ_LOCK(kq);
1301                         if (kq->kq_knhashmask == 0) {
1302                                 kq->kq_knhash = tmp_knhash;
1303                                 kq->kq_knhashmask = tmp_knhashmask;
1304                         } else {
1305                                 to_free = tmp_knhash;
1306                         }
1307                         KQ_UNLOCK(kq);
1308                 }
1309         }
1310         free(to_free, M_KQUEUE);
1311
1312         KQ_NOTOWNED(kq);
1313         return 0;
1314 }
1315
1316 static void
1317 kqueue_task(void *arg, int pending)
1318 {
1319         struct kqueue *kq;
1320         int haskqglobal;
1321
1322         haskqglobal = 0;
1323         kq = arg;
1324
1325         KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1326         KQ_LOCK(kq);
1327
1328         KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1329
1330         kq->kq_state &= ~KQ_TASKSCHED;
1331         if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1332                 wakeup(&kq->kq_state);
1333         }
1334         KQ_UNLOCK(kq);
1335         KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1336 }
1337
1338 /*
1339  * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1340  * We treat KN_MARKER knotes as if they are INFLUX.
1341  */
1342 static int
1343 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1344     const struct timespec *tsp, struct kevent *keva, struct thread *td)
1345 {
1346         struct kevent *kevp;
1347         struct knote *kn, *marker;
1348         sbintime_t asbt, rsbt;
1349         int count, error, haskqglobal, influx, nkev, touch;
1350
1351         count = maxevents;
1352         nkev = 0;
1353         error = 0;
1354         haskqglobal = 0;
1355
1356         if (maxevents == 0)
1357                 goto done_nl;
1358
1359         rsbt = 0;
1360         if (tsp != NULL) {
1361                 if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1362                     tsp->tv_nsec >= 1000000000) {
1363                         error = EINVAL;
1364                         goto done_nl;
1365                 }
1366                 if (timespecisset(tsp)) {
1367                         if (tsp->tv_sec <= INT32_MAX) {
1368                                 rsbt = tstosbt(*tsp);
1369                                 if (TIMESEL(&asbt, rsbt))
1370                                         asbt += tc_tick_sbt;
1371                                 if (asbt <= INT64_MAX - rsbt)
1372                                         asbt += rsbt;
1373                                 else
1374                                         asbt = 0;
1375                                 rsbt >>= tc_precexp;
1376                         } else
1377                                 asbt = 0;
1378                 } else
1379                         asbt = -1;
1380         } else
1381                 asbt = 0;
1382         marker = knote_alloc(1);
1383         if (marker == NULL) {
1384                 error = ENOMEM;
1385                 goto done_nl;
1386         }
1387         marker->kn_status = KN_MARKER;
1388         KQ_LOCK(kq);
1389
1390 retry:
1391         kevp = keva;
1392         if (kq->kq_count == 0) {
1393                 if (asbt == -1) {
1394                         error = EWOULDBLOCK;
1395                 } else {
1396                         kq->kq_state |= KQ_SLEEP;
1397                         error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1398                             "kqread", asbt, rsbt, C_ABSOLUTE);
1399                 }
1400                 if (error == 0)
1401                         goto retry;
1402                 /* don't restart after signals... */
1403                 if (error == ERESTART)
1404                         error = EINTR;
1405                 else if (error == EWOULDBLOCK)
1406                         error = 0;
1407                 goto done;
1408         }
1409
1410         TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1411         influx = 0;
1412         while (count) {
1413                 KQ_OWNED(kq);
1414                 kn = TAILQ_FIRST(&kq->kq_head);
1415
1416                 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1417                     (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1418                         if (influx) {
1419                                 influx = 0;
1420                                 KQ_FLUX_WAKEUP(kq);
1421                         }
1422                         kq->kq_state |= KQ_FLUXWAIT;
1423                         error = msleep(kq, &kq->kq_lock, PSOCK,
1424                             "kqflxwt", 0);
1425                         continue;
1426                 }
1427
1428                 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1429                 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1430                         kn->kn_status &= ~KN_QUEUED;
1431                         kq->kq_count--;
1432                         continue;
1433                 }
1434                 if (kn == marker) {
1435                         KQ_FLUX_WAKEUP(kq);
1436                         if (count == maxevents)
1437                                 goto retry;
1438                         goto done;
1439                 }
1440                 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1441                     ("KN_INFLUX set when not suppose to be"));
1442
1443                 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1444                         kn->kn_status &= ~KN_QUEUED;
1445                         kn->kn_status |= KN_INFLUX;
1446                         kq->kq_count--;
1447                         KQ_UNLOCK(kq);
1448                         /*
1449                          * We don't need to lock the list since we've marked
1450                          * it _INFLUX.
1451                          */
1452                         if (!(kn->kn_status & KN_DETACHED))
1453                                 kn->kn_fop->f_detach(kn);
1454                         knote_drop(kn, td);
1455                         KQ_LOCK(kq);
1456                         continue;
1457                 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1458                         kn->kn_status &= ~KN_QUEUED;
1459                         kn->kn_status |= KN_INFLUX;
1460                         kq->kq_count--;
1461                         KQ_UNLOCK(kq);
1462                         /*
1463                          * We don't need to lock the list since we've marked
1464                          * it _INFLUX.
1465                          */
1466                         *kevp = kn->kn_kevent;
1467                         if (!(kn->kn_status & KN_DETACHED))
1468                                 kn->kn_fop->f_detach(kn);
1469                         knote_drop(kn, td);
1470                         KQ_LOCK(kq);
1471                         kn = NULL;
1472                 } else {
1473                         kn->kn_status |= KN_INFLUX;
1474                         KQ_UNLOCK(kq);
1475                         if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1476                                 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1477                         KN_LIST_LOCK(kn);
1478                         if (kn->kn_fop->f_event(kn, 0) == 0) {
1479                                 KQ_LOCK(kq);
1480                                 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1481                                 kn->kn_status &=
1482                                     ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX);
1483                                 kq->kq_count--;
1484                                 KN_LIST_UNLOCK(kn);
1485                                 influx = 1;
1486                                 continue;
1487                         }
1488                         touch = (!kn->kn_fop->f_isfd &&
1489                             kn->kn_fop->f_touch != NULL);
1490                         if (touch)
1491                                 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1492                         else
1493                                 *kevp = kn->kn_kevent;
1494                         KQ_LOCK(kq);
1495                         KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1496                         if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1497                                 /* 
1498                                  * Manually clear knotes who weren't 
1499                                  * 'touch'ed.
1500                                  */
1501                                 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1502                                         kn->kn_data = 0;
1503                                         kn->kn_fflags = 0;
1504                                 }
1505                                 if (kn->kn_flags & EV_DISPATCH)
1506                                         kn->kn_status |= KN_DISABLED;
1507                                 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1508                                 kq->kq_count--;
1509                         } else
1510                                 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1511                         
1512                         kn->kn_status &= ~(KN_INFLUX);
1513                         KN_LIST_UNLOCK(kn);
1514                         influx = 1;
1515                 }
1516
1517                 /* we are returning a copy to the user */
1518                 kevp++;
1519                 nkev++;
1520                 count--;
1521
1522                 if (nkev == KQ_NEVENTS) {
1523                         influx = 0;
1524                         KQ_UNLOCK_FLUX(kq);
1525                         error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1526                         nkev = 0;
1527                         kevp = keva;
1528                         KQ_LOCK(kq);
1529                         if (error)
1530                                 break;
1531                 }
1532         }
1533         TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1534 done:
1535         KQ_OWNED(kq);
1536         KQ_UNLOCK_FLUX(kq);
1537         knote_free(marker);
1538 done_nl:
1539         KQ_NOTOWNED(kq);
1540         if (nkev != 0)
1541                 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1542         td->td_retval[0] = maxevents - count;
1543         return (error);
1544 }
1545
1546 /*
1547  * XXX
1548  * This could be expanded to call kqueue_scan, if desired.
1549  */
1550 /*ARGSUSED*/
1551 static int
1552 kqueue_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
1553         int flags, struct thread *td)
1554 {
1555         return (ENXIO);
1556 }
1557
1558 /*ARGSUSED*/
1559 static int
1560 kqueue_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
1561          int flags, struct thread *td)
1562 {
1563         return (ENXIO);
1564 }
1565
1566 /*ARGSUSED*/
1567 static int
1568 kqueue_truncate(struct file *fp, off_t length, struct ucred *active_cred,
1569         struct thread *td)
1570 {
1571
1572         return (EINVAL);
1573 }
1574
1575 /*ARGSUSED*/
1576 static int
1577 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1578         struct ucred *active_cred, struct thread *td)
1579 {
1580         /*
1581          * Enabling sigio causes two major problems:
1582          * 1) infinite recursion:
1583          * Synopsys: kevent is being used to track signals and have FIOASYNC
1584          * set.  On receipt of a signal this will cause a kqueue to recurse
1585          * into itself over and over.  Sending the sigio causes the kqueue
1586          * to become ready, which in turn posts sigio again, forever.
1587          * Solution: this can be solved by setting a flag in the kqueue that
1588          * we have a SIGIO in progress.
1589          * 2) locking problems:
1590          * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1591          * us above the proc and pgrp locks.
1592          * Solution: Post a signal using an async mechanism, being sure to
1593          * record a generation count in the delivery so that we do not deliver
1594          * a signal to the wrong process.
1595          *
1596          * Note, these two mechanisms are somewhat mutually exclusive!
1597          */
1598 #if 0
1599         struct kqueue *kq;
1600
1601         kq = fp->f_data;
1602         switch (cmd) {
1603         case FIOASYNC:
1604                 if (*(int *)data) {
1605                         kq->kq_state |= KQ_ASYNC;
1606                 } else {
1607                         kq->kq_state &= ~KQ_ASYNC;
1608                 }
1609                 return (0);
1610
1611         case FIOSETOWN:
1612                 return (fsetown(*(int *)data, &kq->kq_sigio));
1613
1614         case FIOGETOWN:
1615                 *(int *)data = fgetown(&kq->kq_sigio);
1616                 return (0);
1617         }
1618 #endif
1619
1620         return (ENOTTY);
1621 }
1622
1623 /*ARGSUSED*/
1624 static int
1625 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1626         struct thread *td)
1627 {
1628         struct kqueue *kq;
1629         int revents = 0;
1630         int error;
1631
1632         if ((error = kqueue_acquire(fp, &kq)))
1633                 return POLLERR;
1634
1635         KQ_LOCK(kq);
1636         if (events & (POLLIN | POLLRDNORM)) {
1637                 if (kq->kq_count) {
1638                         revents |= events & (POLLIN | POLLRDNORM);
1639                 } else {
1640                         selrecord(td, &kq->kq_sel);
1641                         if (SEL_WAITING(&kq->kq_sel))
1642                                 kq->kq_state |= KQ_SEL;
1643                 }
1644         }
1645         kqueue_release(kq, 1);
1646         KQ_UNLOCK(kq);
1647         return (revents);
1648 }
1649
1650 /*ARGSUSED*/
1651 static int
1652 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1653         struct thread *td)
1654 {
1655
1656         bzero((void *)st, sizeof *st);
1657         /*
1658          * We no longer return kq_count because the unlocked value is useless.
1659          * If you spent all this time getting the count, why not spend your
1660          * syscall better by calling kevent?
1661          *
1662          * XXX - This is needed for libc_r.
1663          */
1664         st->st_mode = S_IFIFO;
1665         return (0);
1666 }
1667
1668 /*ARGSUSED*/
1669 static int
1670 kqueue_close(struct file *fp, struct thread *td)
1671 {
1672         struct kqueue *kq = fp->f_data;
1673         struct filedesc *fdp;
1674         struct knote *kn;
1675         int i;
1676         int error;
1677         int filedesc_unlock;
1678
1679         if ((error = kqueue_acquire(fp, &kq)))
1680                 return error;
1681
1682         filedesc_unlock = 0;
1683         KQ_LOCK(kq);
1684
1685         KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1686             ("kqueue already closing"));
1687         kq->kq_state |= KQ_CLOSING;
1688         if (kq->kq_refcnt > 1)
1689                 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1690
1691         KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1692         fdp = kq->kq_fdp;
1693
1694         KASSERT(knlist_empty(&kq->kq_sel.si_note),
1695             ("kqueue's knlist not empty"));
1696
1697         for (i = 0; i < kq->kq_knlistsize; i++) {
1698                 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1699                         if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1700                                 kq->kq_state |= KQ_FLUXWAIT;
1701                                 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
1702                                 continue;
1703                         }
1704                         kn->kn_status |= KN_INFLUX;
1705                         KQ_UNLOCK(kq);
1706                         if (!(kn->kn_status & KN_DETACHED))
1707                                 kn->kn_fop->f_detach(kn);
1708                         knote_drop(kn, td);
1709                         KQ_LOCK(kq);
1710                 }
1711         }
1712         if (kq->kq_knhashmask != 0) {
1713                 for (i = 0; i <= kq->kq_knhashmask; i++) {
1714                         while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1715                                 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1716                                         kq->kq_state |= KQ_FLUXWAIT;
1717                                         msleep(kq, &kq->kq_lock, PSOCK,
1718                                                "kqclo2", 0);
1719                                         continue;
1720                                 }
1721                                 kn->kn_status |= KN_INFLUX;
1722                                 KQ_UNLOCK(kq);
1723                                 if (!(kn->kn_status & KN_DETACHED))
1724                                         kn->kn_fop->f_detach(kn);
1725                                 knote_drop(kn, td);
1726                                 KQ_LOCK(kq);
1727                         }
1728                 }
1729         }
1730
1731         if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1732                 kq->kq_state |= KQ_TASKDRAIN;
1733                 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1734         }
1735
1736         if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1737                 selwakeuppri(&kq->kq_sel, PSOCK);
1738                 if (!SEL_WAITING(&kq->kq_sel))
1739                         kq->kq_state &= ~KQ_SEL;
1740         }
1741
1742         KQ_UNLOCK(kq);
1743
1744         /*
1745          * We could be called due to the knote_drop() doing fdrop(),
1746          * called from kqueue_register().  In this case the global
1747          * lock is owned, and filedesc sx is locked before, to not
1748          * take the sleepable lock after non-sleepable.
1749          */
1750         if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
1751                 FILEDESC_XLOCK(fdp);
1752                 filedesc_unlock = 1;
1753         } else
1754                 filedesc_unlock = 0;
1755         TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
1756         if (filedesc_unlock)
1757                 FILEDESC_XUNLOCK(fdp);
1758
1759         seldrain(&kq->kq_sel);
1760         knlist_destroy(&kq->kq_sel.si_note);
1761         mtx_destroy(&kq->kq_lock);
1762         kq->kq_fdp = NULL;
1763
1764         if (kq->kq_knhash != NULL)
1765                 free(kq->kq_knhash, M_KQUEUE);
1766         if (kq->kq_knlist != NULL)
1767                 free(kq->kq_knlist, M_KQUEUE);
1768
1769         funsetown(&kq->kq_sigio);
1770         free(kq, M_KQUEUE);
1771         fp->f_data = NULL;
1772
1773         return (0);
1774 }
1775
1776 static void
1777 kqueue_wakeup(struct kqueue *kq)
1778 {
1779         KQ_OWNED(kq);
1780
1781         if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
1782                 kq->kq_state &= ~KQ_SLEEP;
1783                 wakeup(kq);
1784         }
1785         if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1786                 selwakeuppri(&kq->kq_sel, PSOCK);
1787                 if (!SEL_WAITING(&kq->kq_sel))
1788                         kq->kq_state &= ~KQ_SEL;
1789         }
1790         if (!knlist_empty(&kq->kq_sel.si_note))
1791                 kqueue_schedtask(kq);
1792         if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
1793                 pgsigio(&kq->kq_sigio, SIGIO, 0);
1794         }
1795 }
1796
1797 /*
1798  * Walk down a list of knotes, activating them if their event has triggered.
1799  *
1800  * There is a possibility to optimize in the case of one kq watching another.
1801  * Instead of scheduling a task to wake it up, you could pass enough state
1802  * down the chain to make up the parent kqueue.  Make this code functional
1803  * first.
1804  */
1805 void
1806 knote(struct knlist *list, long hint, int lockflags)
1807 {
1808         struct kqueue *kq;
1809         struct knote *kn;
1810         int error;
1811
1812         if (list == NULL)
1813                 return;
1814
1815         KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
1816
1817         if ((lockflags & KNF_LISTLOCKED) == 0)
1818                 list->kl_lock(list->kl_lockarg); 
1819
1820         /*
1821          * If we unlock the list lock (and set KN_INFLUX), we can eliminate
1822          * the kqueue scheduling, but this will introduce four
1823          * lock/unlock's for each knote to test.  If we do, continue to use
1824          * SLIST_FOREACH, SLIST_FOREACH_SAFE is not safe in our case, it is
1825          * only safe if you want to remove the current item, which we are
1826          * not doing.
1827          */
1828         SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
1829                 kq = kn->kn_kq;
1830                 if ((kn->kn_status & KN_INFLUX) != KN_INFLUX) {
1831                         KQ_LOCK(kq);
1832                         if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1833                                 KQ_UNLOCK(kq);
1834                         } else if ((lockflags & KNF_NOKQLOCK) != 0) {
1835                                 kn->kn_status |= KN_INFLUX;
1836                                 KQ_UNLOCK(kq);
1837                                 error = kn->kn_fop->f_event(kn, hint);
1838                                 KQ_LOCK(kq);
1839                                 kn->kn_status &= ~KN_INFLUX;
1840                                 if (error)
1841                                         KNOTE_ACTIVATE(kn, 1);
1842                                 KQ_UNLOCK_FLUX(kq);
1843                         } else {
1844                                 kn->kn_status |= KN_HASKQLOCK;
1845                                 if (kn->kn_fop->f_event(kn, hint))
1846                                         KNOTE_ACTIVATE(kn, 1);
1847                                 kn->kn_status &= ~KN_HASKQLOCK;
1848                                 KQ_UNLOCK(kq);
1849                         }
1850                 }
1851                 kq = NULL;
1852         }
1853         if ((lockflags & KNF_LISTLOCKED) == 0)
1854                 list->kl_unlock(list->kl_lockarg); 
1855 }
1856
1857 /*
1858  * add a knote to a knlist
1859  */
1860 void
1861 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
1862 {
1863         KNL_ASSERT_LOCK(knl, islocked);
1864         KQ_NOTOWNED(kn->kn_kq);
1865         KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
1866             (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
1867         if (!islocked)
1868                 knl->kl_lock(knl->kl_lockarg);
1869         SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
1870         if (!islocked)
1871                 knl->kl_unlock(knl->kl_lockarg);
1872         KQ_LOCK(kn->kn_kq);
1873         kn->kn_knlist = knl;
1874         kn->kn_status &= ~KN_DETACHED;
1875         KQ_UNLOCK(kn->kn_kq);
1876 }
1877
1878 static void
1879 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked, int kqislocked)
1880 {
1881         KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
1882         KNL_ASSERT_LOCK(knl, knlislocked);
1883         mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
1884         if (!kqislocked)
1885                 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
1886     ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
1887         if (!knlislocked)
1888                 knl->kl_lock(knl->kl_lockarg);
1889         SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
1890         kn->kn_knlist = NULL;
1891         if (!knlislocked)
1892                 knl->kl_unlock(knl->kl_lockarg);
1893         if (!kqislocked)
1894                 KQ_LOCK(kn->kn_kq);
1895         kn->kn_status |= KN_DETACHED;
1896         if (!kqislocked)
1897                 KQ_UNLOCK(kn->kn_kq);
1898 }
1899
1900 /*
1901  * remove knote from the specified knlist
1902  */
1903 void
1904 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
1905 {
1906
1907         knlist_remove_kq(knl, kn, islocked, 0);
1908 }
1909
1910 /*
1911  * remove knote from the specified knlist while in f_event handler.
1912  */
1913 void
1914 knlist_remove_inevent(struct knlist *knl, struct knote *kn)
1915 {
1916
1917         knlist_remove_kq(knl, kn, 1,
1918             (kn->kn_status & KN_HASKQLOCK) == KN_HASKQLOCK);
1919 }
1920
1921 int
1922 knlist_empty(struct knlist *knl)
1923 {
1924
1925         KNL_ASSERT_LOCKED(knl);
1926         return SLIST_EMPTY(&knl->kl_list);
1927 }
1928
1929 static struct mtx       knlist_lock;
1930 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
1931         MTX_DEF);
1932 static void knlist_mtx_lock(void *arg);
1933 static void knlist_mtx_unlock(void *arg);
1934
1935 static void
1936 knlist_mtx_lock(void *arg)
1937 {
1938
1939         mtx_lock((struct mtx *)arg);
1940 }
1941
1942 static void
1943 knlist_mtx_unlock(void *arg)
1944 {
1945
1946         mtx_unlock((struct mtx *)arg);
1947 }
1948
1949 static void
1950 knlist_mtx_assert_locked(void *arg)
1951 {
1952
1953         mtx_assert((struct mtx *)arg, MA_OWNED);
1954 }
1955
1956 static void
1957 knlist_mtx_assert_unlocked(void *arg)
1958 {
1959
1960         mtx_assert((struct mtx *)arg, MA_NOTOWNED);
1961 }
1962
1963 static void
1964 knlist_rw_rlock(void *arg)
1965 {
1966
1967         rw_rlock((struct rwlock *)arg);
1968 }
1969
1970 static void
1971 knlist_rw_runlock(void *arg)
1972 {
1973
1974         rw_runlock((struct rwlock *)arg);
1975 }
1976
1977 static void
1978 knlist_rw_assert_locked(void *arg)
1979 {
1980
1981         rw_assert((struct rwlock *)arg, RA_LOCKED);
1982 }
1983
1984 static void
1985 knlist_rw_assert_unlocked(void *arg)
1986 {
1987
1988         rw_assert((struct rwlock *)arg, RA_UNLOCKED);
1989 }
1990
1991 void
1992 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
1993     void (*kl_unlock)(void *),
1994     void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
1995 {
1996
1997         if (lock == NULL)
1998                 knl->kl_lockarg = &knlist_lock;
1999         else
2000                 knl->kl_lockarg = lock;
2001
2002         if (kl_lock == NULL)
2003                 knl->kl_lock = knlist_mtx_lock;
2004         else
2005                 knl->kl_lock = kl_lock;
2006         if (kl_unlock == NULL)
2007                 knl->kl_unlock = knlist_mtx_unlock;
2008         else
2009                 knl->kl_unlock = kl_unlock;
2010         if (kl_assert_locked == NULL)
2011                 knl->kl_assert_locked = knlist_mtx_assert_locked;
2012         else
2013                 knl->kl_assert_locked = kl_assert_locked;
2014         if (kl_assert_unlocked == NULL)
2015                 knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2016         else
2017                 knl->kl_assert_unlocked = kl_assert_unlocked;
2018
2019         SLIST_INIT(&knl->kl_list);
2020 }
2021
2022 void
2023 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2024 {
2025
2026         knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2027 }
2028
2029 void
2030 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2031 {
2032
2033         knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2034             knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2035 }
2036
2037 void
2038 knlist_destroy(struct knlist *knl)
2039 {
2040
2041 #ifdef INVARIANTS
2042         /*
2043          * if we run across this error, we need to find the offending
2044          * driver and have it call knlist_clear or knlist_delete.
2045          */
2046         if (!SLIST_EMPTY(&knl->kl_list))
2047                 printf("WARNING: destroying knlist w/ knotes on it!\n");
2048 #endif
2049
2050         knl->kl_lockarg = knl->kl_lock = knl->kl_unlock = NULL;
2051         SLIST_INIT(&knl->kl_list);
2052 }
2053
2054 /*
2055  * Even if we are locked, we may need to drop the lock to allow any influx
2056  * knotes time to "settle".
2057  */
2058 void
2059 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2060 {
2061         struct knote *kn, *kn2;
2062         struct kqueue *kq;
2063
2064         if (islocked)
2065                 KNL_ASSERT_LOCKED(knl);
2066         else {
2067                 KNL_ASSERT_UNLOCKED(knl);
2068 again:          /* need to reacquire lock since we have dropped it */
2069                 knl->kl_lock(knl->kl_lockarg);
2070         }
2071
2072         SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2073                 kq = kn->kn_kq;
2074                 KQ_LOCK(kq);
2075                 if ((kn->kn_status & KN_INFLUX)) {
2076                         KQ_UNLOCK(kq);
2077                         continue;
2078                 }
2079                 knlist_remove_kq(knl, kn, 1, 1);
2080                 if (killkn) {
2081                         kn->kn_status |= KN_INFLUX | KN_DETACHED;
2082                         KQ_UNLOCK(kq);
2083                         knote_drop(kn, td);
2084                 } else {
2085                         /* Make sure cleared knotes disappear soon */
2086                         kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2087                         KQ_UNLOCK(kq);
2088                 }
2089                 kq = NULL;
2090         }
2091
2092         if (!SLIST_EMPTY(&knl->kl_list)) {
2093                 /* there are still KN_INFLUX remaining */
2094                 kn = SLIST_FIRST(&knl->kl_list);
2095                 kq = kn->kn_kq;
2096                 KQ_LOCK(kq);
2097                 KASSERT(kn->kn_status & KN_INFLUX,
2098                     ("knote removed w/o list lock"));
2099                 knl->kl_unlock(knl->kl_lockarg);
2100                 kq->kq_state |= KQ_FLUXWAIT;
2101                 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2102                 kq = NULL;
2103                 goto again;
2104         }
2105
2106         if (islocked)
2107                 KNL_ASSERT_LOCKED(knl);
2108         else {
2109                 knl->kl_unlock(knl->kl_lockarg);
2110                 KNL_ASSERT_UNLOCKED(knl);
2111         }
2112 }
2113
2114 /*
2115  * Remove all knotes referencing a specified fd must be called with FILEDESC
2116  * lock.  This prevents a race where a new fd comes along and occupies the
2117  * entry and we attach a knote to the fd.
2118  */
2119 void
2120 knote_fdclose(struct thread *td, int fd)
2121 {
2122         struct filedesc *fdp = td->td_proc->p_fd;
2123         struct kqueue *kq;
2124         struct knote *kn;
2125         int influx;
2126
2127         FILEDESC_XLOCK_ASSERT(fdp);
2128
2129         /*
2130          * We shouldn't have to worry about new kevents appearing on fd
2131          * since filedesc is locked.
2132          */
2133         TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2134                 KQ_LOCK(kq);
2135
2136 again:
2137                 influx = 0;
2138                 while (kq->kq_knlistsize > fd &&
2139                     (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2140                         if (kn->kn_status & KN_INFLUX) {
2141                                 /* someone else might be waiting on our knote */
2142                                 if (influx)
2143                                         wakeup(kq);
2144                                 kq->kq_state |= KQ_FLUXWAIT;
2145                                 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2146                                 goto again;
2147                         }
2148                         kn->kn_status |= KN_INFLUX;
2149                         KQ_UNLOCK(kq);
2150                         if (!(kn->kn_status & KN_DETACHED))
2151                                 kn->kn_fop->f_detach(kn);
2152                         knote_drop(kn, td);
2153                         influx = 1;
2154                         KQ_LOCK(kq);
2155                 }
2156                 KQ_UNLOCK_FLUX(kq);
2157         }
2158 }
2159
2160 static int
2161 knote_attach(struct knote *kn, struct kqueue *kq)
2162 {
2163         struct klist *list;
2164
2165         KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
2166         KQ_OWNED(kq);
2167
2168         if (kn->kn_fop->f_isfd) {
2169                 if (kn->kn_id >= kq->kq_knlistsize)
2170                         return ENOMEM;
2171                 list = &kq->kq_knlist[kn->kn_id];
2172         } else {
2173                 if (kq->kq_knhash == NULL)
2174                         return ENOMEM;
2175                 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2176         }
2177
2178         SLIST_INSERT_HEAD(list, kn, kn_link);
2179
2180         return 0;
2181 }
2182
2183 /*
2184  * knote must already have been detached using the f_detach method.
2185  * no lock need to be held, it is assumed that the KN_INFLUX flag is set
2186  * to prevent other removal.
2187  */
2188 static void
2189 knote_drop(struct knote *kn, struct thread *td)
2190 {
2191         struct kqueue *kq;
2192         struct klist *list;
2193
2194         kq = kn->kn_kq;
2195
2196         KQ_NOTOWNED(kq);
2197         KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
2198             ("knote_drop called without KN_INFLUX set in kn_status"));
2199
2200         KQ_LOCK(kq);
2201         if (kn->kn_fop->f_isfd)
2202                 list = &kq->kq_knlist[kn->kn_id];
2203         else
2204                 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2205
2206         if (!SLIST_EMPTY(list))
2207                 SLIST_REMOVE(list, kn, knote, kn_link);
2208         if (kn->kn_status & KN_QUEUED)
2209                 knote_dequeue(kn);
2210         KQ_UNLOCK_FLUX(kq);
2211
2212         if (kn->kn_fop->f_isfd) {
2213                 fdrop(kn->kn_fp, td);
2214                 kn->kn_fp = NULL;
2215         }
2216         kqueue_fo_release(kn->kn_kevent.filter);
2217         kn->kn_fop = NULL;
2218         knote_free(kn);
2219 }
2220
2221 static void
2222 knote_enqueue(struct knote *kn)
2223 {
2224         struct kqueue *kq = kn->kn_kq;
2225
2226         KQ_OWNED(kn->kn_kq);
2227         KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2228
2229         TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2230         kn->kn_status |= KN_QUEUED;
2231         kq->kq_count++;
2232         kqueue_wakeup(kq);
2233 }
2234
2235 static void
2236 knote_dequeue(struct knote *kn)
2237 {
2238         struct kqueue *kq = kn->kn_kq;
2239
2240         KQ_OWNED(kn->kn_kq);
2241         KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2242
2243         TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2244         kn->kn_status &= ~KN_QUEUED;
2245         kq->kq_count--;
2246 }
2247
2248 static void
2249 knote_init(void)
2250 {
2251
2252         knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2253             NULL, NULL, UMA_ALIGN_PTR, 0);
2254 }
2255 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2256
2257 static struct knote *
2258 knote_alloc(int waitok)
2259 {
2260         return ((struct knote *)uma_zalloc(knote_zone,
2261             (waitok ? M_WAITOK : M_NOWAIT)|M_ZERO));
2262 }
2263
2264 static void
2265 knote_free(struct knote *kn)
2266 {
2267         if (kn != NULL)
2268                 uma_zfree(knote_zone, kn);
2269 }
2270
2271 /*
2272  * Register the kev w/ the kq specified by fd.
2273  */
2274 int 
2275 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2276 {
2277         struct kqueue *kq;
2278         struct file *fp;
2279         cap_rights_t rights;
2280         int error;
2281
2282         error = fget(td, fd, cap_rights_init(&rights, CAP_POST_EVENT), &fp);
2283         if (error != 0)
2284                 return (error);
2285         if ((error = kqueue_acquire(fp, &kq)) != 0)
2286                 goto noacquire;
2287
2288         error = kqueue_register(kq, kev, td, waitok);
2289
2290         kqueue_release(kq, 0);
2291
2292 noacquire:
2293         fdrop(fp, td);
2294
2295         return error;
2296 }