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