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