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