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