[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ]

FreeBSD/Linux Kernel Cross Reference
sys/kern/kern_event.c

Version: -  FREEBSD  -  FREEBSD7  -  FREEBSD70  -  FREEBSD6  -  FREEBSD63  -  FREEBSD62  -  FREEBSD61  -  FREEBSD60  -  FREEBSD5  -  FREEBSD55  -  FREEBSD54  -  FREEBSD53  -  FREEBSD52  -  FREEBSD51  -  FREEBSD50  -  FREEBSD4  -  FREEBSD3  -  linux-2.6  -  linux-2.4.22  -  MK83  -  MK84  -  PLAN9  -  DFBSD  -  NETBSD  -  NETBSD4  -  NETBSD3  -  NETBSD20  -  OPENBSD  -  xnu-517  -  xnu-792  -  xnu-792.6.70  -  xnu-1228  -  OPENSOLARIS  -  minix-3-1-1  -  TRUSTEDBSD-SEBSD  -  TRUSTEDBSD-SEDARWIN  -  TRUSTEDBSD-SEDARWIN7 
Ident_Mode: -  plain  -  excerpts  -  bigexcerpts 

  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: src/sys/kern/kern_event.c,v 1.122 2008/07/07 09:30:11 kib Exp $");
 30 
 31 #include "opt_ktrace.h"
 32 
 33 #include <sys/param.h>
 34 #include <sys/systm.h>
 35 #include <sys/kernel.h>
 36 #include <sys/lock.h>
 37 #include <sys/mutex.h>
 38 #include <sys/proc.h>
 39 #include <sys/malloc.h>
 40 #include <sys/unistd.h>
 41 #include <sys/file.h>
 42 #include <sys/filedesc.h>
 43 #include <sys/filio.h>
 44 #include <sys/fcntl.h>
 45 #include <sys/kthread.h>
 46 #include <sys/selinfo.h>
 47 #include <sys/queue.h>
 48 #include <sys/event.h>
 49 #include <sys/eventvar.h>
 50 #include <sys/poll.h>
 51 #include <sys/protosw.h>
 52 #include <sys/sigio.h>
 53 #include <sys/signalvar.h>
 54 #include <sys/socket.h>
 55 #include <sys/socketvar.h>
 56 #include <sys/stat.h>
 57 #include <sys/sysctl.h>
 58 #include <sys/sysproto.h>
 59 #include <sys/syscallsubr.h>
 60 #include <sys/taskqueue.h>
 61 #include <sys/uio.h>
 62 #ifdef KTRACE
 63 #include <sys/ktrace.h>
 64 #endif
 65 
 66 #include <vm/uma.h>
 67 
 68 static MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
 69 
 70 /*
 71  * This lock is used if multiple kq locks are required.  This possibly
 72  * should be made into a per proc lock.
 73  */
 74 static struct mtx       kq_global;
 75 MTX_SYSINIT(kq_global, &kq_global, "kqueue order", MTX_DEF);
 76 #define KQ_GLOBAL_LOCK(lck, haslck)     do {    \
 77         if (!haslck)                            \
 78                 mtx_lock(lck);                  \
 79         haslck = 1;                             \
 80 } while (0)
 81 #define KQ_GLOBAL_UNLOCK(lck, haslck)   do {    \
 82         if (haslck)                             \
 83                 mtx_unlock(lck);                        \
 84         haslck = 0;                             \
 85 } while (0)
 86 
 87 TASKQUEUE_DEFINE_THREAD(kqueue);
 88 
 89 static int      kevent_copyout(void *arg, struct kevent *kevp, int count);
 90 static int      kevent_copyin(void *arg, struct kevent *kevp, int count);
 91 static int      kqueue_register(struct kqueue *kq, struct kevent *kev,
 92                     struct thread *td, int waitok);
 93 static int      kqueue_acquire(struct file *fp, struct kqueue **kqp);
 94 static void     kqueue_release(struct kqueue *kq, int locked);
 95 static int      kqueue_expand(struct kqueue *kq, struct filterops *fops,
 96                     uintptr_t ident, int waitok);
 97 static void     kqueue_task(void *arg, int pending);
 98 static int      kqueue_scan(struct kqueue *kq, int maxevents,
 99                     struct kevent_copyops *k_ops,
100                     const struct timespec *timeout,
101                     struct kevent *keva, struct thread *td);
102 static void     kqueue_wakeup(struct kqueue *kq);
103 static struct filterops *kqueue_fo_find(int filt);
104 static void     kqueue_fo_release(int filt);
105 
106 static fo_rdwr_t        kqueue_read;
107 static fo_rdwr_t        kqueue_write;
108 static fo_truncate_t    kqueue_truncate;
109 static fo_ioctl_t       kqueue_ioctl;
110 static fo_poll_t        kqueue_poll;
111 static fo_kqfilter_t    kqueue_kqfilter;
112 static fo_stat_t        kqueue_stat;
113 static fo_close_t       kqueue_close;
114 
115 static struct fileops kqueueops = {
116         .fo_read = kqueue_read,
117         .fo_write = kqueue_write,
118         .fo_truncate = kqueue_truncate,
119         .fo_ioctl = kqueue_ioctl,
120         .fo_poll = kqueue_poll,
121         .fo_kqfilter = kqueue_kqfilter,
122         .fo_stat = kqueue_stat,
123         .fo_close = kqueue_close,
124 };
125 
126 static int      knote_attach(struct knote *kn, struct kqueue *kq);
127 static void     knote_drop(struct knote *kn, struct thread *td);
128 static void     knote_enqueue(struct knote *kn);
129 static void     knote_dequeue(struct knote *kn);
130 static void     knote_init(void);
131 static struct   knote *knote_alloc(int waitok);
132 static void     knote_free(struct knote *kn);
133 
134 static void     filt_kqdetach(struct knote *kn);
135 static int      filt_kqueue(struct knote *kn, long hint);
136 static int      filt_procattach(struct knote *kn);
137 static void     filt_procdetach(struct knote *kn);
138 static int      filt_proc(struct knote *kn, long hint);
139 static int      filt_fileattach(struct knote *kn);
140 static void     filt_timerexpire(void *knx);
141 static int      filt_timerattach(struct knote *kn);
142 static void     filt_timerdetach(struct knote *kn);
143 static int      filt_timer(struct knote *kn, long hint);
144 
145 static struct filterops file_filtops =
146         { 1, filt_fileattach, NULL, NULL };
147 static struct filterops kqread_filtops =
148         { 1, NULL, filt_kqdetach, filt_kqueue };
149 /* XXX - move to kern_proc.c?  */
150 static struct filterops proc_filtops =
151         { 0, filt_procattach, filt_procdetach, filt_proc };
152 static struct filterops timer_filtops =
153         { 0, filt_timerattach, filt_timerdetach, filt_timer };
154 
155 static uma_zone_t       knote_zone;
156 static int              kq_ncallouts = 0;
157 static int              kq_calloutmax = (4 * 1024);
158 SYSCTL_INT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
159     &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
160 
161 /* XXX - ensure not KN_INFLUX?? */
162 #define KNOTE_ACTIVATE(kn, islock) do {                                 \
163         if ((islock))                                                   \
164                 mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED);            \
165         else                                                            \
166                 KQ_LOCK((kn)->kn_kq);                                   \
167         (kn)->kn_status |= KN_ACTIVE;                                   \
168         if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0)         \
169                 knote_enqueue((kn));                                    \
170         if (!(islock))                                                  \
171                 KQ_UNLOCK((kn)->kn_kq);                                 \
172 } while(0)
173 #define KQ_LOCK(kq) do {                                                \
174         mtx_lock(&(kq)->kq_lock);                                       \
175 } while (0)
176 #define KQ_FLUX_WAKEUP(kq) do {                                         \
177         if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) {            \
178                 (kq)->kq_state &= ~KQ_FLUXWAIT;                         \
179                 wakeup((kq));                                           \
180         }                                                               \
181 } while (0)
182 #define KQ_UNLOCK_FLUX(kq) do {                                         \
183         KQ_FLUX_WAKEUP(kq);                                             \
184         mtx_unlock(&(kq)->kq_lock);                                     \
185 } while (0)
186 #define KQ_UNLOCK(kq) do {                                              \
187         mtx_unlock(&(kq)->kq_lock);                                     \
188 } while (0)
189 #define KQ_OWNED(kq) do {                                               \
190         mtx_assert(&(kq)->kq_lock, MA_OWNED);                           \
191 } while (0)
192 #define KQ_NOTOWNED(kq) do {                                            \
193         mtx_assert(&(kq)->kq_lock, MA_NOTOWNED);                        \
194 } while (0)
195 #define KN_LIST_LOCK(kn) do {                                           \
196         if (kn->kn_knlist != NULL)                                      \
197                 kn->kn_knlist->kl_lock(kn->kn_knlist->kl_lockarg);      \
198 } while (0)
199 #define KN_LIST_UNLOCK(kn) do {                                         \
200         if (kn->kn_knlist != NULL)                                      \
201                 kn->kn_knlist->kl_unlock(kn->kn_knlist->kl_lockarg);    \
202 } while (0)
203 #define KNL_ASSERT_LOCK(knl, islocked) do {                             \
204         if (islocked)                                                   \
205                 KNL_ASSERT_LOCKED(knl);                         \
206         else                                                            \
207                 KNL_ASSERT_UNLOCKED(knl);                               \
208 } while (0)
209 #ifdef INVARIANTS
210 #define KNL_ASSERT_LOCKED(knl) do {                                     \
211         if (!knl->kl_locked((knl)->kl_lockarg))                         \
212                         panic("knlist not locked, but should be");      \
213 } while (0)
214 #define KNL_ASSERT_UNLOCKED(knl) do {                           \
215         if (knl->kl_locked((knl)->kl_lockarg))                          \
216                 panic("knlist locked, but should not be");              \
217 } while (0)
218 #else /* !INVARIANTS */
219 #define KNL_ASSERT_LOCKED(knl) do {} while(0)
220 #define KNL_ASSERT_UNLOCKED(knl) do {} while (0)
221 #endif /* INVARIANTS */
222 
223 #define KN_HASHSIZE             64              /* XXX should be tunable */
224 #define KN_HASH(val, mask)      (((val) ^ (val >> 8)) & (mask))
225 
226 static int
227 filt_nullattach(struct knote *kn)
228 {
229 
230         return (ENXIO);
231 };
232 
233 struct filterops null_filtops =
234         { 0, filt_nullattach, NULL, NULL };
235 
236 /* XXX - make SYSINIT to add these, and move into respective modules. */
237 extern struct filterops sig_filtops;
238 extern struct filterops fs_filtops;
239 
240 /*
241  * Table for for all system-defined filters.
242  */
243 static struct mtx       filterops_lock;
244 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops",
245         MTX_DEF);
246 static struct {
247         struct filterops *for_fop;
248         int for_refcnt;
249 } sysfilt_ops[EVFILT_SYSCOUNT] = {
250         { &file_filtops },                      /* EVFILT_READ */
251         { &file_filtops },                      /* EVFILT_WRITE */
252         { &null_filtops },                      /* EVFILT_AIO */
253         { &file_filtops },                      /* EVFILT_VNODE */
254         { &proc_filtops },                      /* EVFILT_PROC */
255         { &sig_filtops },                       /* EVFILT_SIGNAL */
256         { &timer_filtops },                     /* EVFILT_TIMER */
257         { &file_filtops },                      /* EVFILT_NETDEV */
258         { &fs_filtops },                        /* EVFILT_FS */
259         { &null_filtops },                      /* EVFILT_LIO */
260 };
261 
262 /*
263  * Simple redirection for all cdevsw style objects to call their fo_kqfilter
264  * method.
265  */
266 static int
267 filt_fileattach(struct knote *kn)
268 {
269 
270         return (fo_kqfilter(kn->kn_fp, kn));
271 }
272 
273 /*ARGSUSED*/
274 static int
275 kqueue_kqfilter(struct file *fp, struct knote *kn)
276 {
277         struct kqueue *kq = kn->kn_fp->f_data;
278 
279         if (kn->kn_filter != EVFILT_READ)
280                 return (EINVAL);
281 
282         kn->kn_status |= KN_KQUEUE;
283         kn->kn_fop = &kqread_filtops;
284         knlist_add(&kq->kq_sel.si_note, kn, 0);
285 
286         return (0);
287 }
288 
289 static void
290 filt_kqdetach(struct knote *kn)
291 {
292         struct kqueue *kq = kn->kn_fp->f_data;
293 
294         knlist_remove(&kq->kq_sel.si_note, kn, 0);
295 }
296 
297 /*ARGSUSED*/
298 static int
299 filt_kqueue(struct knote *kn, long hint)
300 {
301         struct kqueue *kq = kn->kn_fp->f_data;
302 
303         kn->kn_data = kq->kq_count;
304         return (kn->kn_data > 0);
305 }
306 
307 /* XXX - move to kern_proc.c?  */
308 static int
309 filt_procattach(struct knote *kn)
310 {
311         struct proc *p;
312         int immediate;
313         int error;
314 
315         immediate = 0;
316         p = pfind(kn->kn_id);
317         if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
318                 p = zpfind(kn->kn_id);
319                 immediate = 1;
320         } else if (p != NULL && (p->p_flag & P_WEXIT)) {
321                 immediate = 1;
322         }
323 
324         if (p == NULL)
325                 return (ESRCH);
326         if ((error = p_cansee(curthread, p)))
327                 return (error);
328 
329         kn->kn_ptr.p_proc = p;
330         kn->kn_flags |= EV_CLEAR;               /* automatically set */
331 
332         /*
333          * internal flag indicating registration done by kernel
334          */
335         if (kn->kn_flags & EV_FLAG1) {
336                 kn->kn_data = kn->kn_sdata;             /* ppid */
337                 kn->kn_fflags = NOTE_CHILD;
338                 kn->kn_flags &= ~EV_FLAG1;
339         }
340 
341         if (immediate == 0)
342                 knlist_add(&p->p_klist, kn, 1);
343 
344         /*
345          * Immediately activate any exit notes if the target process is a
346          * zombie.  This is necessary to handle the case where the target
347          * process, e.g. a child, dies before the kevent is registered.
348          */
349         if (immediate && filt_proc(kn, NOTE_EXIT))
350                 KNOTE_ACTIVATE(kn, 0);
351 
352         PROC_UNLOCK(p);
353 
354         return (0);
355 }
356 
357 /*
358  * The knote may be attached to a different process, which may exit,
359  * leaving nothing for the knote to be attached to.  So when the process
360  * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
361  * it will be deleted when read out.  However, as part of the knote deletion,
362  * this routine is called, so a check is needed to avoid actually performing
363  * a detach, because the original process does not exist any more.
364  */
365 /* XXX - move to kern_proc.c?  */
366 static void
367 filt_procdetach(struct knote *kn)
368 {
369         struct proc *p;
370 
371         p = kn->kn_ptr.p_proc;
372         knlist_remove(&p->p_klist, kn, 0);
373         kn->kn_ptr.p_proc = NULL;
374 }
375 
376 /* XXX - move to kern_proc.c?  */
377 static int
378 filt_proc(struct knote *kn, long hint)
379 {
380         struct proc *p = kn->kn_ptr.p_proc;
381         u_int event;
382 
383         /*
384          * mask off extra data
385          */
386         event = (u_int)hint & NOTE_PCTRLMASK;
387 
388         /*
389          * if the user is interested in this event, record it.
390          */
391         if (kn->kn_sfflags & event)
392                 kn->kn_fflags |= event;
393 
394         /*
395          * process is gone, so flag the event as finished.
396          */
397         if (event == NOTE_EXIT) {
398                 if (!(kn->kn_status & KN_DETACHED))
399                         knlist_remove_inevent(&p->p_klist, kn);
400                 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
401                 kn->kn_data = p->p_xstat;
402                 kn->kn_ptr.p_proc = NULL;
403                 return (1);
404         }
405 
406         return (kn->kn_fflags != 0);
407 }
408 
409 /*
410  * Called when the process forked. It mostly does the same as the
411  * knote(), activating all knotes registered to be activated when the
412  * process forked. Additionally, for each knote attached to the
413  * parent, check whether user wants to track the new process. If so
414  * attach a new knote to it, and immediately report an event with the
415  * child's pid.
416  */
417 void
418 knote_fork(struct knlist *list, int pid)
419 {
420         struct kqueue *kq;
421         struct knote *kn;
422         struct kevent kev;
423         int error;
424 
425         if (list == NULL)
426                 return;
427         list->kl_lock(list->kl_lockarg);
428 
429         SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
430                 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX)
431                         continue;
432                 kq = kn->kn_kq;
433                 KQ_LOCK(kq);
434                 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
435                         KQ_UNLOCK(kq);
436                         continue;
437                 }
438 
439                 /*
440                  * The same as knote(), activate the event.
441                  */
442                 if ((kn->kn_sfflags & NOTE_TRACK) == 0) {
443                         kn->kn_status |= KN_HASKQLOCK;
444                         if (kn->kn_fop->f_event(kn, NOTE_FORK | pid))
445                                 KNOTE_ACTIVATE(kn, 1);
446                         kn->kn_status &= ~KN_HASKQLOCK;
447                         KQ_UNLOCK(kq);
448                         continue;
449                 }
450 
451                 /*
452                  * The NOTE_TRACK case. In addition to the activation
453                  * of the event, we need to register new event to
454                  * track the child. Drop the locks in preparation for
455                  * the call to kqueue_register().
456                  */
457                 kn->kn_status |= KN_INFLUX;
458                 KQ_UNLOCK(kq);
459                 list->kl_unlock(list->kl_lockarg);
460 
461                 /*
462                  * Activate existing knote and register a knote with
463                  * new process.
464                  */
465                 kev.ident = pid;
466                 kev.filter = kn->kn_filter;
467                 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
468                 kev.fflags = kn->kn_sfflags;
469                 kev.data = kn->kn_id;           /* parent */
470                 kev.udata = kn->kn_kevent.udata;/* preserve udata */
471                 error = kqueue_register(kq, &kev, NULL, 0);
472                 if (kn->kn_fop->f_event(kn, NOTE_FORK | pid))
473                         KNOTE_ACTIVATE(kn, 0);
474                 if (error)
475                         kn->kn_fflags |= NOTE_TRACKERR;
476                 KQ_LOCK(kq);
477                 kn->kn_status &= ~KN_INFLUX;
478                 KQ_UNLOCK_FLUX(kq);
479                 list->kl_lock(list->kl_lockarg);
480         }
481         list->kl_unlock(list->kl_lockarg);
482 }
483 
484 static int
485 timertoticks(intptr_t data)
486 {
487         struct timeval tv;
488         int tticks;
489 
490         tv.tv_sec = data / 1000;
491         tv.tv_usec = (data % 1000) * 1000;
492         tticks = tvtohz(&tv);
493 
494         return tticks;
495 }
496 
497 /* XXX - move to kern_timeout.c? */
498 static void
499 filt_timerexpire(void *knx)
500 {
501         struct knote *kn = knx;
502         struct callout *calloutp;
503 
504         kn->kn_data++;
505         KNOTE_ACTIVATE(kn, 0);  /* XXX - handle locking */
506 
507         if ((kn->kn_flags & EV_ONESHOT) != EV_ONESHOT) {
508                 calloutp = (struct callout *)kn->kn_hook;
509                 callout_reset_curcpu(calloutp, timertoticks(kn->kn_sdata),
510                     filt_timerexpire, kn);
511         }
512 }
513 
514 /*
515  * data contains amount of time to sleep, in milliseconds
516  */
517 /* XXX - move to kern_timeout.c? */
518 static int
519 filt_timerattach(struct knote *kn)
520 {
521         struct callout *calloutp;
522 
523         atomic_add_int(&kq_ncallouts, 1);
524 
525         if (kq_ncallouts >= kq_calloutmax) {
526                 atomic_add_int(&kq_ncallouts, -1);
527                 return (ENOMEM);
528         }
529 
530         kn->kn_flags |= EV_CLEAR;               /* automatically set */
531         kn->kn_status &= ~KN_DETACHED;          /* knlist_add usually sets it */
532         MALLOC(calloutp, struct callout *, sizeof(*calloutp),
533             M_KQUEUE, M_WAITOK);
534         callout_init(calloutp, CALLOUT_MPSAFE);
535         kn->kn_hook = calloutp;
536         callout_reset_curcpu(calloutp, timertoticks(kn->kn_sdata),
537             filt_timerexpire, kn);
538 
539         return (0);
540 }
541 
542 /* XXX - move to kern_timeout.c? */
543 static void
544 filt_timerdetach(struct knote *kn)
545 {
546         struct callout *calloutp;
547 
548         calloutp = (struct callout *)kn->kn_hook;
549         callout_drain(calloutp);
550         FREE(calloutp, M_KQUEUE);
551         atomic_add_int(&kq_ncallouts, -1);
552         kn->kn_status |= KN_DETACHED;   /* knlist_remove usually clears it */
553 }
554 
555 /* XXX - move to kern_timeout.c? */
556 static int
557 filt_timer(struct knote *kn, long hint)
558 {
559 
560         return (kn->kn_data != 0);
561 }
562 
563 int
564 kqueue(struct thread *td, struct kqueue_args *uap)
565 {
566         struct filedesc *fdp;
567         struct kqueue *kq;
568         struct file *fp;
569         int fd, error;
570 
571         fdp = td->td_proc->p_fd;
572         error = falloc(td, &fp, &fd);
573         if (error)
574                 goto done2;
575 
576         /* An extra reference on `nfp' has been held for us by falloc(). */
577         kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
578         mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF|MTX_DUPOK);
579         TAILQ_INIT(&kq->kq_head);
580         kq->kq_fdp = fdp;
581         knlist_init(&kq->kq_sel.si_note, &kq->kq_lock, NULL, NULL, NULL);
582         TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
583 
584         FILEDESC_XLOCK(fdp);
585         SLIST_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
586         FILEDESC_XUNLOCK(fdp);
587 
588         finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
589         fdrop(fp, td);
590 
591         td->td_retval[0] = fd;
592 done2:
593         return (error);
594 }
595 
596 #ifndef _SYS_SYSPROTO_H_
597 struct kevent_args {
598         int     fd;
599         const struct kevent *changelist;
600         int     nchanges;
601         struct  kevent *eventlist;
602         int     nevents;
603         const struct timespec *timeout;
604 };
605 #endif
606 int
607 kevent(struct thread *td, struct kevent_args *uap)
608 {
609         struct timespec ts, *tsp;
610         struct kevent_copyops k_ops = { uap,
611                                         kevent_copyout,
612                                         kevent_copyin};
613         int error;
614 #ifdef KTRACE
615         struct uio ktruio;
616         struct iovec ktriov;
617         struct uio *ktruioin = NULL;
618         struct uio *ktruioout = NULL;
619 #endif
620 
621         if (uap->timeout != NULL) {
622                 error = copyin(uap->timeout, &ts, sizeof(ts));
623                 if (error)
624                         return (error);
625                 tsp = &ts;
626         } else
627                 tsp = NULL;
628 
629 #ifdef KTRACE
630         if (KTRPOINT(td, KTR_GENIO)) {
631                 ktriov.iov_base = uap->changelist;
632                 ktriov.iov_len = uap->nchanges * sizeof(struct kevent);
633                 ktruio = (struct uio){ .uio_iov = &ktriov, .uio_iovcnt = 1,
634                     .uio_segflg = UIO_USERSPACE, .uio_rw = UIO_READ,
635                     .uio_td = td };
636                 ktruioin = cloneuio(&ktruio);
637                 ktriov.iov_base = uap->eventlist;
638                 ktriov.iov_len = uap->nevents * sizeof(struct kevent);
639                 ktruioout = cloneuio(&ktruio);
640         }
641 #endif
642 
643         error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
644             &k_ops, tsp);
645 
646 #ifdef KTRACE
647         if (ktruioin != NULL) {
648                 ktruioin->uio_resid = uap->nchanges * sizeof(struct kevent);
649                 ktrgenio(uap->fd, UIO_WRITE, ktruioin, 0);
650                 ktruioout->uio_resid = td->td_retval[0] * sizeof(struct kevent);
651                 ktrgenio(uap->fd, UIO_READ, ktruioout, error);
652         }
653 #endif
654 
655         return (error);
656 }
657 
658 /*
659  * Copy 'count' items into the destination list pointed to by uap->eventlist.
660  */
661 static int
662 kevent_copyout(void *arg, struct kevent *kevp, int count)
663 {
664         struct kevent_args *uap;
665         int error;
666 
667         KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
668         uap = (struct kevent_args *)arg;
669 
670         error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
671         if (error == 0)
672                 uap->eventlist += count;
673         return (error);
674 }
675 
676 /*
677  * Copy 'count' items from the list pointed to by uap->changelist.
678  */
679 static int
680 kevent_copyin(void *arg, struct kevent *kevp, int count)
681 {
682         struct kevent_args *uap;
683         int error;
684 
685         KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
686         uap = (struct kevent_args *)arg;
687 
688         error = copyin(uap->changelist, kevp, count * sizeof *kevp);
689         if (error == 0)
690                 uap->changelist += count;
691         return (error);
692 }
693 
694 int
695 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
696     struct kevent_copyops *k_ops, const struct timespec *timeout)
697 {
698         struct kevent keva[KQ_NEVENTS];
699         struct kevent *kevp, *changes;
700         struct kqueue *kq;
701         struct file *fp;
702         int i, n, nerrors, error;
703 
704         if ((error = fget(td, fd, &fp)) != 0)
705                 return (error);
706         if ((error = kqueue_acquire(fp, &kq)) != 0)
707                 goto done_norel;
708 
709         nerrors = 0;
710 
711         while (nchanges > 0) {
712                 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
713                 error = k_ops->k_copyin(k_ops->arg, keva, n);
714                 if (error)
715                         goto done;
716                 changes = keva;
717                 for (i = 0; i < n; i++) {
718                         kevp = &changes[i];
719                         if (!kevp->filter)
720                                 continue;
721                         kevp->flags &= ~EV_SYSFLAGS;
722                         error = kqueue_register(kq, kevp, td, 1);
723                         if (error) {
724                                 if (nevents != 0) {
725                                         kevp->flags = EV_ERROR;
726                                         kevp->data = error;
727                                         (void) k_ops->k_copyout(k_ops->arg,
728                                             kevp, 1);
729                                         nevents--;
730                                         nerrors++;
731                                 } else {
732                                         goto done;
733                                 }
734                         }
735                 }
736                 nchanges -= n;
737         }
738         if (nerrors) {
739                 td->td_retval[0] = nerrors;
740                 error = 0;
741                 goto done;
742         }
743 
744         error = kqueue_scan(kq, nevents, k_ops, timeout, keva, td);
745 done:
746         kqueue_release(kq, 0);
747 done_norel:
748         fdrop(fp, td);
749         return (error);
750 }
751 
752 int
753 kqueue_add_filteropts(int filt, struct filterops *filtops)
754 {
755         int error;
756 
757         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
758                 printf(
759 "trying to add a filterop that is out of range: %d is beyond %d\n",
760                     ~filt, EVFILT_SYSCOUNT);
761                 return EINVAL;
762         }
763         mtx_lock(&filterops_lock);
764         if (sysfilt_ops[~filt].for_fop != &null_filtops &&
765             sysfilt_ops[~filt].for_fop != NULL)
766                 error = EEXIST;
767         else {
768                 sysfilt_ops[~filt].for_fop = filtops;
769                 sysfilt_ops[~filt].for_refcnt = 0;
770         }
771         mtx_unlock(&filterops_lock);
772 
773         return (0);
774 }
775 
776 int
777 kqueue_del_filteropts(int filt)
778 {
779         int error;
780 
781         error = 0;
782         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
783                 return EINVAL;
784 
785         mtx_lock(&filterops_lock);
786         if (sysfilt_ops[~filt].for_fop == &null_filtops ||
787             sysfilt_ops[~filt].for_fop == NULL)
788                 error = EINVAL;
789         else if (sysfilt_ops[~filt].for_refcnt != 0)
790                 error = EBUSY;
791         else {
792                 sysfilt_ops[~filt].for_fop = &null_filtops;
793                 sysfilt_ops[~filt].for_refcnt = 0;
794         }
795         mtx_unlock(&filterops_lock);
796 
797         return error;
798 }
799 
800 static struct filterops *
801 kqueue_fo_find(int filt)
802 {
803 
804         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
805                 return NULL;
806 
807         mtx_lock(&filterops_lock);
808         sysfilt_ops[~filt].for_refcnt++;
809         if (sysfilt_ops[~filt].for_fop == NULL)
810                 sysfilt_ops[~filt].for_fop = &null_filtops;
811         mtx_unlock(&filterops_lock);
812 
813         return sysfilt_ops[~filt].for_fop;
814 }
815 
816 static void
817 kqueue_fo_release(int filt)
818 {
819 
820         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
821                 return;
822 
823         mtx_lock(&filterops_lock);
824         KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
825             ("filter object refcount not valid on release"));
826         sysfilt_ops[~filt].for_refcnt--;
827         mtx_unlock(&filterops_lock);
828 }
829 
830 /*
831  * A ref to kq (obtained via kqueue_acquire) must be held.  waitok will
832  * influence if memory allocation should wait.  Make sure it is 0 if you
833  * hold any mutexes.
834  */
835 static int
836 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
837 {
838         struct filterops *fops;
839         struct file *fp;
840         struct knote *kn, *tkn;
841         int error, filt, event;
842         int haskqglobal;
843 
844         fp = NULL;
845         kn = NULL;
846         error = 0;
847         haskqglobal = 0;
848 
849         filt = kev->filter;
850         fops = kqueue_fo_find(filt);
851         if (fops == NULL)
852                 return EINVAL;
853 
854         tkn = knote_alloc(waitok);              /* prevent waiting with locks */
855 
856 findkn:
857         if (fops->f_isfd) {
858                 KASSERT(td != NULL, ("td is NULL"));
859                 error = fget(td, kev->ident, &fp);
860                 if (error)
861                         goto done;
862 
863                 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
864                     kev->ident, 0) != 0) {
865                         /* try again */
866                         fdrop(fp, td);
867                         fp = NULL;
868                         error = kqueue_expand(kq, fops, kev->ident, waitok);
869                         if (error)
870                                 goto done;
871                         goto findkn;
872                 }
873 
874                 if (fp->f_type == DTYPE_KQUEUE) {
875                         /*
876                          * if we add some inteligence about what we are doing,
877                          * we should be able to support events on ourselves.
878                          * We need to know when we are doing this to prevent
879                          * getting both the knlist lock and the kq lock since
880                          * they are the same thing.
881                          */
882                         if (fp->f_data == kq) {
883                                 error = EINVAL;
884                                 goto done;
885                         }
886 
887                         KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
888                 }
889 
890                 KQ_LOCK(kq);
891                 if (kev->ident < kq->kq_knlistsize) {
892                         SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
893                                 if (kev->filter == kn->kn_filter)
894                                         break;
895                 }
896         } else {
897                 if ((kev->flags & EV_ADD) == EV_ADD)
898                         kqueue_expand(kq, fops, kev->ident, waitok);
899 
900                 KQ_LOCK(kq);
901                 if (kq->kq_knhashmask != 0) {
902                         struct klist *list;
903 
904                         list = &kq->kq_knhash[
905                             KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
906                         SLIST_FOREACH(kn, list, kn_link)
907                                 if (kev->ident == kn->kn_id &&
908                                     kev->filter == kn->kn_filter)
909                                         break;
910                 }
911         }
912 
913         /* knote is in the process of changing, wait for it to stablize. */
914         if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
915                 if (fp != NULL) {
916                         fdrop(fp, td);
917                         fp = NULL;
918                 }
919                 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
920                 kq->kq_state |= KQ_FLUXWAIT;
921                 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
922                 goto findkn;
923         }
924 
925         if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
926                 KQ_UNLOCK(kq);
927                 error = ENOENT;
928                 goto done;
929         }
930 
931         /*
932          * kn now contains the matching knote, or NULL if no match
933          */
934         if (kev->flags & EV_ADD) {
935                 if (kn == NULL) {
936                         kn = tkn;
937                         tkn = NULL;
938                         if (kn == NULL) {
939                                 KQ_UNLOCK(kq);
940                                 error = ENOMEM;
941                                 goto done;
942                         }
943                         kn->kn_fp = fp;
944                         kn->kn_kq = kq;
945                         kn->kn_fop = fops;
946                         /*
947                          * apply reference counts to knote structure, and
948                          * do not release it at the end of this routine.
949                          */
950                         fops = NULL;
951                         fp = NULL;
952 
953                         kn->kn_sfflags = kev->fflags;
954                         kn->kn_sdata = kev->data;
955                         kev->fflags = 0;
956                         kev->data = 0;
957                         kn->kn_kevent = *kev;
958                         kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
959                             EV_ENABLE | EV_DISABLE);
960                         kn->kn_status = KN_INFLUX|KN_DETACHED;
961 
962                         error = knote_attach(kn, kq);
963                         KQ_UNLOCK(kq);
964                         if (error != 0) {
965                                 tkn = kn;
966                                 goto done;
967                         }
968 
969                         if ((error = kn->kn_fop->f_attach(kn)) != 0) {
970                                 knote_drop(kn, td);
971                                 goto done;
972                         }
973                         KN_LIST_LOCK(kn);
974                 } else {
975                         /*
976                          * The user may change some filter values after the
977                          * initial EV_ADD, but doing so will not reset any
978                          * filter which has already been triggered.
979                          */
980                         kn->kn_status |= KN_INFLUX;
981                         KQ_UNLOCK(kq);
982                         KN_LIST_LOCK(kn);
983                         kn->kn_sfflags = kev->fflags;
984                         kn->kn_sdata = kev->data;
985                         kn->kn_kevent.udata = kev->udata;
986                 }
987 
988                 /*
989                  * We can get here with kn->kn_knlist == NULL.
990                  * This can happen when the initial attach event decides that