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