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