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