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