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