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