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