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