]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/kern/kern_event.c
MFC r259609 (by se):
[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_SCAN)) == 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 #ifdef __LP64__
530         if (data > INT64_MAX / SBT_1MS)
531                 return INT64_MAX;
532 #endif
533         return (SBT_1MS * data);
534 }
535
536 static void
537 filt_timerexpire(void *knx)
538 {
539         struct callout *calloutp;
540         struct knote *kn;
541
542         kn = knx;
543         kn->kn_data++;
544         KNOTE_ACTIVATE(kn, 0);  /* XXX - handle locking */
545
546         if ((kn->kn_flags & EV_ONESHOT) != EV_ONESHOT) {
547                 calloutp = (struct callout *)kn->kn_hook;
548                 *kn->kn_ptr.p_nexttime += timer2sbintime(kn->kn_sdata);
549                 callout_reset_sbt_on(calloutp, *kn->kn_ptr.p_nexttime, 0,
550                     filt_timerexpire, kn, PCPU_GET(cpuid), C_ABSOLUTE);
551         }
552 }
553
554 /*
555  * data contains amount of time to sleep, in milliseconds
556  */
557 static int
558 filt_timerattach(struct knote *kn)
559 {
560         struct callout *calloutp;
561         sbintime_t to;
562         unsigned int ncallouts;
563
564         if ((intptr_t)kn->kn_sdata < 0)
565                 return (EINVAL);
566         if ((intptr_t)kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
567                 kn->kn_sdata = 1;
568         to = timer2sbintime(kn->kn_sdata);
569         if (to < 0)
570                 return (EINVAL);
571
572         ncallouts = atomic_load_explicit(&kq_ncallouts, memory_order_relaxed);
573         do {
574                 if (ncallouts >= kq_calloutmax)
575                         return (ENOMEM);
576         } while (!atomic_compare_exchange_weak_explicit(&kq_ncallouts,
577             &ncallouts, ncallouts + 1, memory_order_relaxed,
578             memory_order_relaxed));
579
580         kn->kn_flags |= EV_CLEAR;               /* automatically set */
581         kn->kn_status &= ~KN_DETACHED;          /* knlist_add clears it */
582         kn->kn_ptr.p_nexttime = malloc(sizeof(sbintime_t), M_KQUEUE, M_WAITOK);
583         calloutp = malloc(sizeof(*calloutp), M_KQUEUE, M_WAITOK);
584         callout_init(calloutp, CALLOUT_MPSAFE);
585         kn->kn_hook = calloutp;
586         *kn->kn_ptr.p_nexttime = to + sbinuptime();
587         callout_reset_sbt_on(calloutp, *kn->kn_ptr.p_nexttime, 0,
588             filt_timerexpire, kn, PCPU_GET(cpuid), C_ABSOLUTE);
589
590         return (0);
591 }
592
593 static void
594 filt_timerdetach(struct knote *kn)
595 {
596         struct callout *calloutp;
597         unsigned int old;
598
599         calloutp = (struct callout *)kn->kn_hook;
600         callout_drain(calloutp);
601         free(calloutp, M_KQUEUE);
602         free(kn->kn_ptr.p_nexttime, M_KQUEUE);
603         old = atomic_fetch_sub_explicit(&kq_ncallouts, 1, memory_order_relaxed);
604         KASSERT(old > 0, ("Number of callouts cannot become negative"));
605         kn->kn_status |= KN_DETACHED;   /* knlist_remove sets it */
606 }
607
608 static int
609 filt_timer(struct knote *kn, long hint)
610 {
611
612         return (kn->kn_data != 0);
613 }
614
615 static int
616 filt_userattach(struct knote *kn)
617 {
618
619         /* 
620          * EVFILT_USER knotes are not attached to anything in the kernel.
621          */ 
622         kn->kn_hook = NULL;
623         if (kn->kn_fflags & NOTE_TRIGGER)
624                 kn->kn_hookid = 1;
625         else
626                 kn->kn_hookid = 0;
627         return (0);
628 }
629
630 static void
631 filt_userdetach(__unused struct knote *kn)
632 {
633
634         /*
635          * EVFILT_USER knotes are not attached to anything in the kernel.
636          */
637 }
638
639 static int
640 filt_user(struct knote *kn, __unused long hint)
641 {
642
643         return (kn->kn_hookid);
644 }
645
646 static void
647 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
648 {
649         u_int ffctrl;
650
651         switch (type) {
652         case EVENT_REGISTER:
653                 if (kev->fflags & NOTE_TRIGGER)
654                         kn->kn_hookid = 1;
655
656                 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
657                 kev->fflags &= NOTE_FFLAGSMASK;
658                 switch (ffctrl) {
659                 case NOTE_FFNOP:
660                         break;
661
662                 case NOTE_FFAND:
663                         kn->kn_sfflags &= kev->fflags;
664                         break;
665
666                 case NOTE_FFOR:
667                         kn->kn_sfflags |= kev->fflags;
668                         break;
669
670                 case NOTE_FFCOPY:
671                         kn->kn_sfflags = kev->fflags;
672                         break;
673
674                 default:
675                         /* XXX Return error? */
676                         break;
677                 }
678                 kn->kn_sdata = kev->data;
679                 if (kev->flags & EV_CLEAR) {
680                         kn->kn_hookid = 0;
681                         kn->kn_data = 0;
682                         kn->kn_fflags = 0;
683                 }
684                 break;
685
686         case EVENT_PROCESS:
687                 *kev = kn->kn_kevent;
688                 kev->fflags = kn->kn_sfflags;
689                 kev->data = kn->kn_sdata;
690                 if (kn->kn_flags & EV_CLEAR) {
691                         kn->kn_hookid = 0;
692                         kn->kn_data = 0;
693                         kn->kn_fflags = 0;
694                 }
695                 break;
696
697         default:
698                 panic("filt_usertouch() - invalid type (%ld)", type);
699                 break;
700         }
701 }
702
703 int
704 sys_kqueue(struct thread *td, struct kqueue_args *uap)
705 {
706         struct filedesc *fdp;
707         struct kqueue *kq;
708         struct file *fp;
709         int fd, error;
710
711         fdp = td->td_proc->p_fd;
712         error = falloc(td, &fp, &fd, 0);
713         if (error)
714                 goto done2;
715
716         /* An extra reference on `fp' has been held for us by falloc(). */
717         kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
718         mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF|MTX_DUPOK);
719         TAILQ_INIT(&kq->kq_head);
720         kq->kq_fdp = fdp;
721         knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
722         TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
723
724         FILEDESC_XLOCK(fdp);
725         TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
726         FILEDESC_XUNLOCK(fdp);
727
728         finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
729         fdrop(fp, td);
730
731         td->td_retval[0] = fd;
732 done2:
733         return (error);
734 }
735
736 #ifndef _SYS_SYSPROTO_H_
737 struct kevent_args {
738         int     fd;
739         const struct kevent *changelist;
740         int     nchanges;
741         struct  kevent *eventlist;
742         int     nevents;
743         const struct timespec *timeout;
744 };
745 #endif
746 int
747 sys_kevent(struct thread *td, struct kevent_args *uap)
748 {
749         struct timespec ts, *tsp;
750         struct kevent_copyops k_ops = { uap,
751                                         kevent_copyout,
752                                         kevent_copyin};
753         int error;
754 #ifdef KTRACE
755         struct uio ktruio;
756         struct iovec ktriov;
757         struct uio *ktruioin = NULL;
758         struct uio *ktruioout = NULL;
759 #endif
760
761         if (uap->timeout != NULL) {
762                 error = copyin(uap->timeout, &ts, sizeof(ts));
763                 if (error)
764                         return (error);
765                 tsp = &ts;
766         } else
767                 tsp = NULL;
768
769 #ifdef KTRACE
770         if (KTRPOINT(td, KTR_GENIO)) {
771                 ktriov.iov_base = uap->changelist;
772                 ktriov.iov_len = uap->nchanges * sizeof(struct kevent);
773                 ktruio = (struct uio){ .uio_iov = &ktriov, .uio_iovcnt = 1,
774                     .uio_segflg = UIO_USERSPACE, .uio_rw = UIO_READ,
775                     .uio_td = td };
776                 ktruioin = cloneuio(&ktruio);
777                 ktriov.iov_base = uap->eventlist;
778                 ktriov.iov_len = uap->nevents * sizeof(struct kevent);
779                 ktruioout = cloneuio(&ktruio);
780         }
781 #endif
782
783         error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
784             &k_ops, tsp);
785
786 #ifdef KTRACE
787         if (ktruioin != NULL) {
788                 ktruioin->uio_resid = uap->nchanges * sizeof(struct kevent);
789                 ktrgenio(uap->fd, UIO_WRITE, ktruioin, 0);
790                 ktruioout->uio_resid = td->td_retval[0] * sizeof(struct kevent);
791                 ktrgenio(uap->fd, UIO_READ, ktruioout, error);
792         }
793 #endif
794
795         return (error);
796 }
797
798 /*
799  * Copy 'count' items into the destination list pointed to by uap->eventlist.
800  */
801 static int
802 kevent_copyout(void *arg, struct kevent *kevp, int count)
803 {
804         struct kevent_args *uap;
805         int error;
806
807         KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
808         uap = (struct kevent_args *)arg;
809
810         error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
811         if (error == 0)
812                 uap->eventlist += count;
813         return (error);
814 }
815
816 /*
817  * Copy 'count' items from the list pointed to by uap->changelist.
818  */
819 static int
820 kevent_copyin(void *arg, struct kevent *kevp, int count)
821 {
822         struct kevent_args *uap;
823         int error;
824
825         KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
826         uap = (struct kevent_args *)arg;
827
828         error = copyin(uap->changelist, kevp, count * sizeof *kevp);
829         if (error == 0)
830                 uap->changelist += count;
831         return (error);
832 }
833
834 int
835 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
836     struct kevent_copyops *k_ops, const struct timespec *timeout)
837 {
838         struct kevent keva[KQ_NEVENTS];
839         struct kevent *kevp, *changes;
840         struct kqueue *kq;
841         struct file *fp;
842         cap_rights_t rights;
843         int i, n, nerrors, error;
844
845         cap_rights_init(&rights);
846         if (nchanges > 0)
847                 cap_rights_set(&rights, CAP_KQUEUE_CHANGE);
848         if (nevents > 0)
849                 cap_rights_set(&rights, CAP_KQUEUE_EVENT);
850         error = fget(td, fd, &rights, &fp);
851         if (error != 0)
852                 return (error);
853
854         error = kqueue_acquire(fp, &kq);
855         if (error != 0)
856                 goto done_norel;
857
858         nerrors = 0;
859
860         while (nchanges > 0) {
861                 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
862                 error = k_ops->k_copyin(k_ops->arg, keva, n);
863                 if (error)
864                         goto done;
865                 changes = keva;
866                 for (i = 0; i < n; i++) {
867                         kevp = &changes[i];
868                         if (!kevp->filter)
869                                 continue;
870                         kevp->flags &= ~EV_SYSFLAGS;
871                         error = kqueue_register(kq, kevp, td, 1);
872                         if (error || (kevp->flags & EV_RECEIPT)) {
873                                 if (nevents != 0) {
874                                         kevp->flags = EV_ERROR;
875                                         kevp->data = error;
876                                         (void) k_ops->k_copyout(k_ops->arg,
877                                             kevp, 1);
878                                         nevents--;
879                                         nerrors++;
880                                 } else {
881                                         goto done;
882                                 }
883                         }
884                 }
885                 nchanges -= n;
886         }
887         if (nerrors) {
888                 td->td_retval[0] = nerrors;
889                 error = 0;
890                 goto done;
891         }
892
893         error = kqueue_scan(kq, nevents, k_ops, timeout, keva, td);
894 done:
895         kqueue_release(kq, 0);
896 done_norel:
897         fdrop(fp, td);
898         return (error);
899 }
900
901 int
902 kqueue_add_filteropts(int filt, struct filterops *filtops)
903 {
904         int error;
905
906         error = 0;
907         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
908                 printf(
909 "trying to add a filterop that is out of range: %d is beyond %d\n",
910                     ~filt, EVFILT_SYSCOUNT);
911                 return EINVAL;
912         }
913         mtx_lock(&filterops_lock);
914         if (sysfilt_ops[~filt].for_fop != &null_filtops &&
915             sysfilt_ops[~filt].for_fop != NULL)
916                 error = EEXIST;
917         else {
918                 sysfilt_ops[~filt].for_fop = filtops;
919                 sysfilt_ops[~filt].for_refcnt = 0;
920         }
921         mtx_unlock(&filterops_lock);
922
923         return (error);
924 }
925
926 int
927 kqueue_del_filteropts(int filt)
928 {
929         int error;
930
931         error = 0;
932         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
933                 return EINVAL;
934
935         mtx_lock(&filterops_lock);
936         if (sysfilt_ops[~filt].for_fop == &null_filtops ||
937             sysfilt_ops[~filt].for_fop == NULL)
938                 error = EINVAL;
939         else if (sysfilt_ops[~filt].for_refcnt != 0)
940                 error = EBUSY;
941         else {
942                 sysfilt_ops[~filt].for_fop = &null_filtops;
943                 sysfilt_ops[~filt].for_refcnt = 0;
944         }
945         mtx_unlock(&filterops_lock);
946
947         return error;
948 }
949
950 static struct filterops *
951 kqueue_fo_find(int filt)
952 {
953
954         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
955                 return NULL;
956
957         mtx_lock(&filterops_lock);
958         sysfilt_ops[~filt].for_refcnt++;
959         if (sysfilt_ops[~filt].for_fop == NULL)
960                 sysfilt_ops[~filt].for_fop = &null_filtops;
961         mtx_unlock(&filterops_lock);
962
963         return sysfilt_ops[~filt].for_fop;
964 }
965
966 static void
967 kqueue_fo_release(int filt)
968 {
969
970         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
971                 return;
972
973         mtx_lock(&filterops_lock);
974         KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
975             ("filter object refcount not valid on release"));
976         sysfilt_ops[~filt].for_refcnt--;
977         mtx_unlock(&filterops_lock);
978 }
979
980 /*
981  * A ref to kq (obtained via kqueue_acquire) must be held.  waitok will
982  * influence if memory allocation should wait.  Make sure it is 0 if you
983  * hold any mutexes.
984  */
985 static int
986 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
987 {
988         struct filterops *fops;
989         struct file *fp;
990         struct knote *kn, *tkn;
991         cap_rights_t rights;
992         int error, filt, event;
993         int haskqglobal, filedesc_unlock;
994
995         fp = NULL;
996         kn = NULL;
997         error = 0;
998         haskqglobal = 0;
999         filedesc_unlock = 0;
1000
1001         filt = kev->filter;
1002         fops = kqueue_fo_find(filt);
1003         if (fops == NULL)
1004                 return EINVAL;
1005
1006         tkn = knote_alloc(waitok);              /* prevent waiting with locks */
1007
1008 findkn:
1009         if (fops->f_isfd) {
1010                 KASSERT(td != NULL, ("td is NULL"));
1011                 error = fget(td, kev->ident,
1012                     cap_rights_init(&rights, CAP_EVENT), &fp);
1013                 if (error)
1014                         goto done;
1015
1016                 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1017                     kev->ident, 0) != 0) {
1018                         /* try again */
1019                         fdrop(fp, td);
1020                         fp = NULL;
1021                         error = kqueue_expand(kq, fops, kev->ident, waitok);
1022                         if (error)
1023                                 goto done;
1024                         goto findkn;
1025                 }
1026
1027                 if (fp->f_type == DTYPE_KQUEUE) {
1028                         /*
1029                          * if we add some inteligence about what we are doing,
1030                          * we should be able to support events on ourselves.
1031                          * We need to know when we are doing this to prevent
1032                          * getting both the knlist lock and the kq lock since
1033                          * they are the same thing.
1034                          */
1035                         if (fp->f_data == kq) {
1036                                 error = EINVAL;
1037                                 goto done;
1038                         }
1039
1040                         /*
1041                          * Pre-lock the filedesc before the global
1042                          * lock mutex, see the comment in
1043                          * kqueue_close().
1044                          */
1045                         FILEDESC_XLOCK(td->td_proc->p_fd);
1046                         filedesc_unlock = 1;
1047                         KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1048                 }
1049
1050                 KQ_LOCK(kq);
1051                 if (kev->ident < kq->kq_knlistsize) {
1052                         SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1053                                 if (kev->filter == kn->kn_filter)
1054                                         break;
1055                 }
1056         } else {
1057                 if ((kev->flags & EV_ADD) == EV_ADD)
1058                         kqueue_expand(kq, fops, kev->ident, waitok);
1059
1060                 KQ_LOCK(kq);
1061                 if (kq->kq_knhashmask != 0) {
1062                         struct klist *list;
1063
1064                         list = &kq->kq_knhash[
1065                             KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1066                         SLIST_FOREACH(kn, list, kn_link)
1067                                 if (kev->ident == kn->kn_id &&
1068                                     kev->filter == kn->kn_filter)
1069                                         break;
1070                 }
1071         }
1072
1073         /* knote is in the process of changing, wait for it to stablize. */
1074         if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1075                 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1076                 if (filedesc_unlock) {
1077                         FILEDESC_XUNLOCK(td->td_proc->p_fd);
1078                         filedesc_unlock = 0;
1079                 }
1080                 kq->kq_state |= KQ_FLUXWAIT;
1081                 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1082                 if (fp != NULL) {
1083                         fdrop(fp, td);
1084                         fp = NULL;
1085                 }
1086                 goto findkn;
1087         }
1088
1089         /*
1090          * kn now contains the matching knote, or NULL if no match
1091          */
1092         if (kn == NULL) {
1093                 if (kev->flags & EV_ADD) {
1094                         kn = tkn;
1095                         tkn = NULL;
1096                         if (kn == NULL) {
1097                                 KQ_UNLOCK(kq);
1098                                 error = ENOMEM;
1099                                 goto done;
1100                         }
1101                         kn->kn_fp = fp;
1102                         kn->kn_kq = kq;
1103                         kn->kn_fop = fops;
1104                         /*
1105                          * apply reference counts to knote structure, and
1106                          * do not release it at the end of this routine.
1107                          */
1108                         fops = NULL;
1109                         fp = NULL;
1110
1111                         kn->kn_sfflags = kev->fflags;
1112                         kn->kn_sdata = kev->data;
1113                         kev->fflags = 0;
1114                         kev->data = 0;
1115                         kn->kn_kevent = *kev;
1116                         kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1117                             EV_ENABLE | EV_DISABLE);
1118                         kn->kn_status = KN_INFLUX|KN_DETACHED;
1119
1120                         error = knote_attach(kn, kq);
1121                         KQ_UNLOCK(kq);
1122                         if (error != 0) {
1123                                 tkn = kn;
1124                                 goto done;
1125                         }
1126
1127                         if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1128                                 knote_drop(kn, td);
1129                                 goto done;
1130                         }
1131                         KN_LIST_LOCK(kn);
1132                         goto done_ev_add;
1133                 } else {
1134                         /* No matching knote and the EV_ADD flag is not set. */
1135                         KQ_UNLOCK(kq);
1136                         error = ENOENT;
1137                         goto done;
1138                 }
1139         }
1140         
1141         if (kev->flags & EV_DELETE) {
1142                 kn->kn_status |= KN_INFLUX;
1143                 KQ_UNLOCK(kq);
1144                 if (!(kn->kn_status & KN_DETACHED))
1145                         kn->kn_fop->f_detach(kn);
1146                 knote_drop(kn, td);
1147                 goto done;
1148         }
1149
1150         /*
1151          * The user may change some filter values after the initial EV_ADD,
1152          * but doing so will not reset any filter which has already been
1153          * triggered.
1154          */
1155         kn->kn_status |= KN_INFLUX | KN_SCAN;
1156         KQ_UNLOCK(kq);
1157         KN_LIST_LOCK(kn);
1158         kn->kn_kevent.udata = kev->udata;
1159         if (!fops->f_isfd && fops->f_touch != NULL) {
1160                 fops->f_touch(kn, kev, EVENT_REGISTER);
1161         } else {
1162                 kn->kn_sfflags = kev->fflags;
1163                 kn->kn_sdata = kev->data;
1164         }
1165
1166         /*
1167          * We can get here with kn->kn_knlist == NULL.  This can happen when
1168          * the initial attach event decides that the event is "completed" 
1169          * already.  i.e. filt_procattach is called on a zombie process.  It
1170          * will call filt_proc which will remove it from the list, and NULL
1171          * kn_knlist.
1172          */
1173 done_ev_add:
1174         event = kn->kn_fop->f_event(kn, 0);
1175         KQ_LOCK(kq);
1176         if (event)
1177                 KNOTE_ACTIVATE(kn, 1);
1178         kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1179         KN_LIST_UNLOCK(kn);
1180
1181         if ((kev->flags & EV_DISABLE) &&
1182             ((kn->kn_status & KN_DISABLED) == 0)) {
1183                 kn->kn_status |= KN_DISABLED;
1184         }
1185
1186         if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
1187                 kn->kn_status &= ~KN_DISABLED;
1188                 if ((kn->kn_status & KN_ACTIVE) &&
1189                     ((kn->kn_status & KN_QUEUED) == 0))
1190                         knote_enqueue(kn);
1191         }
1192         KQ_UNLOCK_FLUX(kq);
1193
1194 done:
1195         KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1196         if (filedesc_unlock)
1197                 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1198         if (fp != NULL)
1199                 fdrop(fp, td);
1200         if (tkn != NULL)
1201                 knote_free(tkn);
1202         if (fops != NULL)
1203                 kqueue_fo_release(filt);
1204         return (error);
1205 }
1206
1207 static int
1208 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1209 {
1210         int error;
1211         struct kqueue *kq;
1212
1213         error = 0;
1214
1215         kq = fp->f_data;
1216         if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1217                 return (EBADF);
1218         *kqp = kq;
1219         KQ_LOCK(kq);
1220         if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1221                 KQ_UNLOCK(kq);
1222                 return (EBADF);
1223         }
1224         kq->kq_refcnt++;
1225         KQ_UNLOCK(kq);
1226
1227         return error;
1228 }
1229
1230 static void
1231 kqueue_release(struct kqueue *kq, int locked)
1232 {
1233         if (locked)
1234                 KQ_OWNED(kq);
1235         else
1236                 KQ_LOCK(kq);
1237         kq->kq_refcnt--;
1238         if (kq->kq_refcnt == 1)
1239                 wakeup(&kq->kq_refcnt);
1240         if (!locked)
1241                 KQ_UNLOCK(kq);
1242 }
1243
1244 static void
1245 kqueue_schedtask(struct kqueue *kq)
1246 {
1247
1248         KQ_OWNED(kq);
1249         KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1250             ("scheduling kqueue task while draining"));
1251
1252         if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1253                 taskqueue_enqueue(taskqueue_kqueue, &kq->kq_task);
1254                 kq->kq_state |= KQ_TASKSCHED;
1255         }
1256 }
1257
1258 /*
1259  * Expand the kq to make sure we have storage for fops/ident pair.
1260  *
1261  * Return 0 on success (or no work necessary), return errno on failure.
1262  *
1263  * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1264  * If kqueue_register is called from a non-fd context, there usually/should
1265  * be no locks held.
1266  */
1267 static int
1268 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1269         int waitok)
1270 {
1271         struct klist *list, *tmp_knhash, *to_free;
1272         u_long tmp_knhashmask;
1273         int size;
1274         int fd;
1275         int mflag = waitok ? M_WAITOK : M_NOWAIT;
1276
1277         KQ_NOTOWNED(kq);
1278
1279         to_free = NULL;
1280         if (fops->f_isfd) {
1281                 fd = ident;
1282                 if (kq->kq_knlistsize <= fd) {
1283                         size = kq->kq_knlistsize;
1284                         while (size <= fd)
1285                                 size += KQEXTENT;
1286                         list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1287                         if (list == NULL)
1288                                 return ENOMEM;
1289                         KQ_LOCK(kq);
1290                         if (kq->kq_knlistsize > fd) {
1291                                 to_free = list;
1292                                 list = NULL;
1293                         } else {
1294                                 if (kq->kq_knlist != NULL) {
1295                                         bcopy(kq->kq_knlist, list,
1296                                             kq->kq_knlistsize * sizeof(*list));
1297                                         to_free = kq->kq_knlist;
1298                                         kq->kq_knlist = NULL;
1299                                 }
1300                                 bzero((caddr_t)list +
1301                                     kq->kq_knlistsize * sizeof(*list),
1302                                     (size - kq->kq_knlistsize) * sizeof(*list));
1303                                 kq->kq_knlistsize = size;
1304                                 kq->kq_knlist = list;
1305                         }
1306                         KQ_UNLOCK(kq);
1307                 }
1308         } else {
1309                 if (kq->kq_knhashmask == 0) {
1310                         tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1311                             &tmp_knhashmask);
1312                         if (tmp_knhash == NULL)
1313                                 return ENOMEM;
1314                         KQ_LOCK(kq);
1315                         if (kq->kq_knhashmask == 0) {
1316                                 kq->kq_knhash = tmp_knhash;
1317                                 kq->kq_knhashmask = tmp_knhashmask;
1318                         } else {
1319                                 to_free = tmp_knhash;
1320                         }
1321                         KQ_UNLOCK(kq);
1322                 }
1323         }
1324         free(to_free, M_KQUEUE);
1325
1326         KQ_NOTOWNED(kq);
1327         return 0;
1328 }
1329
1330 static void
1331 kqueue_task(void *arg, int pending)
1332 {
1333         struct kqueue *kq;
1334         int haskqglobal;
1335
1336         haskqglobal = 0;
1337         kq = arg;
1338
1339         KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1340         KQ_LOCK(kq);
1341
1342         KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1343
1344         kq->kq_state &= ~KQ_TASKSCHED;
1345         if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1346                 wakeup(&kq->kq_state);
1347         }
1348         KQ_UNLOCK(kq);
1349         KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1350 }
1351
1352 /*
1353  * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1354  * We treat KN_MARKER knotes as if they are INFLUX.
1355  */
1356 static int
1357 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1358     const struct timespec *tsp, struct kevent *keva, struct thread *td)
1359 {
1360         struct kevent *kevp;
1361         struct knote *kn, *marker;
1362         sbintime_t asbt, rsbt;
1363         int count, error, haskqglobal, influx, nkev, touch;
1364
1365         count = maxevents;
1366         nkev = 0;
1367         error = 0;
1368         haskqglobal = 0;
1369
1370         if (maxevents == 0)
1371                 goto done_nl;
1372
1373         rsbt = 0;
1374         if (tsp != NULL) {
1375                 if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1376                     tsp->tv_nsec >= 1000000000) {
1377                         error = EINVAL;
1378                         goto done_nl;
1379                 }
1380                 if (timespecisset(tsp)) {
1381                         if (tsp->tv_sec <= INT32_MAX) {
1382                                 rsbt = tstosbt(*tsp);
1383                                 if (TIMESEL(&asbt, rsbt))
1384                                         asbt += tc_tick_sbt;
1385                                 if (asbt <= INT64_MAX - rsbt)
1386                                         asbt += rsbt;
1387                                 else
1388                                         asbt = 0;
1389                                 rsbt >>= tc_precexp;
1390                         } else
1391                                 asbt = 0;
1392                 } else
1393                         asbt = -1;
1394         } else
1395                 asbt = 0;
1396         marker = knote_alloc(1);
1397         if (marker == NULL) {
1398                 error = ENOMEM;
1399                 goto done_nl;
1400         }
1401         marker->kn_status = KN_MARKER;
1402         KQ_LOCK(kq);
1403
1404 retry:
1405         kevp = keva;
1406         if (kq->kq_count == 0) {
1407                 if (asbt == -1) {
1408                         error = EWOULDBLOCK;
1409                 } else {
1410                         kq->kq_state |= KQ_SLEEP;
1411                         error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1412                             "kqread", asbt, rsbt, C_ABSOLUTE);
1413                 }
1414                 if (error == 0)
1415                         goto retry;
1416                 /* don't restart after signals... */
1417                 if (error == ERESTART)
1418                         error = EINTR;
1419                 else if (error == EWOULDBLOCK)
1420                         error = 0;
1421                 goto done;
1422         }
1423
1424         TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1425         influx = 0;
1426         while (count) {
1427                 KQ_OWNED(kq);
1428                 kn = TAILQ_FIRST(&kq->kq_head);
1429
1430                 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1431                     (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1432                         if (influx) {
1433                                 influx = 0;
1434                                 KQ_FLUX_WAKEUP(kq);
1435                         }
1436                         kq->kq_state |= KQ_FLUXWAIT;
1437                         error = msleep(kq, &kq->kq_lock, PSOCK,
1438                             "kqflxwt", 0);
1439                         continue;
1440                 }
1441
1442                 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1443                 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1444                         kn->kn_status &= ~KN_QUEUED;
1445                         kq->kq_count--;
1446                         continue;
1447                 }
1448                 if (kn == marker) {
1449                         KQ_FLUX_WAKEUP(kq);
1450                         if (count == maxevents)
1451                                 goto retry;
1452                         goto done;
1453                 }
1454                 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1455                     ("KN_INFLUX set when not suppose to be"));
1456
1457                 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
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                         if (!(kn->kn_status & KN_DETACHED))
1467                                 kn->kn_fop->f_detach(kn);
1468                         knote_drop(kn, td);
1469                         KQ_LOCK(kq);
1470                         continue;
1471                 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1472                         kn->kn_status &= ~KN_QUEUED;
1473                         kn->kn_status |= KN_INFLUX;
1474                         kq->kq_count--;
1475                         KQ_UNLOCK(kq);
1476                         /*
1477                          * We don't need to lock the list since we've marked
1478                          * it _INFLUX.
1479                          */
1480                         *kevp = kn->kn_kevent;
1481                         if (!(kn->kn_status & KN_DETACHED))
1482                                 kn->kn_fop->f_detach(kn);
1483                         knote_drop(kn, td);
1484                         KQ_LOCK(kq);
1485                         kn = NULL;
1486                 } else {
1487                         kn->kn_status |= KN_INFLUX | KN_SCAN;
1488                         KQ_UNLOCK(kq);
1489                         if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1490                                 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1491                         KN_LIST_LOCK(kn);
1492                         if (kn->kn_fop->f_event(kn, 0) == 0) {
1493                                 KQ_LOCK(kq);
1494                                 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1495                                 kn->kn_status &=
1496                                     ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX |
1497                                     KN_SCAN);
1498                                 kq->kq_count--;
1499                                 KN_LIST_UNLOCK(kn);
1500                                 influx = 1;
1501                                 continue;
1502                         }
1503                         touch = (!kn->kn_fop->f_isfd &&
1504                             kn->kn_fop->f_touch != NULL);
1505                         if (touch)
1506                                 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1507                         else
1508                                 *kevp = kn->kn_kevent;
1509                         KQ_LOCK(kq);
1510                         KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1511                         if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1512                                 /* 
1513                                  * Manually clear knotes who weren't 
1514                                  * 'touch'ed.
1515                                  */
1516                                 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1517                                         kn->kn_data = 0;
1518                                         kn->kn_fflags = 0;
1519                                 }
1520                                 if (kn->kn_flags & EV_DISPATCH)
1521                                         kn->kn_status |= KN_DISABLED;
1522                                 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1523                                 kq->kq_count--;
1524                         } else
1525                                 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1526                         
1527                         kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1528                         KN_LIST_UNLOCK(kn);
1529                         influx = 1;
1530                 }
1531
1532                 /* we are returning a copy to the user */
1533                 kevp++;
1534                 nkev++;
1535                 count--;
1536
1537                 if (nkev == KQ_NEVENTS) {
1538                         influx = 0;
1539                         KQ_UNLOCK_FLUX(kq);
1540                         error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1541                         nkev = 0;
1542                         kevp = keva;
1543                         KQ_LOCK(kq);
1544                         if (error)
1545                                 break;
1546                 }
1547         }
1548         TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1549 done:
1550         KQ_OWNED(kq);
1551         KQ_UNLOCK_FLUX(kq);
1552         knote_free(marker);
1553 done_nl:
1554         KQ_NOTOWNED(kq);
1555         if (nkev != 0)
1556                 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1557         td->td_retval[0] = maxevents - count;
1558         return (error);
1559 }
1560
1561 /*
1562  * XXX
1563  * This could be expanded to call kqueue_scan, if desired.
1564  */
1565 /*ARGSUSED*/
1566 static int
1567 kqueue_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
1568         int flags, struct thread *td)
1569 {
1570         return (ENXIO);
1571 }
1572
1573 /*ARGSUSED*/
1574 static int
1575 kqueue_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
1576          int flags, struct thread *td)
1577 {
1578         return (ENXIO);
1579 }
1580
1581 /*ARGSUSED*/
1582 static int
1583 kqueue_truncate(struct file *fp, off_t length, struct ucred *active_cred,
1584         struct thread *td)
1585 {
1586
1587         return (EINVAL);
1588 }
1589
1590 /*ARGSUSED*/
1591 static int
1592 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1593         struct ucred *active_cred, struct thread *td)
1594 {
1595         /*
1596          * Enabling sigio causes two major problems:
1597          * 1) infinite recursion:
1598          * Synopsys: kevent is being used to track signals and have FIOASYNC
1599          * set.  On receipt of a signal this will cause a kqueue to recurse
1600          * into itself over and over.  Sending the sigio causes the kqueue
1601          * to become ready, which in turn posts sigio again, forever.
1602          * Solution: this can be solved by setting a flag in the kqueue that
1603          * we have a SIGIO in progress.
1604          * 2) locking problems:
1605          * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1606          * us above the proc and pgrp locks.
1607          * Solution: Post a signal using an async mechanism, being sure to
1608          * record a generation count in the delivery so that we do not deliver
1609          * a signal to the wrong process.
1610          *
1611          * Note, these two mechanisms are somewhat mutually exclusive!
1612          */
1613 #if 0
1614         struct kqueue *kq;
1615
1616         kq = fp->f_data;
1617         switch (cmd) {
1618         case FIOASYNC:
1619                 if (*(int *)data) {
1620                         kq->kq_state |= KQ_ASYNC;
1621                 } else {
1622                         kq->kq_state &= ~KQ_ASYNC;
1623                 }
1624                 return (0);
1625
1626         case FIOSETOWN:
1627                 return (fsetown(*(int *)data, &kq->kq_sigio));
1628
1629         case FIOGETOWN:
1630                 *(int *)data = fgetown(&kq->kq_sigio);
1631                 return (0);
1632         }
1633 #endif
1634
1635         return (ENOTTY);
1636 }
1637
1638 /*ARGSUSED*/
1639 static int
1640 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1641         struct thread *td)
1642 {
1643         struct kqueue *kq;
1644         int revents = 0;
1645         int error;
1646
1647         if ((error = kqueue_acquire(fp, &kq)))
1648                 return POLLERR;
1649
1650         KQ_LOCK(kq);
1651         if (events & (POLLIN | POLLRDNORM)) {
1652                 if (kq->kq_count) {
1653                         revents |= events & (POLLIN | POLLRDNORM);
1654                 } else {
1655                         selrecord(td, &kq->kq_sel);
1656                         if (SEL_WAITING(&kq->kq_sel))
1657                                 kq->kq_state |= KQ_SEL;
1658                 }
1659         }
1660         kqueue_release(kq, 1);
1661         KQ_UNLOCK(kq);
1662         return (revents);
1663 }
1664
1665 /*ARGSUSED*/
1666 static int
1667 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1668         struct thread *td)
1669 {
1670
1671         bzero((void *)st, sizeof *st);
1672         /*
1673          * We no longer return kq_count because the unlocked value is useless.
1674          * If you spent all this time getting the count, why not spend your
1675          * syscall better by calling kevent?
1676          *
1677          * XXX - This is needed for libc_r.
1678          */
1679         st->st_mode = S_IFIFO;
1680         return (0);
1681 }
1682
1683 /*ARGSUSED*/
1684 static int
1685 kqueue_close(struct file *fp, struct thread *td)
1686 {
1687         struct kqueue *kq = fp->f_data;
1688         struct filedesc *fdp;
1689         struct knote *kn;
1690         int i;
1691         int error;
1692         int filedesc_unlock;
1693
1694         if ((error = kqueue_acquire(fp, &kq)))
1695                 return error;
1696
1697         filedesc_unlock = 0;
1698         KQ_LOCK(kq);
1699
1700         KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1701             ("kqueue already closing"));
1702         kq->kq_state |= KQ_CLOSING;
1703         if (kq->kq_refcnt > 1)
1704                 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1705
1706         KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1707         fdp = kq->kq_fdp;
1708
1709         KASSERT(knlist_empty(&kq->kq_sel.si_note),
1710             ("kqueue's knlist not empty"));
1711
1712         for (i = 0; i < kq->kq_knlistsize; i++) {
1713                 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1714                         if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1715                                 kq->kq_state |= KQ_FLUXWAIT;
1716                                 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
1717                                 continue;
1718                         }
1719                         kn->kn_status |= KN_INFLUX;
1720                         KQ_UNLOCK(kq);
1721                         if (!(kn->kn_status & KN_DETACHED))
1722                                 kn->kn_fop->f_detach(kn);
1723                         knote_drop(kn, td);
1724                         KQ_LOCK(kq);
1725                 }
1726         }
1727         if (kq->kq_knhashmask != 0) {
1728                 for (i = 0; i <= kq->kq_knhashmask; i++) {
1729                         while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1730                                 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1731                                         kq->kq_state |= KQ_FLUXWAIT;
1732                                         msleep(kq, &kq->kq_lock, PSOCK,
1733                                                "kqclo2", 0);
1734                                         continue;
1735                                 }
1736                                 kn->kn_status |= KN_INFLUX;
1737                                 KQ_UNLOCK(kq);
1738                                 if (!(kn->kn_status & KN_DETACHED))
1739                                         kn->kn_fop->f_detach(kn);
1740                                 knote_drop(kn, td);
1741                                 KQ_LOCK(kq);
1742                         }
1743                 }
1744         }
1745
1746         if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1747                 kq->kq_state |= KQ_TASKDRAIN;
1748                 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1749         }
1750
1751         if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1752                 selwakeuppri(&kq->kq_sel, PSOCK);
1753                 if (!SEL_WAITING(&kq->kq_sel))
1754                         kq->kq_state &= ~KQ_SEL;
1755         }
1756
1757         KQ_UNLOCK(kq);
1758
1759         /*
1760          * We could be called due to the knote_drop() doing fdrop(),
1761          * called from kqueue_register().  In this case the global
1762          * lock is owned, and filedesc sx is locked before, to not
1763          * take the sleepable lock after non-sleepable.
1764          */
1765         if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
1766                 FILEDESC_XLOCK(fdp);
1767                 filedesc_unlock = 1;
1768         } else
1769                 filedesc_unlock = 0;
1770         TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
1771         if (filedesc_unlock)
1772                 FILEDESC_XUNLOCK(fdp);
1773
1774         seldrain(&kq->kq_sel);
1775         knlist_destroy(&kq->kq_sel.si_note);
1776         mtx_destroy(&kq->kq_lock);
1777         kq->kq_fdp = NULL;
1778
1779         if (kq->kq_knhash != NULL)
1780                 free(kq->kq_knhash, M_KQUEUE);
1781         if (kq->kq_knlist != NULL)
1782                 free(kq->kq_knlist, M_KQUEUE);
1783
1784         funsetown(&kq->kq_sigio);
1785         free(kq, M_KQUEUE);
1786         fp->f_data = NULL;
1787
1788         return (0);
1789 }
1790
1791 static void
1792 kqueue_wakeup(struct kqueue *kq)
1793 {
1794         KQ_OWNED(kq);
1795
1796         if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
1797                 kq->kq_state &= ~KQ_SLEEP;
1798                 wakeup(kq);
1799         }
1800         if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1801                 selwakeuppri(&kq->kq_sel, PSOCK);
1802                 if (!SEL_WAITING(&kq->kq_sel))
1803                         kq->kq_state &= ~KQ_SEL;
1804         }
1805         if (!knlist_empty(&kq->kq_sel.si_note))
1806                 kqueue_schedtask(kq);
1807         if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
1808                 pgsigio(&kq->kq_sigio, SIGIO, 0);
1809         }
1810 }
1811
1812 /*
1813  * Walk down a list of knotes, activating them if their event has triggered.
1814  *
1815  * There is a possibility to optimize in the case of one kq watching another.
1816  * Instead of scheduling a task to wake it up, you could pass enough state
1817  * down the chain to make up the parent kqueue.  Make this code functional
1818  * first.
1819  */
1820 void
1821 knote(struct knlist *list, long hint, int lockflags)
1822 {
1823         struct kqueue *kq;
1824         struct knote *kn;
1825         int error;
1826
1827         if (list == NULL)
1828                 return;
1829
1830         KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
1831
1832         if ((lockflags & KNF_LISTLOCKED) == 0)
1833                 list->kl_lock(list->kl_lockarg); 
1834
1835         /*
1836          * If we unlock the list lock (and set KN_INFLUX), we can eliminate
1837          * the kqueue scheduling, but this will introduce four
1838          * lock/unlock's for each knote to test.  If we do, continue to use
1839          * SLIST_FOREACH, SLIST_FOREACH_SAFE is not safe in our case, it is
1840          * only safe if you want to remove the current item, which we are
1841          * not doing.
1842          */
1843         SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
1844                 kq = kn->kn_kq;
1845                 KQ_LOCK(kq);
1846                 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
1847                         /*
1848                          * Do not process the influx notes, except for
1849                          * the influx coming from the kq unlock in the
1850                          * kqueue_scan().  In the later case, we do
1851                          * not interfere with the scan, since the code
1852                          * fragment in kqueue_scan() locks the knlist,
1853                          * and cannot proceed until we finished.
1854                          */
1855                         KQ_UNLOCK(kq);
1856                 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
1857                         kn->kn_status |= KN_INFLUX;
1858                         KQ_UNLOCK(kq);
1859                         error = kn->kn_fop->f_event(kn, hint);
1860                         KQ_LOCK(kq);
1861                         kn->kn_status &= ~KN_INFLUX;
1862                         if (error)
1863                                 KNOTE_ACTIVATE(kn, 1);
1864                         KQ_UNLOCK_FLUX(kq);
1865                 } else {
1866                         kn->kn_status |= KN_HASKQLOCK;
1867                         if (kn->kn_fop->f_event(kn, hint))
1868                                 KNOTE_ACTIVATE(kn, 1);
1869                         kn->kn_status &= ~KN_HASKQLOCK;
1870                         KQ_UNLOCK(kq);
1871                 }
1872         }
1873         if ((lockflags & KNF_LISTLOCKED) == 0)
1874                 list->kl_unlock(list->kl_lockarg); 
1875 }
1876
1877 /*
1878  * add a knote to a knlist
1879  */
1880 void
1881 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
1882 {
1883         KNL_ASSERT_LOCK(knl, islocked);
1884         KQ_NOTOWNED(kn->kn_kq);
1885         KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
1886             (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
1887         if (!islocked)
1888                 knl->kl_lock(knl->kl_lockarg);
1889         SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
1890         if (!islocked)
1891                 knl->kl_unlock(knl->kl_lockarg);
1892         KQ_LOCK(kn->kn_kq);
1893         kn->kn_knlist = knl;
1894         kn->kn_status &= ~KN_DETACHED;
1895         KQ_UNLOCK(kn->kn_kq);
1896 }
1897
1898 static void
1899 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked, int kqislocked)
1900 {
1901         KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
1902         KNL_ASSERT_LOCK(knl, knlislocked);
1903         mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
1904         if (!kqislocked)
1905                 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
1906     ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
1907         if (!knlislocked)
1908                 knl->kl_lock(knl->kl_lockarg);
1909         SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
1910         kn->kn_knlist = NULL;
1911         if (!knlislocked)
1912                 knl->kl_unlock(knl->kl_lockarg);
1913         if (!kqislocked)
1914                 KQ_LOCK(kn->kn_kq);
1915         kn->kn_status |= KN_DETACHED;
1916         if (!kqislocked)
1917                 KQ_UNLOCK(kn->kn_kq);
1918 }
1919
1920 /*
1921  * remove knote from the specified knlist
1922  */
1923 void
1924 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
1925 {
1926
1927         knlist_remove_kq(knl, kn, islocked, 0);
1928 }
1929
1930 /*
1931  * remove knote from the specified knlist while in f_event handler.
1932  */
1933 void
1934 knlist_remove_inevent(struct knlist *knl, struct knote *kn)
1935 {
1936
1937         knlist_remove_kq(knl, kn, 1,
1938             (kn->kn_status & KN_HASKQLOCK) == KN_HASKQLOCK);
1939 }
1940
1941 int
1942 knlist_empty(struct knlist *knl)
1943 {
1944
1945         KNL_ASSERT_LOCKED(knl);
1946         return SLIST_EMPTY(&knl->kl_list);
1947 }
1948
1949 static struct mtx       knlist_lock;
1950 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
1951         MTX_DEF);
1952 static void knlist_mtx_lock(void *arg);
1953 static void knlist_mtx_unlock(void *arg);
1954
1955 static void
1956 knlist_mtx_lock(void *arg)
1957 {
1958
1959         mtx_lock((struct mtx *)arg);
1960 }
1961
1962 static void
1963 knlist_mtx_unlock(void *arg)
1964 {
1965
1966         mtx_unlock((struct mtx *)arg);
1967 }
1968
1969 static void
1970 knlist_mtx_assert_locked(void *arg)
1971 {
1972
1973         mtx_assert((struct mtx *)arg, MA_OWNED);
1974 }
1975
1976 static void
1977 knlist_mtx_assert_unlocked(void *arg)
1978 {
1979
1980         mtx_assert((struct mtx *)arg, MA_NOTOWNED);
1981 }
1982
1983 static void
1984 knlist_rw_rlock(void *arg)
1985 {
1986
1987         rw_rlock((struct rwlock *)arg);
1988 }
1989
1990 static void
1991 knlist_rw_runlock(void *arg)
1992 {
1993
1994         rw_runlock((struct rwlock *)arg);
1995 }
1996
1997 static void
1998 knlist_rw_assert_locked(void *arg)
1999 {
2000
2001         rw_assert((struct rwlock *)arg, RA_LOCKED);
2002 }
2003
2004 static void
2005 knlist_rw_assert_unlocked(void *arg)
2006 {
2007
2008         rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2009 }
2010
2011 void
2012 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2013     void (*kl_unlock)(void *),
2014     void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2015 {
2016
2017         if (lock == NULL)
2018                 knl->kl_lockarg = &knlist_lock;
2019         else
2020                 knl->kl_lockarg = lock;
2021
2022         if (kl_lock == NULL)
2023                 knl->kl_lock = knlist_mtx_lock;
2024         else
2025                 knl->kl_lock = kl_lock;
2026         if (kl_unlock == NULL)
2027                 knl->kl_unlock = knlist_mtx_unlock;
2028         else
2029                 knl->kl_unlock = kl_unlock;
2030         if (kl_assert_locked == NULL)
2031                 knl->kl_assert_locked = knlist_mtx_assert_locked;
2032         else
2033                 knl->kl_assert_locked = kl_assert_locked;
2034         if (kl_assert_unlocked == NULL)
2035                 knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2036         else
2037                 knl->kl_assert_unlocked = kl_assert_unlocked;
2038
2039         SLIST_INIT(&knl->kl_list);
2040 }
2041
2042 void
2043 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2044 {
2045
2046         knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2047 }
2048
2049 void
2050 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2051 {
2052
2053         knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2054             knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2055 }
2056
2057 void
2058 knlist_destroy(struct knlist *knl)
2059 {
2060
2061 #ifdef INVARIANTS
2062         /*
2063          * if we run across this error, we need to find the offending
2064          * driver and have it call knlist_clear or knlist_delete.
2065          */
2066         if (!SLIST_EMPTY(&knl->kl_list))
2067                 printf("WARNING: destroying knlist w/ knotes on it!\n");
2068 #endif
2069
2070         knl->kl_lockarg = knl->kl_lock = knl->kl_unlock = NULL;
2071         SLIST_INIT(&knl->kl_list);
2072 }
2073
2074 /*
2075  * Even if we are locked, we may need to drop the lock to allow any influx
2076  * knotes time to "settle".
2077  */
2078 void
2079 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2080 {
2081         struct knote *kn, *kn2;
2082         struct kqueue *kq;
2083
2084         if (islocked)
2085                 KNL_ASSERT_LOCKED(knl);
2086         else {
2087                 KNL_ASSERT_UNLOCKED(knl);
2088 again:          /* need to reacquire lock since we have dropped it */
2089                 knl->kl_lock(knl->kl_lockarg);
2090         }
2091
2092         SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2093                 kq = kn->kn_kq;
2094                 KQ_LOCK(kq);
2095                 if ((kn->kn_status & KN_INFLUX)) {
2096                         KQ_UNLOCK(kq);
2097                         continue;
2098                 }
2099                 knlist_remove_kq(knl, kn, 1, 1);
2100                 if (killkn) {
2101                         kn->kn_status |= KN_INFLUX | KN_DETACHED;
2102                         KQ_UNLOCK(kq);
2103                         knote_drop(kn, td);
2104                 } else {
2105                         /* Make sure cleared knotes disappear soon */
2106                         kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2107                         KQ_UNLOCK(kq);
2108                 }
2109                 kq = NULL;
2110         }
2111
2112         if (!SLIST_EMPTY(&knl->kl_list)) {
2113                 /* there are still KN_INFLUX remaining */
2114                 kn = SLIST_FIRST(&knl->kl_list);
2115                 kq = kn->kn_kq;
2116                 KQ_LOCK(kq);
2117                 KASSERT(kn->kn_status & KN_INFLUX,
2118                     ("knote removed w/o list lock"));
2119                 knl->kl_unlock(knl->kl_lockarg);
2120                 kq->kq_state |= KQ_FLUXWAIT;
2121                 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2122                 kq = NULL;
2123                 goto again;
2124         }
2125
2126         if (islocked)
2127                 KNL_ASSERT_LOCKED(knl);
2128         else {
2129                 knl->kl_unlock(knl->kl_lockarg);
2130                 KNL_ASSERT_UNLOCKED(knl);
2131         }
2132 }
2133
2134 /*
2135  * Remove all knotes referencing a specified fd must be called with FILEDESC
2136  * lock.  This prevents a race where a new fd comes along and occupies the
2137  * entry and we attach a knote to the fd.
2138  */
2139 void
2140 knote_fdclose(struct thread *td, int fd)
2141 {
2142         struct filedesc *fdp = td->td_proc->p_fd;
2143         struct kqueue *kq;
2144         struct knote *kn;
2145         int influx;
2146
2147         FILEDESC_XLOCK_ASSERT(fdp);
2148
2149         /*
2150          * We shouldn't have to worry about new kevents appearing on fd
2151          * since filedesc is locked.
2152          */
2153         TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2154                 KQ_LOCK(kq);
2155
2156 again:
2157                 influx = 0;
2158                 while (kq->kq_knlistsize > fd &&
2159                     (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2160                         if (kn->kn_status & KN_INFLUX) {
2161                                 /* someone else might be waiting on our knote */
2162                                 if (influx)
2163                                         wakeup(kq);
2164                                 kq->kq_state |= KQ_FLUXWAIT;
2165                                 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2166                                 goto again;
2167                         }
2168                         kn->kn_status |= KN_INFLUX;
2169                         KQ_UNLOCK(kq);
2170                         if (!(kn->kn_status & KN_DETACHED))
2171                                 kn->kn_fop->f_detach(kn);
2172                         knote_drop(kn, td);
2173                         influx = 1;
2174                         KQ_LOCK(kq);
2175                 }
2176                 KQ_UNLOCK_FLUX(kq);
2177         }
2178 }
2179
2180 static int
2181 knote_attach(struct knote *kn, struct kqueue *kq)
2182 {
2183         struct klist *list;
2184
2185         KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
2186         KQ_OWNED(kq);
2187
2188         if (kn->kn_fop->f_isfd) {
2189                 if (kn->kn_id >= kq->kq_knlistsize)
2190                         return ENOMEM;
2191                 list = &kq->kq_knlist[kn->kn_id];
2192         } else {
2193                 if (kq->kq_knhash == NULL)
2194                         return ENOMEM;
2195                 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2196         }
2197
2198         SLIST_INSERT_HEAD(list, kn, kn_link);
2199
2200         return 0;
2201 }
2202
2203 /*
2204  * knote must already have been detached using the f_detach method.
2205  * no lock need to be held, it is assumed that the KN_INFLUX flag is set
2206  * to prevent other removal.
2207  */
2208 static void
2209 knote_drop(struct knote *kn, struct thread *td)
2210 {
2211         struct kqueue *kq;
2212         struct klist *list;
2213
2214         kq = kn->kn_kq;
2215
2216         KQ_NOTOWNED(kq);
2217         KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
2218             ("knote_drop called without KN_INFLUX set in kn_status"));
2219
2220         KQ_LOCK(kq);
2221         if (kn->kn_fop->f_isfd)
2222                 list = &kq->kq_knlist[kn->kn_id];
2223         else
2224                 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2225
2226         if (!SLIST_EMPTY(list))
2227                 SLIST_REMOVE(list, kn, knote, kn_link);
2228         if (kn->kn_status & KN_QUEUED)
2229                 knote_dequeue(kn);
2230         KQ_UNLOCK_FLUX(kq);
2231
2232         if (kn->kn_fop->f_isfd) {
2233                 fdrop(kn->kn_fp, td);
2234                 kn->kn_fp = NULL;
2235         }
2236         kqueue_fo_release(kn->kn_kevent.filter);
2237         kn->kn_fop = NULL;
2238         knote_free(kn);
2239 }
2240
2241 static void
2242 knote_enqueue(struct knote *kn)
2243 {
2244         struct kqueue *kq = kn->kn_kq;
2245
2246         KQ_OWNED(kn->kn_kq);
2247         KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2248
2249         TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2250         kn->kn_status |= KN_QUEUED;
2251         kq->kq_count++;
2252         kqueue_wakeup(kq);
2253 }
2254
2255 static void
2256 knote_dequeue(struct knote *kn)
2257 {
2258         struct kqueue *kq = kn->kn_kq;
2259
2260         KQ_OWNED(kn->kn_kq);
2261         KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2262
2263         TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2264         kn->kn_status &= ~KN_QUEUED;
2265         kq->kq_count--;
2266 }
2267
2268 static void
2269 knote_init(void)
2270 {
2271
2272         knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2273             NULL, NULL, UMA_ALIGN_PTR, 0);
2274 }
2275 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2276
2277 static struct knote *
2278 knote_alloc(int waitok)
2279 {
2280         return ((struct knote *)uma_zalloc(knote_zone,
2281             (waitok ? M_WAITOK : M_NOWAIT)|M_ZERO));
2282 }
2283
2284 static void
2285 knote_free(struct knote *kn)
2286 {
2287         if (kn != NULL)
2288                 uma_zfree(knote_zone, kn);
2289 }
2290
2291 /*
2292  * Register the kev w/ the kq specified by fd.
2293  */
2294 int 
2295 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2296 {
2297         struct kqueue *kq;
2298         struct file *fp;
2299         cap_rights_t rights;
2300         int error;
2301
2302         error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2303         if (error != 0)
2304                 return (error);
2305         if ((error = kqueue_acquire(fp, &kq)) != 0)
2306                 goto noacquire;
2307
2308         error = kqueue_register(kq, kev, td, waitok);
2309
2310         kqueue_release(kq, 0);
2311
2312 noacquire:
2313         fdrop(fp, td);
2314
2315         return error;
2316 }