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