]> git.saurik.com Git - apple/xnu.git/blobdiff - bsd/kern/kern_event.c
xnu-2782.40.9.tar.gz
[apple/xnu.git] / bsd / kern / kern_event.c
index ee3d66b09df04f6113ca0ba45aaf7e0dc9a1a7c1..708aef4747ad4ddd1bbeef79d7c7fdf43cedaa9f 100644 (file)
@@ -1,8 +1,8 @@
 /*
 /*
- * Copyright (c) 2000-2011 Apple Inc. All rights reserved.
+ * Copyright (c) 2000-2014 Apple Inc. All rights reserved.
  *
  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
  *
  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
- * 
+ *
  * This file contains Original Code and/or Modifications of Original Code
  * as defined in and that are subject to the Apple Public Source License
  * Version 2.0 (the 'License'). You may not use this file except in
  * This file contains Original Code and/or Modifications of Original Code
  * as defined in and that are subject to the Apple Public Source License
  * Version 2.0 (the 'License'). You may not use this file except in
  * unlawful or unlicensed copies of an Apple operating system, or to
  * circumvent, violate, or enable the circumvention or violation of, any
  * terms of an Apple operating system software license agreement.
  * unlawful or unlicensed copies of an Apple operating system, or to
  * circumvent, violate, or enable the circumvention or violation of, any
  * terms of an Apple operating system software license agreement.
- * 
+ *
  * Please obtain a copy of the License at
  * http://www.opensource.apple.com/apsl/ and read it before using this file.
  * Please obtain a copy of the License at
  * http://www.opensource.apple.com/apsl/ and read it before using this file.
- * 
+ *
  * The Original Code and all software distributed under the License are
  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
  * The Original Code and all software distributed under the License are
  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
@@ -22,7 +22,7 @@
  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
  * Please see the License for the specific language governing rights and
  * limitations under the License.
  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
  * Please see the License for the specific language governing rights and
  * limitations under the License.
- * 
+ *
  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
  *
  */
  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
  *
  */
@@ -62,7 +62,7 @@
 #include <sys/kernel.h>
 #include <sys/proc_internal.h>
 #include <sys/kauth.h>
 #include <sys/kernel.h>
 #include <sys/proc_internal.h>
 #include <sys/kauth.h>
-#include <sys/malloc.h> 
+#include <sys/malloc.h>
 #include <sys/unistd.h>
 #include <sys/file_internal.h>
 #include <sys/fcntl.h>
 #include <sys/unistd.h>
 #include <sys/file_internal.h>
 #include <sys/fcntl.h>
 #include <sys/vnode_internal.h>
 #include <string.h>
 #include <sys/proc_info.h>
 #include <sys/vnode_internal.h>
 #include <string.h>
 #include <sys/proc_info.h>
+#include <sys/codesign.h>
 
 
-#include <kern/lock.h>
+#include <kern/locks.h>
 #include <kern/clock.h>
 #include <kern/thread_call.h>
 #include <kern/sched_prim.h>
 #include <kern/clock.h>
 #include <kern/thread_call.h>
 #include <kern/sched_prim.h>
+#include <kern/wait_queue.h>
 #include <kern/zalloc.h>
 #include <kern/assert.h>
 
 #include <kern/zalloc.h>
 #include <kern/assert.h>
 
 #include <kern/vm_pressure.h>
 #endif
 
 #include <kern/vm_pressure.h>
 #endif
 
+#if CONFIG_MEMORYSTATUS
+#include <sys/kern_memorystatus.h>
+#endif
+
 MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
 
 MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
 
-#define KQ_EVENT NULL
+#define        KQ_EVENT        NULL
 
 static inline void kqlock(struct kqueue *kq);
 static inline void kqunlock(struct kqueue *kq);
 
 
 static inline void kqlock(struct kqueue *kq);
 static inline void kqunlock(struct kqueue *kq);
 
-static int     kqlock2knoteuse(struct kqueue *kq, struct knote *kn);
-static int     kqlock2knoteusewait(struct kqueue *kq, struct knote *kn);
-static int     kqlock2knotedrop(struct kqueue *kq, struct knote *kn);
-static int     knoteuse2kqlock(struct kqueue *kq, struct knote *kn);
-
-static void    kqueue_wakeup(struct kqueue *kq, int closed);
-static int     kqueue_read(struct fileproc *fp, struct uio *uio,
-                   int flags, vfs_context_t ctx);
-static int     kqueue_write(struct fileproc *fp, struct uio *uio,
-                   int flags, vfs_context_t ctx);
-static int     kqueue_ioctl(struct fileproc *fp, u_long com, caddr_t data,
-                   vfs_context_t ctx);
-static int     kqueue_select(struct fileproc *fp, int which, void *wql, 
-                   vfs_context_t ctx);
-static int     kqueue_close(struct fileglob *fg, vfs_context_t ctx);
-static int     kqueue_kqfilter(struct fileproc *fp, struct knote *kn, vfs_context_t ctx);
-static int     kqueue_drain(struct fileproc *fp, vfs_context_t ctx);
-extern int     kqueue_stat(struct fileproc *fp, void  *ub, int isstat64, vfs_context_t ctx);
-
-static struct fileops kqueueops = {
-       .fo_read = kqueue_read,
-       .fo_write = kqueue_write,
-       .fo_ioctl = kqueue_ioctl,
-       .fo_select = kqueue_select,
-       .fo_close = kqueue_close,
-       .fo_kqfilter = kqueue_kqfilter,
+static int kqlock2knoteuse(struct kqueue *kq, struct knote *kn);
+static int kqlock2knoteusewait(struct kqueue *kq, struct knote *kn);
+static int kqlock2knotedrop(struct kqueue *kq, struct knote *kn);
+static int knoteuse2kqlock(struct kqueue *kq, struct knote *kn);
+
+static void kqueue_wakeup(struct kqueue *kq, int closed);
+static int kqueue_read(struct fileproc *fp, struct uio *uio,
+    int flags, vfs_context_t ctx);
+static int kqueue_write(struct fileproc *fp, struct uio *uio,
+    int flags, vfs_context_t ctx);
+static int kqueue_ioctl(struct fileproc *fp, u_long com, caddr_t data,
+    vfs_context_t ctx);
+static int kqueue_select(struct fileproc *fp, int which, void *wql,
+    vfs_context_t ctx);
+static int kqueue_close(struct fileglob *fg, vfs_context_t ctx);
+static int kqueue_kqfilter(struct fileproc *fp, struct knote *kn,
+       vfs_context_t ctx);
+static int kqueue_drain(struct fileproc *fp, vfs_context_t ctx);
+
+static const struct fileops kqueueops = {
+       .fo_type = DTYPE_KQUEUE,
+       .fo_read = kqueue_read,
+       .fo_write = kqueue_write,
+       .fo_ioctl = kqueue_ioctl,
+       .fo_select = kqueue_select,
+       .fo_close = kqueue_close,
+       .fo_kqfilter = kqueue_kqfilter,
        .fo_drain = kqueue_drain,
 };
 
 static int kevent_internal(struct proc *p, int iskev64, user_addr_t changelist,
        .fo_drain = kqueue_drain,
 };
 
 static int kevent_internal(struct proc *p, int iskev64, user_addr_t changelist,
-               int nchanges, user_addr_t eventlist, int nevents, int fd, 
-               user_addr_t utimeout, unsigned int flags, int32_t *retval);
-static int kevent_copyin(user_addr_t *addrp, struct kevent64_s *kevp, struct proc *p, int iskev64);
-static int kevent_copyout(struct kevent64_s *kevp, user_addr_t *addrp, struct proc *p, int iskev64);
+    int nchanges, user_addr_t eventlist, int nevents, int fd,
+    user_addr_t utimeout, unsigned int flags, int32_t *retval);
+static int kevent_copyin(user_addr_t *addrp, struct kevent64_s *kevp,
+    struct proc *p, int iskev64);
+static int kevent_copyout(struct kevent64_s *kevp, user_addr_t *addrp,
+    struct proc *p, int iskev64);
 char * kevent_description(struct kevent64_s *kevp, char *s, size_t n);
 
 char * kevent_description(struct kevent64_s *kevp, char *s, size_t n);
 
-static int     kevent_callback(struct kqueue *kq, struct kevent64_s *kevp, void *data);
-static void    kevent_continue(struct kqueue *kq, void *data, int error);
-static void    kqueue_scan_continue(void *contp, wait_result_t wait_result);
-static int     kqueue_process(struct kqueue *kq, kevent_callback_t callback,
-                              void *data, int *countp, struct proc *p);
-static int     kqueue_begin_processing(struct kqueue *kq);
-static void    kqueue_end_processing(struct kqueue *kq);
-static int     knote_process(struct knote *kn, kevent_callback_t callback,
-                             void *data, struct kqtailq *inprocessp, struct proc *p);
-static void    knote_put(struct knote *kn);
-static int     knote_fdpattach(struct knote *kn, struct filedesc *fdp, struct proc *p);
-static void    knote_drop(struct knote *kn, struct proc *p);
-static void    knote_activate(struct knote *kn, int);
-static void    knote_deactivate(struct knote *kn);
-static void    knote_enqueue(struct knote *kn);
-static void    knote_dequeue(struct knote *kn);
-static struct  knote *knote_alloc(void);
-static void    knote_free(struct knote *kn);
-
-static int     filt_fileattach(struct knote *kn);
+static int kevent_callback(struct kqueue *kq, struct kevent64_s *kevp,
+    void *data);
+static void kevent_continue(struct kqueue *kq, void *data, int error);
+static void kqueue_scan_continue(void *contp, wait_result_t wait_result);
+static int kqueue_process(struct kqueue *kq, kevent_callback_t callback,
+    void *data, int *countp, struct proc *p);
+static int kqueue_begin_processing(struct kqueue *kq);
+static void kqueue_end_processing(struct kqueue *kq);
+static int knote_process(struct knote *kn, kevent_callback_t callback,
+    void *data, struct kqtailq *inprocessp, struct proc *p);
+static void knote_put(struct knote *kn);
+static int knote_fdpattach(struct knote *kn, struct filedesc *fdp,
+    struct proc *p);
+static void knote_drop(struct knote *kn, struct proc *p);
+static void knote_activate(struct knote *kn, int);
+static void knote_deactivate(struct knote *kn);
+static void knote_enqueue(struct knote *kn);
+static void knote_dequeue(struct knote *kn);
+static struct knote *knote_alloc(void);
+static void knote_free(struct knote *kn);
+
+static int filt_fileattach(struct knote *kn);
 static struct filterops file_filtops = {
 static struct filterops file_filtops = {
-        .f_isfd = 1,
-        .f_attach = filt_fileattach,
+       .f_isfd = 1,
+       .f_attach = filt_fileattach,
 };
 
 };
 
-static void    filt_kqdetach(struct knote *kn);
-static int     filt_kqueue(struct knote *kn, long hint);
+static void filt_kqdetach(struct knote *kn);
+static int filt_kqueue(struct knote *kn, long hint);
 static struct filterops kqread_filtops = {
 static struct filterops kqread_filtops = {
-        .f_isfd = 1,
-        .f_detach = filt_kqdetach,
-        .f_event = filt_kqueue,
+       .f_isfd = 1,
+       .f_detach = filt_kqdetach,
+       .f_event = filt_kqueue,
 };
 
 };
 
-/*
- * placeholder for not-yet-implemented filters
- */ 
-static int     filt_badattach(struct knote *kn);
+/* placeholder for not-yet-implemented filters */
+static int filt_badattach(struct knote *kn);
 static struct filterops bad_filtops = {
 static struct filterops bad_filtops = {
-        .f_attach = filt_badattach,
+       .f_attach = filt_badattach,
 };
 
 };
 
-static int     filt_procattach(struct knote *kn);
-static void    filt_procdetach(struct knote *kn);
-static int     filt_proc(struct knote *kn, long hint);
+static int filt_procattach(struct knote *kn);
+static void filt_procdetach(struct knote *kn);
+static int filt_proc(struct knote *kn, long hint);
 static struct filterops proc_filtops = {
 static struct filterops proc_filtops = {
-        .f_attach = filt_procattach,
-        .f_detach = filt_procdetach,
-        .f_event = filt_proc,
+       .f_attach = filt_procattach,
+       .f_detach = filt_procdetach,
+       .f_event = filt_proc,
 };
 
 #if VM_PRESSURE_EVENTS
 };
 
 #if VM_PRESSURE_EVENTS
@@ -202,40 +211,43 @@ static struct filterops vm_filtops = {
 };
 #endif /* VM_PRESSURE_EVENTS */
 
 };
 #endif /* VM_PRESSURE_EVENTS */
 
+#if CONFIG_MEMORYSTATUS
+extern struct filterops memorystatus_filtops;
+#endif /* CONFIG_MEMORYSTATUS */
+
 extern struct filterops fs_filtops;
 
 extern struct filterops sig_filtops;
 
 /* Timer filter */
 extern struct filterops fs_filtops;
 
 extern struct filterops sig_filtops;
 
 /* Timer filter */
-static int     filt_timerattach(struct knote *kn);
-static void    filt_timerdetach(struct knote *kn);
-static int     filt_timer(struct knote *kn, long hint);
-static void     filt_timertouch(struct knote *kn, struct kevent64_s *kev, 
-               long type);
+static int filt_timerattach(struct knote *kn);
+static void filt_timerdetach(struct knote *kn);
+static int filt_timer(struct knote *kn, long hint);
+static void filt_timertouch(struct knote *kn, struct kevent64_s *kev,
+    long type);
 static struct filterops timer_filtops = {
 static struct filterops timer_filtops = {
-        .f_attach = filt_timerattach,
-        .f_detach = filt_timerdetach,
-        .f_event = filt_timer,
-        .f_touch = filt_timertouch,
+       .f_attach = filt_timerattach,
+       .f_detach = filt_timerdetach,
+       .f_event = filt_timer,
+       .f_touch = filt_timertouch,
 };
 
 /* Helpers */
 };
 
 /* Helpers */
+static void filt_timerexpire(void *knx, void *param1);
+static int filt_timervalidate(struct knote *kn);
+static void filt_timerupdate(struct knote *kn);
+static void filt_timercancel(struct knote *kn);
 
 
-static void    filt_timerexpire(void *knx, void *param1);
-static int     filt_timervalidate(struct knote *kn);
-static void    filt_timerupdate(struct knote *kn);
-static void    filt_timercancel(struct knote *kn);
-
-#define TIMER_RUNNING          0x1
-#define TIMER_CANCELWAIT       0x2
+#define        TIMER_RUNNING           0x1
+#define        TIMER_CANCELWAIT        0x2
 
 static lck_mtx_t _filt_timerlock;
 
 static lck_mtx_t _filt_timerlock;
-static void    filt_timerlock(void);
-static void    filt_timerunlock(void);
+static void filt_timerlock(void);
+static void filt_timerunlock(void);
 
 
-static zone_t  knote_zone;
+static zone_t knote_zone;
 
 
-#define KN_HASH(val, mask)     (((val) ^ (val >> 8)) & (mask))
+#define        KN_HASH(val, mask)      (((val) ^ (val >> 8)) & (mask))
 
 #if 0
 extern struct filterops aio_filtops;
 
 #if 0
 extern struct filterops aio_filtops;
@@ -245,20 +257,20 @@ extern struct filterops aio_filtops;
 extern struct filterops machport_filtops;
 
 /* User filter */
 extern struct filterops machport_filtops;
 
 /* User filter */
-static int      filt_userattach(struct knote *kn);
-static void    filt_userdetach(struct knote *kn);
-static int     filt_user(struct knote *kn, long hint);
-static void     filt_usertouch(struct knote *kn, struct kevent64_s *kev, 
-               long type);
+static int filt_userattach(struct knote *kn);
+static void filt_userdetach(struct knote *kn);
+static int filt_user(struct knote *kn, long hint);
+static void filt_usertouch(struct knote *kn, struct kevent64_s *kev,
+    long type);
 static struct filterops user_filtops = {
 static struct filterops user_filtops = {
-        .f_attach = filt_userattach,
-        .f_detach = filt_userdetach,
-        .f_event = filt_user,
-        .f_touch = filt_usertouch,
+       .f_attach = filt_userattach,
+       .f_detach = filt_userdetach,
+       .f_event = filt_user,
+       .f_touch = filt_usertouch,
 };
 
 /*
 };
 
 /*
- * Table for for all system-defined filters.
+ * Table for all system-defined filters.
  */
 static struct filterops *sysfilt_ops[] = {
        &file_filtops,                  /* EVFILT_READ */
  */
 static struct filterops *sysfilt_ops[] = {
        &file_filtops,                  /* EVFILT_READ */
@@ -282,6 +294,11 @@ static struct filterops *sysfilt_ops[] = {
        &bad_filtops,                   /* EVFILT_VM */
 #endif
        &file_filtops,                  /* EVFILT_SOCK */
        &bad_filtops,                   /* EVFILT_VM */
 #endif
        &file_filtops,                  /* EVFILT_SOCK */
+#if CONFIG_MEMORYSTATUS
+       &memorystatus_filtops,  /* EVFILT_MEMORYSTATUS */
+#else
+       &bad_filtops,                   /* EVFILT_MEMORYSTATUS */
+#endif
 };
 
 /*
 };
 
 /*
@@ -307,13 +324,12 @@ kqunlock(struct kqueue *kq)
        lck_spin_unlock(&kq->kq_lock);
 }
 
        lck_spin_unlock(&kq->kq_lock);
 }
 
-/* 
+/*
  * Convert a kq lock to a knote use referece.
  *
  *     If the knote is being dropped, we can't get
  *     a use reference, so just return with it
  *     still locked.
  * Convert a kq lock to a knote use referece.
  *
  *     If the knote is being dropped, we can't get
  *     a use reference, so just return with it
  *     still locked.
- *     
  *     - kq locked at entry
  *     - unlock on exit if we get the use reference
  */
  *     - kq locked at entry
  *     - unlock on exit if we get the use reference
  */
@@ -321,20 +337,19 @@ static int
 kqlock2knoteuse(struct kqueue *kq, struct knote *kn)
 {
        if (kn->kn_status & KN_DROPPING)
 kqlock2knoteuse(struct kqueue *kq, struct knote *kn)
 {
        if (kn->kn_status & KN_DROPPING)
-               return 0;
+               return (0);
        kn->kn_inuse++;
        kqunlock(kq);
        kn->kn_inuse++;
        kqunlock(kq);
-       return 1;
- }
+       return (1);
+}
 
 
-/* 
+/*
  * Convert a kq lock to a knote use referece,
  * but wait for attach and drop events to complete.
  *
  *     If the knote is being dropped, we can't get
  *     a use reference, so just return with it
  *     still locked.
  * Convert a kq lock to a knote use referece,
  * but wait for attach and drop events to complete.
  *
  *     If the knote is being dropped, we can't get
  *     a use reference, so just return with it
  *     still locked.
- *     
  *     - kq locked at entry
  *     - kq always unlocked on exit
  */
  *     - kq locked at entry
  *     - kq always unlocked on exit
  */
@@ -343,18 +358,18 @@ kqlock2knoteusewait(struct kqueue *kq, struct knote *kn)
 {
        if ((kn->kn_status & (KN_DROPPING | KN_ATTACHING)) != 0) {
                kn->kn_status |= KN_USEWAIT;
 {
        if ((kn->kn_status & (KN_DROPPING | KN_ATTACHING)) != 0) {
                kn->kn_status |= KN_USEWAIT;
-               wait_queue_assert_wait((wait_queue_t)kq->kq_wqs, &kn->kn_status, THREAD_UNINT, 0);
+               wait_queue_assert_wait((wait_queue_t)kq->kq_wqs,
+                   &kn->kn_status, THREAD_UNINT, 0);
                kqunlock(kq);
                thread_block(THREAD_CONTINUE_NULL);
                kqunlock(kq);
                thread_block(THREAD_CONTINUE_NULL);
-               return 0;
+               return (0);
        }
        kn->kn_inuse++;
        kqunlock(kq);
        }
        kn->kn_inuse++;
        kqunlock(kq);
-       return 1;
- }
-
+       return (1);
+}
 
 
-/* 
+/*
  * Convert from a knote use reference back to kq lock.
  *
  *     Drop a use reference and wake any waiters if
  * Convert from a knote use reference back to kq lock.
  *
  *     Drop a use reference and wake any waiters if
@@ -374,21 +389,22 @@ knoteuse2kqlock(struct kqueue *kq, struct knote *kn)
                }
                if ((kn->kn_status & KN_USEWAIT) != 0) {
                        kn->kn_status &= ~KN_USEWAIT;
                }
                if ((kn->kn_status & KN_USEWAIT) != 0) {
                        kn->kn_status &= ~KN_USEWAIT;
-                       wait_queue_wakeup_all((wait_queue_t)kq->kq_wqs, &kn->kn_status, THREAD_AWAKENED);
+                       wait_queue_wakeup_all((wait_queue_t)kq->kq_wqs,
+                           &kn->kn_status, THREAD_AWAKENED);
                }
        }
        return ((kn->kn_status & KN_DROPPING) == 0);
                }
        }
        return ((kn->kn_status & KN_DROPPING) == 0);
- }
+}
 
 
-/* 
- * Convert a kq lock to a knote drop referece.
+/*
+ * Convert a kq lock to a knote drop reference.
  *
  *     If the knote is in use, wait for the use count
  *     to subside.  We first mark our intention to drop
  *     it - keeping other users from "piling on."
  *     If we are too late, we have to wait for the
  *     other drop to complete.
  *
  *     If the knote is in use, wait for the use count
  *     to subside.  We first mark our intention to drop
  *     it - keeping other users from "piling on."
  *     If we are too late, we have to wait for the
  *     other drop to complete.
- *     
+ *
  *     - kq locked at entry
  *     - always unlocked on exit.
  *     - caller can't hold any locks that would prevent
  *     - kq locked at entry
  *     - always unlocked on exit.
  *     - caller can't hold any locks that would prevent
@@ -400,21 +416,23 @@ kqlock2knotedrop(struct kqueue *kq, struct knote *kn)
        int oktodrop;
 
        oktodrop = ((kn->kn_status & (KN_DROPPING | KN_ATTACHING)) == 0);
        int oktodrop;
 
        oktodrop = ((kn->kn_status & (KN_DROPPING | KN_ATTACHING)) == 0);
+       kn->kn_status &= ~KN_STAYQUEUED;
        kn->kn_status |= KN_DROPPING;
        if (oktodrop) {
                if (kn->kn_inuse == 0) {
                        kqunlock(kq);
        kn->kn_status |= KN_DROPPING;
        if (oktodrop) {
                if (kn->kn_inuse == 0) {
                        kqunlock(kq);
-                       return oktodrop;
+                       return (oktodrop);
                }
        }
        kn->kn_status |= KN_USEWAIT;
                }
        }
        kn->kn_status |= KN_USEWAIT;
-       wait_queue_assert_wait((wait_queue_t)kq->kq_wqs, &kn->kn_status, THREAD_UNINT, 0);
+       wait_queue_assert_wait((wait_queue_t)kq->kq_wqs, &kn->kn_status,
+           THREAD_UNINT, 0);
        kqunlock(kq);
        thread_block(THREAD_CONTINUE_NULL);
        kqunlock(kq);
        thread_block(THREAD_CONTINUE_NULL);
-       return oktodrop;
+       return (oktodrop);
 }
 }
-               
-/* 
+
+/*
  * Release a knote use count reference.
  */
 static void
  * Release a knote use count reference.
  */
 static void
@@ -426,26 +444,25 @@ knote_put(struct knote *kn)
        if (--kn->kn_inuse == 0) {
                if ((kn->kn_status & KN_USEWAIT) != 0) {
                        kn->kn_status &= ~KN_USEWAIT;
        if (--kn->kn_inuse == 0) {
                if ((kn->kn_status & KN_USEWAIT) != 0) {
                        kn->kn_status &= ~KN_USEWAIT;
-                       wait_queue_wakeup_all((wait_queue_t)kq->kq_wqs, &kn->kn_status, THREAD_AWAKENED);
+                       wait_queue_wakeup_all((wait_queue_t)kq->kq_wqs,
+                           &kn->kn_status, THREAD_AWAKENED);
                }
        }
        kqunlock(kq);
                }
        }
        kqunlock(kq);
- }
+}
 
 static int
 filt_fileattach(struct knote *kn)
 {
 
 static int
 filt_fileattach(struct knote *kn)
 {
-       
        return (fo_kqfilter(kn->kn_fp, kn, vfs_context_current()));
 }
 
        return (fo_kqfilter(kn->kn_fp, kn, vfs_context_current()));
 }
 
-#define f_flag f_fglob->fg_flag
-#define f_type f_fglob->fg_type
-#define f_msgcount f_fglob->fg_msgcount
-#define f_cred f_fglob->fg_cred
-#define f_ops f_fglob->fg_ops
-#define f_offset f_fglob->fg_offset
-#define f_data f_fglob->fg_data
+#define        f_flag f_fglob->fg_flag
+#define        f_msgcount f_fglob->fg_msgcount
+#define        f_cred f_fglob->fg_cred
+#define        f_ops f_fglob->fg_ops
+#define        f_offset f_fglob->fg_offset
+#define        f_data f_fglob->fg_data
 
 static void
 filt_kqdetach(struct knote *kn)
 
 static void
 filt_kqdetach(struct knote *kn)
@@ -471,27 +488,33 @@ static int
 filt_procattach(struct knote *kn)
 {
        struct proc *p;
 filt_procattach(struct knote *kn)
 {
        struct proc *p;
-       pid_t selfpid = (pid_t)0;
 
        assert(PID_MAX < NOTE_PDATAMASK);
 
        assert(PID_MAX < NOTE_PDATAMASK);
-       
+
        if ((kn->kn_sfflags & (NOTE_TRACK | NOTE_TRACKERR | NOTE_CHILD)) != 0)
        if ((kn->kn_sfflags & (NOTE_TRACK | NOTE_TRACKERR | NOTE_CHILD)) != 0)
-               return(ENOTSUP);
+               return (ENOTSUP);
 
        p = proc_find(kn->kn_id);
        if (p == NULL) {
                return (ESRCH);
        }
 
 
        p = proc_find(kn->kn_id);
        if (p == NULL) {
                return (ESRCH);
        }
 
-       if ((kn->kn_sfflags & NOTE_EXIT) != 0) {
-               selfpid = proc_selfpid();
-               /* check for validity of NOTE_EXISTATUS */
-               if (((kn->kn_sfflags & NOTE_EXITSTATUS) != 0) && 
-                       ((p->p_ppid != selfpid) && (((p->p_lflag & P_LTRACED) == 0) || (p->p_oppid != selfpid)))) {
+       const int NoteExitStatusBits = NOTE_EXIT | NOTE_EXITSTATUS;
+
+       if ((kn->kn_sfflags & NoteExitStatusBits) == NoteExitStatusBits)
+               do {
+                       pid_t selfpid = proc_selfpid();
+
+                       if (p->p_ppid == selfpid)
+                               break;  /* parent => ok */
+
+                       if ((p->p_lflag & P_LTRACED) != 0 &&
+                           (p->p_oppid == selfpid))
+                               break;  /* parent-in-waiting => ok */
+
                        proc_rele(p);
                        proc_rele(p);
-                       return(EACCES);
-               }
-       }
+                       return (EACCES);
+               } while (0);
 
        proc_klist_lock();
 
 
        proc_klist_lock();
 
@@ -518,7 +541,7 @@ filt_procdetach(struct knote *kn)
        struct proc *p;
 
        proc_klist_lock();
        struct proc *p;
 
        proc_klist_lock();
-       
+
        p = kn->kn_ptr.p_proc;
        if (p != PROC_NULL) {
                kn->kn_ptr.p_proc = PROC_NULL;
        p = kn->kn_ptr.p_proc;
        if (p != PROC_NULL) {
                kn->kn_ptr.p_proc = PROC_NULL;
@@ -531,6 +554,11 @@ filt_procdetach(struct knote *kn)
 static int
 filt_proc(struct knote *kn, long hint)
 {
 static int
 filt_proc(struct knote *kn, long hint)
 {
+       /*
+        * Note: a lot of bits in hint may be obtained from the knote
+        * To free some of those bits, see <rdar://problem/12592988> Freeing up
+        * bits in hint for filt_proc
+        */
        /* hint is 0 when called from above */
        if (hint != 0) {
                u_int event;
        /* hint is 0 when called from above */
        if (hint != 0) {
                u_int event;
@@ -542,35 +570,94 @@ filt_proc(struct knote *kn, long hint)
                 */
                event = (u_int)hint & NOTE_PCTRLMASK;
 
                 */
                event = (u_int)hint & NOTE_PCTRLMASK;
 
+               /*
+                * termination lifecycle events can happen while a debugger
+                * has reparented a process, in which case notifications
+                * should be quashed except to the tracing parent. When
+                * the debugger reaps the child (either via wait4(2) or
+                * process exit), the child will be reparented to the original
+                * parent and these knotes re-fired.
+                */
+               if (event & NOTE_EXIT) {
+                       if ((kn->kn_ptr.p_proc->p_oppid != 0)
+                               && (kn->kn_kq->kq_p->p_pid != kn->kn_ptr.p_proc->p_ppid)) {
+                               /*
+                                * This knote is not for the current ptrace(2) parent, ignore.
+                                */
+                               return 0;
+                       }
+               }                                       
+
                /*
                 * if the user is interested in this event, record it.
                 */
                if (kn->kn_sfflags & event)
                        kn->kn_fflags |= event;
 
                /*
                 * if the user is interested in this event, record it.
                 */
                if (kn->kn_sfflags & event)
                        kn->kn_fflags |= event;
 
-               if (event == NOTE_REAP || (event == NOTE_EXIT && !(kn->kn_sfflags & NOTE_REAP))) {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+               if ((event == NOTE_REAP) || ((event == NOTE_EXIT) && !(kn->kn_sfflags & NOTE_REAP))) {
                        kn->kn_flags |= (EV_EOF | EV_ONESHOT);
                }
                        kn->kn_flags |= (EV_EOF | EV_ONESHOT);
                }
-               if ((event == NOTE_EXIT) && ((kn->kn_sfflags & NOTE_EXITSTATUS) != 0)) {
-                       kn->kn_fflags |= NOTE_EXITSTATUS;
-                       kn->kn_data = (hint & NOTE_PDATAMASK);
-               }
-               if ((event == NOTE_RESOURCEEND) && ((kn->kn_sfflags & NOTE_RESOURCEEND) != 0)) {
-                       kn->kn_fflags |= NOTE_RESOURCEEND;
-                       kn->kn_data = (hint & NOTE_PDATAMASK);
-               }
-#if CONFIG_EMBEDDED
-               /* If the event is one of the APPSTATE events,remove the rest */
-               if (((event & NOTE_APPALLSTATES) != 0) && ((kn->kn_sfflags & NOTE_APPALLSTATES) != 0)) {
-                       /* only one state at a time */
-                       kn->kn_fflags &= ~NOTE_APPALLSTATES;
-                       kn->kn_fflags |= event;
+#pragma clang diagnostic pop
+
+
+               /*
+                * The kernel has a wrapper in place that returns the same data
+                * as is collected here, in kn_data.  Any changes to how 
+                * NOTE_EXITSTATUS and NOTE_EXIT_DETAIL are collected
+                * should also be reflected in the proc_pidnoteexit() wrapper.
+                */
+               if (event == NOTE_EXIT) {
+                       kn->kn_data = 0;
+                       if ((kn->kn_sfflags & NOTE_EXITSTATUS) != 0) {
+                               kn->kn_fflags |= NOTE_EXITSTATUS;
+                               kn->kn_data |= (hint & NOTE_PDATAMASK);
+                       }
+                       if ((kn->kn_sfflags & NOTE_EXIT_DETAIL) != 0) {
+                               kn->kn_fflags |= NOTE_EXIT_DETAIL;
+                               if ((kn->kn_ptr.p_proc->p_lflag &
+                                   P_LTERM_DECRYPTFAIL) != 0) {
+                                       kn->kn_data |= NOTE_EXIT_DECRYPTFAIL; 
+                               }
+                               if ((kn->kn_ptr.p_proc->p_lflag &
+                                   P_LTERM_JETSAM) != 0) {
+                                       kn->kn_data |= NOTE_EXIT_MEMORY;
+                                       switch (kn->kn_ptr.p_proc->p_lflag &
+                                           P_JETSAM_MASK) {
+                                               case P_JETSAM_VMPAGESHORTAGE:
+                                                       kn->kn_data |= NOTE_EXIT_MEMORY_VMPAGESHORTAGE;
+                                                       break;
+                                               case P_JETSAM_VMTHRASHING:
+                                                       kn->kn_data |= NOTE_EXIT_MEMORY_VMTHRASHING;
+                                                       break;
+                                               case P_JETSAM_FCTHRASHING:
+                                                       kn->kn_data |= NOTE_EXIT_MEMORY_FCTHRASHING;
+                                                       break;
+                                               case P_JETSAM_VNODE:
+                                                       kn->kn_data |= NOTE_EXIT_MEMORY_VNODE;
+                                                       break;
+                                               case P_JETSAM_HIWAT:
+                                                       kn->kn_data |= NOTE_EXIT_MEMORY_HIWAT;
+                                                       break;
+                                               case P_JETSAM_PID:
+                                                       kn->kn_data |= NOTE_EXIT_MEMORY_PID;
+                                                       break;
+                                               case P_JETSAM_IDLEEXIT:
+                                                       kn->kn_data |= NOTE_EXIT_MEMORY_IDLE;
+                                                       break;
+                                       }
+                               }
+                               if ((kn->kn_ptr.p_proc->p_csflags &
+                                   CS_KILLED) != 0) {
+                                       kn->kn_data |= NOTE_EXIT_CSERROR;
+                               }
+                       }
                }
                }
-#endif /* CONFIG_EMBEDDED */
        }
 
        /* atomic check, no locking need when called from above */
        }
 
        /* atomic check, no locking need when called from above */
-       return (kn->kn_fflags != 0); 
+       return (kn->kn_fflags != 0);
 }
 
 #if VM_PRESSURE_EVENTS
 }
 
 #if VM_PRESSURE_EVENTS
@@ -582,14 +669,13 @@ filt_proc(struct knote *kn, long hint)
 
 static int
 filt_vmattach(struct knote *kn)
 
 static int
 filt_vmattach(struct knote *kn)
-{      
-       /* 
-        * The note will be cleared once the information has been flushed to the client. 
-        * If there is still pressure, we will be re-alerted.
+{
+       /*
+        * The note will be cleared once the information has been flushed to
+        * the client. If there is still pressure, we will be re-alerted.
         */
         */
-       kn->kn_flags |= EV_CLEAR; 
-       
-       return vm_knote_register(kn);
+       kn->kn_flags |= EV_CLEAR;
+       return (vm_knote_register(kn));
 }
 
 static void
 }
 
 static void
@@ -602,29 +688,30 @@ static int
 filt_vm(struct knote *kn, long hint)
 {
        /* hint == 0 means this is just an alive? check (always true) */
 filt_vm(struct knote *kn, long hint)
 {
        /* hint == 0 means this is just an alive? check (always true) */
-       if (hint != 0) { 
+       if (hint != 0) {
                const pid_t pid = (pid_t)hint;
                const pid_t pid = (pid_t)hint;
-               if ((kn->kn_sfflags & NOTE_VM_PRESSURE) && (kn->kn_kq->kq_p->p_pid == pid)) {
+               if ((kn->kn_sfflags & NOTE_VM_PRESSURE) &&
+                   (kn->kn_kq->kq_p->p_pid == pid)) {
                        kn->kn_fflags |= NOTE_VM_PRESSURE;
                }
        }
                        kn->kn_fflags |= NOTE_VM_PRESSURE;
                }
        }
-       
+
        return (kn->kn_fflags != 0);
 }
 #endif /* VM_PRESSURE_EVENTS */
 
 /*
  * filt_timervalidate - process data from user
        return (kn->kn_fflags != 0);
 }
 #endif /* VM_PRESSURE_EVENTS */
 
 /*
  * filt_timervalidate - process data from user
- *     
- *     Converts to either interval or deadline format.
- *     
+ *
+ *     Converts to either interval or deadline format.
+ *
  *     The saved-data field in the knote contains the
  *     time value.  The saved filter-flags indicates
  *     the unit of measurement.
  *
  *     The saved-data field in the knote contains the
  *     time value.  The saved filter-flags indicates
  *     the unit of measurement.
  *
- *     After validation, either the saved-data field 
- *     contains the interval in absolute time, or ext[0] 
- *     contains the expected deadline. If that deadline 
+ *     After validation, either the saved-data field
+ *     contains the interval in absolute time, or ext[0]
+ *     contains the expected deadline. If that deadline
  *     is in the past, ext[0] is 0.
  *
  *     Returns EINVAL for unrecognized units of time.
  *     is in the past, ext[0] is 0.
  *
  *     Returns EINVAL for unrecognized units of time.
@@ -636,7 +723,7 @@ static int
 filt_timervalidate(struct knote *kn)
 {
        uint64_t multiplier;
 filt_timervalidate(struct knote *kn)
 {
        uint64_t multiplier;
-       uint64_t raw;
+       uint64_t raw = 0;
 
        switch (kn->kn_sfflags & (NOTE_SECONDS|NOTE_USECONDS|NOTE_NSECONDS)) {
        case NOTE_SECONDS:
 
        switch (kn->kn_sfflags & (NOTE_SECONDS|NOTE_USECONDS|NOTE_NSECONDS)) {
        case NOTE_SECONDS:
@@ -652,7 +739,13 @@ filt_timervalidate(struct knote *kn)
                multiplier = NSEC_PER_SEC / 1000;
                break;
        default:
                multiplier = NSEC_PER_SEC / 1000;
                break;
        default:
-               return EINVAL;
+               return (EINVAL);
+       }
+
+       /* transform the slop delta(leeway) in kn_ext[1] if passed to same time scale */
+       if(kn->kn_sfflags & NOTE_LEEWAY){
+               nanoseconds_to_absolutetime((uint64_t)kn->kn_ext[1] * multiplier, &raw);
+               kn->kn_ext[1] = raw;
        }
 
        nanoseconds_to_absolutetime((uint64_t)kn->kn_sdata * multiplier, &raw);
        }
 
        nanoseconds_to_absolutetime((uint64_t)kn->kn_sdata * multiplier, &raw);
@@ -666,22 +759,22 @@ filt_timervalidate(struct knote *kn)
                uint64_t now;
 
                clock_get_calendar_nanotime(&seconds, &nanoseconds);
                uint64_t now;
 
                clock_get_calendar_nanotime(&seconds, &nanoseconds);
-               nanoseconds_to_absolutetime((uint64_t)seconds * NSEC_PER_SEC + 
-                               nanoseconds, &now);
+               nanoseconds_to_absolutetime((uint64_t)seconds * NSEC_PER_SEC +
+                   nanoseconds, &now);
 
                if (raw < now) {
                        /* time has already passed */
                        kn->kn_ext[0] = 0;
                } else {
                        raw -= now;
 
                if (raw < now) {
                        /* time has already passed */
                        kn->kn_ext[0] = 0;
                } else {
                        raw -= now;
-                       clock_absolutetime_interval_to_deadline(raw, 
-                                       &kn->kn_ext[0]);
+                       clock_absolutetime_interval_to_deadline(raw,
+                           &kn->kn_ext[0]);
                }
        } else {
                kn->kn_sdata = raw;
        }
 
                }
        } else {
                kn->kn_sdata = raw;
        }
 
-       return 0;
+       return (0);
 }
 
 /*
 }
 
 /*
@@ -695,7 +788,7 @@ filt_timervalidate(struct knote *kn)
  *
  *     Timer filter lock is held.
  */
  *
  *     Timer filter lock is held.
  */
-static void 
+static void
 filt_timerupdate(struct knote *kn)
 {
        /* if there's no interval, deadline is just in kn_ext[0] */
 filt_timerupdate(struct knote *kn)
 {
        /* if there's no interval, deadline is just in kn_ext[0] */
@@ -705,27 +798,27 @@ filt_timerupdate(struct knote *kn)
        /* if timer hasn't fired before, fire in interval nsecs */
        if (kn->kn_ext[0] == 0) {
                clock_absolutetime_interval_to_deadline(kn->kn_sdata,
        /* if timer hasn't fired before, fire in interval nsecs */
        if (kn->kn_ext[0] == 0) {
                clock_absolutetime_interval_to_deadline(kn->kn_sdata,
-                               &kn->kn_ext[0]);
+                   &kn->kn_ext[0]);
        } else {
        } else {
-               /* 
-                * If timer has fired before, schedule the next pop 
-                * relative to the last intended deadline. 
+               /*
+                * If timer has fired before, schedule the next pop
+                * relative to the last intended deadline.
                 *
                 *
-                * We could check for whether the deadline has expired, 
+                * We could check for whether the deadline has expired,
                 * but the thread call layer can handle that.
                 */
                kn->kn_ext[0] += kn->kn_sdata;
        }
 }
 
                 * but the thread call layer can handle that.
                 */
                kn->kn_ext[0] += kn->kn_sdata;
        }
 }
 
-/* 
+/*
  * filt_timerexpire - the timer callout routine
  *
  * filt_timerexpire - the timer callout routine
  *
- *     Just propagate the timer event into the knote
- *     filter routine (by going through the knote
- *     synchronization point).  Pass a hint to
- *     indicate this is a real event, not just a
- *     query from above.
+ * Just propagate the timer event into the knote
+ * filter routine (by going through the knote
+ * synchronization point).  Pass a hint to
+ * indicate this is a real event, not just a
+ * query from above.
  */
 static void
 filt_timerexpire(void *knx, __unused void *spare)
  */
 static void
 filt_timerexpire(void *knx, __unused void *spare)
@@ -739,14 +832,14 @@ filt_timerexpire(void *knx, __unused void *spare)
 
        /* no "object" for timers, so fake a list */
        SLIST_INIT(&timer_list);
 
        /* no "object" for timers, so fake a list */
        SLIST_INIT(&timer_list);
-       SLIST_INSERT_HEAD(&timer_list, kn, kn_selnext); 
+       SLIST_INSERT_HEAD(&timer_list, kn, kn_selnext);
        KNOTE(&timer_list, 1);
 
        /* if someone is waiting for timer to pop */
        if (kn->kn_hookid & TIMER_CANCELWAIT) {
                struct kqueue *kq = kn->kn_kq;
        KNOTE(&timer_list, 1);
 
        /* if someone is waiting for timer to pop */
        if (kn->kn_hookid & TIMER_CANCELWAIT) {
                struct kqueue *kq = kn->kn_kq;
-               wait_queue_wakeup_all((wait_queue_t)kq->kq_wqs, &kn->kn_hook, 
-                               THREAD_AWAKENED);
+               wait_queue_wakeup_all((wait_queue_t)kq->kq_wqs, &kn->kn_hook,
+                   THREAD_AWAKENED);
        }
 
        filt_timerunlock();
        }
 
        filt_timerunlock();
@@ -771,8 +864,8 @@ filt_timercancel(struct knote *kn)
                } else {
                        /* we have to wait for the expire routine.  */
                        kn->kn_hookid |= TIMER_CANCELWAIT;
                } else {
                        /* we have to wait for the expire routine.  */
                        kn->kn_hookid |= TIMER_CANCELWAIT;
-                       wait_queue_assert_wait((wait_queue_t)kq->kq_wqs, 
-                                       &kn->kn_hook, THREAD_UNINT, 0);
+                       wait_queue_assert_wait((wait_queue_t)kq->kq_wqs,
+                           &kn->kn_hook, THREAD_UNINT, 0);
                        filt_timerunlock();
                        thread_block(THREAD_CONTINUE_NULL);
                        filt_timerlock();
                        filt_timerunlock();
                        thread_block(THREAD_CONTINUE_NULL);
                        filt_timerlock();
@@ -783,7 +876,7 @@ filt_timercancel(struct knote *kn)
 
 /*
  * Allocate a thread call for the knote's lifetime, and kick off the timer.
 
 /*
  * Allocate a thread call for the knote's lifetime, and kick off the timer.
- */ 
+ */
 static int
 filt_timerattach(struct knote *kn)
 {
 static int
 filt_timerattach(struct knote *kn)
 {
@@ -796,7 +889,7 @@ filt_timerattach(struct knote *kn)
 
        filt_timerlock();
        error = filt_timervalidate(kn);
 
        filt_timerlock();
        error = filt_timervalidate(kn);
-       if (error) {
+       if (error != 0) {
                filt_timerunlock();
                return (error);
        }
                filt_timerunlock();
                return (error);
        }
@@ -806,12 +899,25 @@ filt_timerattach(struct knote *kn)
 
        /* absolute=EV_ONESHOT */
        if (kn->kn_sfflags & NOTE_ABSOLUTE)
 
        /* absolute=EV_ONESHOT */
        if (kn->kn_sfflags & NOTE_ABSOLUTE)
-               kn->kn_flags |= EV_ONESHOT; 
+               kn->kn_flags |= EV_ONESHOT;
 
        filt_timerupdate(kn);
        if (kn->kn_ext[0]) {
                kn->kn_flags |= EV_CLEAR;
 
        filt_timerupdate(kn);
        if (kn->kn_ext[0]) {
                kn->kn_flags |= EV_CLEAR;
-               thread_call_enter_delayed(callout, kn->kn_ext[0]);
+               unsigned int timer_flags = 0;
+               if (kn->kn_sfflags & NOTE_CRITICAL)
+                       timer_flags |= THREAD_CALL_DELAY_USER_CRITICAL;
+               else if (kn->kn_sfflags & NOTE_BACKGROUND)
+                       timer_flags |= THREAD_CALL_DELAY_USER_BACKGROUND;
+               else
+                       timer_flags |= THREAD_CALL_DELAY_USER_NORMAL;
+
+               if (kn->kn_sfflags & NOTE_LEEWAY)
+                       timer_flags |= THREAD_CALL_DELAY_LEEWAY;
+
+               thread_call_enter_delayed_with_leeway(callout, NULL,
+                               kn->kn_ext[0], kn->kn_ext[1], timer_flags);
+
                kn->kn_hookid |= TIMER_RUNNING;
        } else {
                /* fake immediate */
                kn->kn_hookid |= TIMER_RUNNING;
        } else {
                /* fake immediate */
@@ -834,8 +940,8 @@ filt_timerdetach(struct knote *kn)
 
        callout = (thread_call_t)kn->kn_hook;
        filt_timercancel(kn);
 
        callout = (thread_call_t)kn->kn_hook;
        filt_timercancel(kn);
-       
-       filt_timerunlock(); 
+
+       filt_timerunlock();
 
        thread_call_free(callout);
 }
 
        thread_call_free(callout);
 }
@@ -846,28 +952,40 @@ static int
 filt_timer(struct knote *kn, long hint)
 {
        int result;
 filt_timer(struct knote *kn, long hint)
 {
        int result;
-       
+
        if (hint) {
                /* real timer pop -- timer lock held by filt_timerexpire */
        if (hint) {
                /* real timer pop -- timer lock held by filt_timerexpire */
-
                kn->kn_data++;
 
                kn->kn_data++;
 
-               if (((kn->kn_hookid & TIMER_CANCELWAIT) == 0) && 
+               if (((kn->kn_hookid & TIMER_CANCELWAIT) == 0) &&
                                ((kn->kn_flags & EV_ONESHOT) == 0)) {
 
                        /* evaluate next time to fire */
                        filt_timerupdate(kn);
 
                        if (kn->kn_ext[0]) {
                                ((kn->kn_flags & EV_ONESHOT) == 0)) {
 
                        /* evaluate next time to fire */
                        filt_timerupdate(kn);
 
                        if (kn->kn_ext[0]) {
+                               unsigned int timer_flags = 0;
+
                                /* keep the callout and re-arm */
                                /* keep the callout and re-arm */
-                               thread_call_enter_delayed(kn->kn_hook, 
-                                               kn->kn_ext[0]);
+                               if (kn->kn_sfflags & NOTE_CRITICAL)
+                                       timer_flags |= THREAD_CALL_DELAY_USER_CRITICAL;
+                               else if (kn->kn_sfflags & NOTE_BACKGROUND)
+                                       timer_flags |= THREAD_CALL_DELAY_USER_BACKGROUND;
+                               else
+                                       timer_flags |= THREAD_CALL_DELAY_USER_NORMAL;
+
+                               if (kn->kn_sfflags & NOTE_LEEWAY)
+                                       timer_flags |= THREAD_CALL_DELAY_LEEWAY;
+
+                               thread_call_enter_delayed_with_leeway(kn->kn_hook, NULL,
+                                               kn->kn_ext[0], kn->kn_ext[1], timer_flags);
+
                                kn->kn_hookid |= TIMER_RUNNING;
                        }
                }
 
                                kn->kn_hookid |= TIMER_RUNNING;
                        }
                }
 
-               return 1;
-       } 
+               return (1);
+       }
 
        /* user-query */
        filt_timerlock();
 
        /* user-query */
        filt_timerlock();
@@ -875,18 +993,19 @@ filt_timer(struct knote *kn, long hint)
        result = (kn->kn_data != 0);
 
        filt_timerunlock();
        result = (kn->kn_data != 0);
 
        filt_timerunlock();
-       return result;
+
+       return (result);
 }
 
 
 /*
  * filt_timertouch - update knote with new user input
  *
 }
 
 
 /*
  * filt_timertouch - update knote with new user input
  *
- *     Cancel and restart the timer based on new user data. When
- *     the user picks up a knote, clear the count of how many timer
- *     pops have gone off (in kn_data).
+ * Cancel and restart the timer based on new user data. When
+ * the user picks up a knote, clear the count of how many timer
+ * pops have gone off (in kn_data).
  */
  */
-static void     
+static void
 filt_timertouch(struct knote *kn, struct kevent64_s *kev, long type)
 {
        int error;
 filt_timertouch(struct knote *kn, struct kevent64_s *kev, long type)
 {
        int error;
@@ -900,6 +1019,8 @@ filt_timertouch(struct knote *kn, struct kevent64_s *kev, long type)
                /* recalculate deadline */
                kn->kn_sdata = kev->data;
                kn->kn_sfflags = kev->fflags;
                /* recalculate deadline */
                kn->kn_sdata = kev->data;
                kn->kn_sfflags = kev->fflags;
+               kn->kn_ext[0] = kev->ext[0];
+               kn->kn_ext[1] = kev->ext[1];
 
                error = filt_timervalidate(kn);
                if (error) {
 
                error = filt_timervalidate(kn);
                if (error) {
@@ -907,12 +1028,26 @@ filt_timertouch(struct knote *kn, struct kevent64_s *kev, long type)
                        kn->kn_flags |= EV_ERROR;
                        kn->kn_data = error;
                        break;
                        kn->kn_flags |= EV_ERROR;
                        kn->kn_data = error;
                        break;
-               } 
+               }
 
                /* start timer if necessary */
                filt_timerupdate(kn);
 
                /* start timer if necessary */
                filt_timerupdate(kn);
+
                if (kn->kn_ext[0]) {
                if (kn->kn_ext[0]) {
-                       thread_call_enter_delayed(kn->kn_hook, kn->kn_ext[0]);
+                       unsigned int timer_flags = 0;
+                       if (kn->kn_sfflags & NOTE_CRITICAL)
+                               timer_flags |= THREAD_CALL_DELAY_USER_CRITICAL;
+                       else if (kn->kn_sfflags & NOTE_BACKGROUND)
+                               timer_flags |= THREAD_CALL_DELAY_USER_BACKGROUND;
+                       else
+                               timer_flags |= THREAD_CALL_DELAY_USER_NORMAL;
+
+                       if (kn->kn_sfflags & NOTE_LEEWAY)
+                               timer_flags |= THREAD_CALL_DELAY_LEEWAY;
+
+                       thread_call_enter_delayed_with_leeway(kn->kn_hook, NULL,
+                                       kn->kn_ext[0], kn->kn_ext[1], timer_flags);
+
                        kn->kn_hookid |= TIMER_RUNNING;
                } else {
                        /* pretend the timer has fired */
                        kn->kn_hookid |= TIMER_RUNNING;
                } else {
                        /* pretend the timer has fired */
@@ -930,7 +1065,7 @@ filt_timertouch(struct knote *kn, struct kevent64_s *kev, long type)
                        kn->kn_fflags = 0;
                break;
        default:
                        kn->kn_fflags = 0;
                break;
        default:
-               panic("filt_timertouch() - invalid type (%ld)", type);
+               panic("%s: - invalid type (%ld)", __func__, type);
                break;
        }
 
                break;
        }
 
@@ -952,114 +1087,115 @@ filt_timerunlock(void)
 static int
 filt_userattach(struct knote *kn)
 {
 static int
 filt_userattach(struct knote *kn)
 {
-        /* EVFILT_USER knotes are not attached to anything in the kernel */
-        kn->kn_hook = NULL;
+       /* EVFILT_USER knotes are not attached to anything in the kernel */
+       kn->kn_hook = NULL;
        if (kn->kn_fflags & NOTE_TRIGGER) {
                kn->kn_hookid = 1;
        } else {
                kn->kn_hookid = 0;
        }
        if (kn->kn_fflags & NOTE_TRIGGER) {
                kn->kn_hookid = 1;
        } else {
                kn->kn_hookid = 0;
        }
-        return 0;
+       return (0);
 }
 
 static void
 filt_userdetach(__unused struct knote *kn)
 {
 }
 
 static void
 filt_userdetach(__unused struct knote *kn)
 {
-        /* EVFILT_USER knotes are not attached to anything in the kernel */
+       /* EVFILT_USER knotes are not attached to anything in the kernel */
 }
 
 static int
 filt_user(struct knote *kn, __unused long hint)
 {
 }
 
 static int
 filt_user(struct knote *kn, __unused long hint)
 {
-        return kn->kn_hookid;
+       return (kn->kn_hookid);
 }
 
 static void
 filt_usertouch(struct knote *kn, struct kevent64_s *kev, long type)
 {
 }
 
 static void
 filt_usertouch(struct knote *kn, struct kevent64_s *kev, long type)
 {
-        uint32_t ffctrl;
-        switch (type) {
-        case EVENT_REGISTER:
-                if (kev->fflags & NOTE_TRIGGER) {
-                        kn->kn_hookid = 1;
-                }
-
-                ffctrl = kev->fflags & NOTE_FFCTRLMASK;
-                kev->fflags &= NOTE_FFLAGSMASK;
-                switch (ffctrl) {
-                case NOTE_FFNOP:
-                        break;
-                case NOTE_FFAND:
-                        OSBitAndAtomic(kev->fflags, &kn->kn_sfflags);
-                        break;
-                case NOTE_FFOR:
-                        OSBitOrAtomic(kev->fflags, &kn->kn_sfflags);
-                        break;
-                case NOTE_FFCOPY:
-                        kn->kn_sfflags = kev->fflags;
-                        break;
-                }
-                kn->kn_sdata = kev->data;
-                break;
-        case EVENT_PROCESS:
-                *kev = kn->kn_kevent;
-                kev->fflags = (volatile UInt32)kn->kn_sfflags;
-                kev->data = kn->kn_sdata;
-                if (kn->kn_flags & EV_CLEAR) {
+       uint32_t ffctrl;
+       switch (type) {
+       case EVENT_REGISTER:
+               if (kev->fflags & NOTE_TRIGGER) {
+                       kn->kn_hookid = 1;
+               }
+
+               ffctrl = kev->fflags & NOTE_FFCTRLMASK;
+               kev->fflags &= NOTE_FFLAGSMASK;
+               switch (ffctrl) {
+               case NOTE_FFNOP:
+                       break;
+               case NOTE_FFAND:
+                       OSBitAndAtomic(kev->fflags, &kn->kn_sfflags);
+                       break;
+               case NOTE_FFOR:
+                       OSBitOrAtomic(kev->fflags, &kn->kn_sfflags);
+                       break;
+               case NOTE_FFCOPY:
+                       kn->kn_sfflags = kev->fflags;
+                       break;
+               }
+               kn->kn_sdata = kev->data;
+               break;
+       case EVENT_PROCESS:
+               *kev = kn->kn_kevent;
+               kev->fflags = (volatile UInt32)kn->kn_sfflags;
+               kev->data = kn->kn_sdata;
+               if (kn->kn_flags & EV_CLEAR) {
                        kn->kn_hookid = 0;
                        kn->kn_data = 0;
                        kn->kn_fflags = 0;
                }
                        kn->kn_hookid = 0;
                        kn->kn_data = 0;
                        kn->kn_fflags = 0;
                }
-                break;
-        default:
-                panic("filt_usertouch() - invalid type (%ld)", type);
-                break;
-        }
+               break;
+       default:
+               panic("%s: - invalid type (%ld)", __func__, type);
+               break;
+       }
 }
 
 /*
  * JMM - placeholder for not-yet-implemented filters
 }
 
 /*
  * JMM - placeholder for not-yet-implemented filters
- */ 
+ */
 static int
 filt_badattach(__unused struct knote *kn)
 {
 static int
 filt_badattach(__unused struct knote *kn)
 {
-       return(ENOTSUP);
+       return (ENOTSUP);
 }
 
 }
 
-
 struct kqueue *
 kqueue_alloc(struct proc *p)
 {
        struct filedesc *fdp = p->p_fd;
        struct kqueue *kq;
 
 struct kqueue *
 kqueue_alloc(struct proc *p)
 {
        struct filedesc *fdp = p->p_fd;
        struct kqueue *kq;
 
-       MALLOC_ZONE(kq, struct kqueue *, sizeof(struct kqueue), M_KQUEUE, M_WAITOK);
+       MALLOC_ZONE(kq, struct kqueue *, sizeof (struct kqueue), M_KQUEUE,
+           M_WAITOK);
        if (kq != NULL) {
                wait_queue_set_t wqs;
 
        if (kq != NULL) {
                wait_queue_set_t wqs;
 
-               wqs = wait_queue_set_alloc(SYNC_POLICY_FIFO | SYNC_POLICY_PREPOST);
+               wqs = wait_queue_set_alloc(SYNC_POLICY_FIFO |
+                   SYNC_POLICY_PREPOST);
                if (wqs != NULL) {
                if (wqs != NULL) {
-                       bzero(kq, sizeof(struct kqueue));
+                       bzero(kq, sizeof (struct kqueue));
                        lck_spin_init(&kq->kq_lock, kq_lck_grp, kq_lck_attr);
                        TAILQ_INIT(&kq->kq_head);
                        kq->kq_wqs = wqs;
                        kq->kq_p = p;
                } else {
                        lck_spin_init(&kq->kq_lock, kq_lck_grp, kq_lck_attr);
                        TAILQ_INIT(&kq->kq_head);
                        kq->kq_wqs = wqs;
                        kq->kq_p = p;
                } else {
-                       FREE_ZONE(kq, sizeof(struct kqueue), M_KQUEUE);
+                       FREE_ZONE(kq, sizeof (struct kqueue), M_KQUEUE);
+                       kq = NULL;
                }
        }
 
        if (fdp->fd_knlistsize < 0) {
                proc_fdlock(p);
                if (fdp->fd_knlistsize < 0)
                }
        }
 
        if (fdp->fd_knlistsize < 0) {
                proc_fdlock(p);
                if (fdp->fd_knlistsize < 0)
-                       fdp->fd_knlistsize = 0;         /* this process has had a kq */
+                       fdp->fd_knlistsize = 0; /* this process has had a kq */
                proc_fdunlock(p);
        }
 
                proc_fdunlock(p);
        }
 
-       return kq;
+       return (kq);
 }
 
 }
 
-
 /*
  * kqueue_dealloc - detach all knotes from a kqueue and free it
  *
 /*
  * kqueue_dealloc - detach all knotes from a kqueue and free it
  *
@@ -1125,24 +1261,25 @@ kqueue_dealloc(struct kqueue *kq)
        }
        proc_fdunlock(p);
 
        }
        proc_fdunlock(p);
 
-       /* 
+       /*
         * before freeing the wait queue set for this kqueue,
         * make sure it is unlinked from all its containing (select) sets.
         */
        wait_queue_unlink_all((wait_queue_t)kq->kq_wqs);
        wait_queue_set_free(kq->kq_wqs);
        lck_spin_destroy(&kq->kq_lock, kq_lck_grp);
         * before freeing the wait queue set for this kqueue,
         * make sure it is unlinked from all its containing (select) sets.
         */
        wait_queue_unlink_all((wait_queue_t)kq->kq_wqs);
        wait_queue_set_free(kq->kq_wqs);
        lck_spin_destroy(&kq->kq_lock, kq_lck_grp);
-       FREE_ZONE(kq, sizeof(struct kqueue), M_KQUEUE);
+       FREE_ZONE(kq, sizeof (struct kqueue), M_KQUEUE);
 }
 
 int
 }
 
 int
-kqueue(struct proc *p, __unused struct kqueue_args *uap, int32_t *retval)
+kqueue_body(struct proc *p, fp_allocfn_t fp_zalloc, void *cra, int32_t *retval)
 {
        struct kqueue *kq;
        struct fileproc *fp;
        int fd, error;
 
 {
        struct kqueue *kq;
        struct fileproc *fp;
        int fd, error;
 
-       error = falloc(p, &fp, &fd, vfs_context_current());
+       error = falloc_withalloc(p,
+           &fp, &fd, vfs_context_current(), fp_zalloc, cra);
        if (error) {
                return (error);
        }
        if (error) {
                return (error);
        }
@@ -1154,11 +1291,11 @@ kqueue(struct proc *p, __unused struct kqueue_args *uap, int32_t *retval)
        }
 
        fp->f_flag = FREAD | FWRITE;
        }
 
        fp->f_flag = FREAD | FWRITE;
-       fp->f_type = DTYPE_KQUEUE;
        fp->f_ops = &kqueueops;
        fp->f_ops = &kqueueops;
-       fp->f_data = (caddr_t)kq;
+       fp->f_data = kq;
 
        proc_fdlock(p);
 
        proc_fdlock(p);
+       *fdflags(p, fd) |= UF_EXCLOSE;
        procfdtbl_releasefd(p, fd, NULL);
        fp_drop(p, fd, fp, 1);
        proc_fdunlock(p);
        procfdtbl_releasefd(p, fd, NULL);
        fp_drop(p, fd, fp, 1);
        proc_fdunlock(p);
@@ -1167,23 +1304,30 @@ kqueue(struct proc *p, __unused struct kqueue_args *uap, int32_t *retval)
        return (error);
 }
 
        return (error);
 }
 
+int
+kqueue(struct proc *p, __unused struct kqueue_args *uap, int32_t *retval)
+{
+       return (kqueue_body(p, fileproc_alloc_init, NULL, retval));
+}
+
 static int
 static int
-kevent_copyin(user_addr_t *addrp, struct kevent64_s *kevp, struct proc *p, int iskev64)
+kevent_copyin(user_addr_t *addrp, struct kevent64_s *kevp, struct proc *p,
+    int iskev64)
 {
        int advance;
        int error;
 
        if (iskev64) {
 {
        int advance;
        int error;
 
        if (iskev64) {
-               advance = sizeof(struct kevent64_s);
+               advance = sizeof (struct kevent64_s);
                error = copyin(*addrp, (caddr_t)kevp, advance);
        } else if (IS_64BIT_PROCESS(p)) {
                struct user64_kevent kev64;
                error = copyin(*addrp, (caddr_t)kevp, advance);
        } else if (IS_64BIT_PROCESS(p)) {
                struct user64_kevent kev64;
-               bzero(kevp, sizeof(struct kevent64_s));
+               bzero(kevp, sizeof (struct kevent64_s));
 
 
-               advance = sizeof(kev64);
+               advance = sizeof (kev64);
                error = copyin(*addrp, (caddr_t)&kev64, advance);
                if (error)
                error = copyin(*addrp, (caddr_t)&kev64, advance);
                if (error)
-                       return error;
+                       return (error);
                kevp->ident = kev64.ident;
                kevp->filter = kev64.filter;
                kevp->flags = kev64.flags;
                kevp->ident = kev64.ident;
                kevp->filter = kev64.filter;
                kevp->flags = kev64.flags;
@@ -1192,12 +1336,12 @@ kevent_copyin(user_addr_t *addrp, struct kevent64_s *kevp, struct proc *p, int i
                kevp->udata = kev64.udata;
        } else {
                struct user32_kevent kev32;
                kevp->udata = kev64.udata;
        } else {
                struct user32_kevent kev32;
-               bzero(kevp, sizeof(struct kevent64_s));
+               bzero(kevp, sizeof (struct kevent64_s));
 
 
-               advance = sizeof(kev32);
+               advance = sizeof (kev32);
                error = copyin(*addrp, (caddr_t)&kev32, advance);
                if (error)
                error = copyin(*addrp, (caddr_t)&kev32, advance);
                if (error)
-                       return error;
+                       return (error);
                kevp->ident = (uintptr_t)kev32.ident;
                kevp->filter = kev32.filter;
                kevp->flags = kev32.flags;
                kevp->ident = (uintptr_t)kev32.ident;
                kevp->filter = kev32.filter;
                kevp->flags = kev32.flags;
@@ -1207,17 +1351,18 @@ kevent_copyin(user_addr_t *addrp, struct kevent64_s *kevp, struct proc *p, int i
        }
        if (!error)
                *addrp += advance;
        }
        if (!error)
                *addrp += advance;
-       return error;
+       return (error);
 }
 
 static int
 }
 
 static int
-kevent_copyout(struct kevent64_s *kevp, user_addr_t *addrp, struct proc *p, int iskev64)
+kevent_copyout(struct kevent64_s *kevp, user_addr_t *addrp, struct proc *p,
+    int iskev64)
 {
        int advance;
        int error;
 
        if (iskev64) {
 {
        int advance;
        int error;
 
        if (iskev64) {
-               advance = sizeof(struct kevent64_s);
+               advance = sizeof (struct kevent64_s);
                error = copyout((caddr_t)kevp, *addrp, advance);
        } else if (IS_64BIT_PROCESS(p)) {
                struct user64_kevent kev64;
                error = copyout((caddr_t)kevp, *addrp, advance);
        } else if (IS_64BIT_PROCESS(p)) {
                struct user64_kevent kev64;
@@ -1227,14 +1372,14 @@ kevent_copyout(struct kevent64_s *kevp, user_addr_t *addrp, struct proc *p, int
                 * value of (uintptr_t)-1.
                 */
                kev64.ident = (kevp->ident == (uintptr_t)-1) ?
                 * value of (uintptr_t)-1.
                 */
                kev64.ident = (kevp->ident == (uintptr_t)-1) ?
-                          (uint64_t)-1LL : (uint64_t)kevp->ident;
+                   (uint64_t)-1LL : (uint64_t)kevp->ident;
 
                kev64.filter = kevp->filter;
                kev64.flags = kevp->flags;
                kev64.fflags = kevp->fflags;
                kev64.data = (int64_t) kevp->data;
                kev64.udata = kevp->udata;
 
                kev64.filter = kevp->filter;
                kev64.flags = kevp->flags;
                kev64.fflags = kevp->fflags;
                kev64.data = (int64_t) kevp->data;
                kev64.udata = kevp->udata;
-               advance = sizeof(kev64);
+               advance = sizeof (kev64);
                error = copyout((caddr_t)&kev64, *addrp, advance);
        } else {
                struct user32_kevent kev32;
                error = copyout((caddr_t)&kev64, *addrp, advance);
        } else {
                struct user32_kevent kev32;
@@ -1245,12 +1390,12 @@ kevent_copyout(struct kevent64_s *kevp, user_addr_t *addrp, struct proc *p, int
                kev32.fflags = kevp->fflags;
                kev32.data = (int32_t)kevp->data;
                kev32.udata = kevp->udata;
                kev32.fflags = kevp->fflags;
                kev32.data = (int32_t)kevp->data;
                kev32.udata = kevp->udata;
-               advance = sizeof(kev32);
+               advance = sizeof (kev32);
                error = copyout((caddr_t)&kev32, *addrp, advance);
        }
        if (!error)
                *addrp += advance;
                error = copyout((caddr_t)&kev32, *addrp, advance);
        }
        if (!error)
                *addrp += advance;
-       return error;
+       return (error);
 }
 
 /*
 }
 
 /*
@@ -1294,38 +1439,38 @@ kevent_continue(__unused struct kqueue *kq, void *data, int error)
 int
 kevent(struct proc *p, struct kevent_args *uap, int32_t *retval)
 {
 int
 kevent(struct proc *p, struct kevent_args *uap, int32_t *retval)
 {
-       return kevent_internal(p, 
-                       0, 
-                       uap->changelist,
-                       uap->nchanges,
-                       uap->eventlist,
-                       uap->nevents,
-                       uap->fd,
-                       uap->timeout,
-                       0, /* no flags from old kevent() call */
-                       retval);
-}
-  
+       return (kevent_internal(p,
+           0,
+           uap->changelist,
+           uap->nchanges,
+           uap->eventlist,
+           uap->nevents,
+           uap->fd,
+           uap->timeout,
+           0, /* no flags from old kevent() call */
+           retval));
+}
+
 int
 kevent64(struct proc *p, struct kevent64_args *uap, int32_t *retval)
 {
 int
 kevent64(struct proc *p, struct kevent64_args *uap, int32_t *retval)
 {
-       return kevent_internal(p, 
-                       1, 
-                       uap->changelist,
-                       uap->nchanges,
-                       uap->eventlist,
-                       uap->nevents,
-                       uap->fd,
-                       uap->timeout,
-                       uap->flags,
-                       retval);
+       return (kevent_internal(p,
+           1,
+           uap->changelist,
+           uap->nchanges,
+           uap->eventlist,
+           uap->nevents,
+           uap->fd,
+           uap->timeout,
+           uap->flags,
+           retval));
 }
 
 static int
 }
 
 static int
-kevent_internal(struct proc *p, int iskev64, user_addr_t changelist, 
-               int nchanges, user_addr_t ueventlist, int nevents, int fd, 
-               user_addr_t utimeout, __unused unsigned int flags, 
-               int32_t *retval)
+kevent_internal(struct proc *p, int iskev64, user_addr_t changelist,
+    int nchanges, user_addr_t ueventlist, int nevents, int fd,
+    user_addr_t utimeout, __unused unsigned int flags,
+    int32_t *retval)
 {
        struct _kevent *cont_args;
        uthread_t ut;
 {
        struct _kevent *cont_args;
        uthread_t ut;
@@ -1351,9 +1496,9 @@ kevent_internal(struct proc *p, int iskev64, user_addr_t changelist,
                        TIMESPEC_TO_TIMEVAL(&rtv, &ts);
                }
                if (error)
                        TIMESPEC_TO_TIMEVAL(&rtv, &ts);
                }
                if (error)
-                       return error;
+                       return (error);
                if (itimerfix(&rtv))
                if (itimerfix(&rtv))
-                       return EINVAL;
+                       return (EINVAL);
                getmicrouptime(&atv);
                timevaladd(&atv, &rtv);
        } else {
                getmicrouptime(&atv);
                timevaladd(&atv, &rtv);
        } else {
@@ -1363,8 +1508,8 @@ kevent_internal(struct proc *p, int iskev64, user_addr_t changelist,
 
        /* get a usecount for the kq itself */
        if ((error = fp_getfkq(p, fd, &fp, &kq)) != 0)
 
        /* get a usecount for the kq itself */
        if ((error = fp_getfkq(p, fd, &fp, &kq)) != 0)
-               return(error);
-       
+               return (error);
+
        /* each kq should only be used for events of one type */
        kqlock(kq);
        if (kq->kq_state & (KQ_KEV32 | KQ_KEV64)) {
        /* each kq should only be used for events of one type */
        kqlock(kq);
        if (kq->kq_state & (KQ_KEV32 | KQ_KEV64)) {
@@ -1385,7 +1530,7 @@ kevent_internal(struct proc *p, int iskev64, user_addr_t changelist,
                error = kevent_copyin(&changelist, &kev, p, iskev64);
                if (error)
                        break;
                error = kevent_copyin(&changelist, &kev, p, iskev64);
                if (error)
                        break;
-                               
+
                kev.flags &= ~EV_SYSFLAGS;
                error = kevent_register(kq, &kev, p);
                if ((error || (kev.flags & EV_RECEIPT)) && nevents > 0) {
                kev.flags &= ~EV_SYSFLAGS;
                error = kevent_register(kq, &kev, p);
                if ((error || (kev.flags & EV_RECEIPT)) && nevents > 0) {
@@ -1413,26 +1558,25 @@ kevent_internal(struct proc *p, int iskev64, user_addr_t changelist,
 
        if (nevents > 0 && noutputs == 0 && error == 0)
                error = kqueue_scan(kq, kevent_callback,
 
        if (nevents > 0 && noutputs == 0 && error == 0)
                error = kqueue_scan(kq, kevent_callback,
-                                   kevent_continue, cont_args,
-                                   &atv, p);
+                   kevent_continue, cont_args,
+                   &atv, p);
        kevent_continue(kq, cont_args, error);
 
 errorout:
        fp_drop(p, fd, fp, 0);
        kevent_continue(kq, cont_args, error);
 
 errorout:
        fp_drop(p, fd, fp, 0);
-       return error;
+       return (error);
 }
 
 
 /*
  * kevent_callback - callback for each individual event
  *
 }
 
 
 /*
  * kevent_callback - callback for each individual event
  *
- *     called with nothing locked
- *     caller holds a reference on the kqueue
+ * called with nothing locked
+ * caller holds a reference on the kqueue
  */
  */
-
 static int
 static int
-kevent_callback(__unused struct kqueue *kq, struct kevent64_s *kevp, 
-               void *data)
+kevent_callback(__unused struct kqueue *kq, struct kevent64_s *kevp,
+    void *data)
 {
        struct _kevent *cont_args;
        int error;
 {
        struct _kevent *cont_args;
        int error;
@@ -1446,38 +1590,40 @@ kevent_callback(__unused struct kqueue *kq, struct kevent64_s *kevp,
        /*
         * Copy out the appropriate amount of event data for this user.
         */
        /*
         * Copy out the appropriate amount of event data for this user.
         */
-       error = kevent_copyout(kevp, &cont_args->eventlist, current_proc(), iskev64);
+       error = kevent_copyout(kevp, &cont_args->eventlist, current_proc(),
+           iskev64);
 
        /*
         * If there isn't space for additional events, return
         * a harmless error to stop the processing here
         */
        if (error == 0 && ++cont_args->eventout == cont_args->eventcount)
 
        /*
         * If there isn't space for additional events, return
         * a harmless error to stop the processing here
         */
        if (error == 0 && ++cont_args->eventout == cont_args->eventcount)
-                       error = EWOULDBLOCK;
-       return error;
+               error = EWOULDBLOCK;
+       return (error);
 }
 
 /*
  * kevent_description - format a description of a kevent for diagnostic output
  *
 }
 
 /*
  * kevent_description - format a description of a kevent for diagnostic output
  *
- *      called with a 128-byte string buffer
+ * called with a 128-byte string buffer
  */
 
 char *
 kevent_description(struct kevent64_s *kevp, char *s, size_t n)
 {
  */
 
 char *
 kevent_description(struct kevent64_s *kevp, char *s, size_t n)
 {
-        snprintf(s, n,
-                 "kevent="
-                 "{.ident=%#llx, .filter=%d, .flags=%#x, .fflags=%#x, .data=%#llx, .udata=%#llx, .ext[0]=%#llx, .ext[1]=%#llx}",
-                 kevp->ident,
-                 kevp->filter,
-                 kevp->flags,
-                 kevp->fflags,
-                 kevp->data,
-                 kevp->udata,
-                kevp->ext[0],
-                kevp->ext[1]);
-        return s;
+       snprintf(s, n,
+           "kevent="
+           "{.ident=%#llx, .filter=%d, .flags=%#x, .fflags=%#x, .data=%#llx, .udata=%#llx, .ext[0]=%#llx, .ext[1]=%#llx}",
+           kevp->ident,
+           kevp->filter,
+           kevp->flags,
+           kevp->fflags,
+           kevp->data,
+           kevp->udata,
+           kevp->ext[0],
+           kevp->ext[1]);
+
+       return (s);
 }
 
 /*
 }
 
 /*
@@ -1495,7 +1641,8 @@ kevent_description(struct kevent64_s *kevp, char *s, size_t n)
  */
 
 int
  */
 
 int
-kevent_register(struct kqueue *kq, struct kevent64_s *kev, __unused struct proc *ctxp)
+kevent_register(struct kqueue *kq, struct kevent64_s *kev,
+    __unused struct proc *ctxp)
 {
        struct proc *p = kq->kq_p;
        struct filedesc *fdp = p->p_fd;
 {
        struct proc *p = kq->kq_p;
        struct filedesc *fdp = p->p_fd;
@@ -1518,12 +1665,12 @@ kevent_register(struct kqueue *kq, struct kevent64_s *kev, __unused struct proc
                return (EINVAL);
        }
 
                return (EINVAL);
        }
 
- restart:
+restart:
        /* this iocount needs to be dropped if it is not registered */
        proc_fdlock(p);
        if (fops->f_isfd && (error = fp_lookup(p, kev->ident, &fp, 1)) != 0) {
                proc_fdunlock(p);
        /* this iocount needs to be dropped if it is not registered */
        proc_fdlock(p);
        if (fops->f_isfd && (error = fp_lookup(p, kev->ident, &fp, 1)) != 0) {
                proc_fdunlock(p);
-               return(error);
+               return (error);
        }
 
        if (fops->f_isfd) {
        }
 
        if (fops->f_isfd) {
@@ -1538,7 +1685,7 @@ kevent_register(struct kqueue *kq, struct kevent64_s *kev, __unused struct proc
                /* hash non-fd knotes here too */
                if (fdp->fd_knhashmask != 0) {
                        struct klist *list;
                /* hash non-fd knotes here too */
                if (fdp->fd_knhashmask != 0) {
                        struct klist *list;
-                       
+
                        list = &fdp->fd_knhash[
                            KN_HASH((u_long)kev->ident, fdp->fd_knhashmask)];
                        SLIST_FOREACH(kn, list, kn_link)
                        list = &fdp->fd_knhash[
                            KN_HASH((u_long)kev->ident, fdp->fd_knhashmask)];
                        SLIST_FOREACH(kn, list, kn_link)
@@ -1626,7 +1773,7 @@ kevent_register(struct kqueue *kq, struct kevent64_s *kev, __unused struct proc
                /* existing knote - get kqueue lock */
                kqlock(kq);
                proc_fdunlock(p);
                /* existing knote - get kqueue lock */
                kqlock(kq);
                proc_fdunlock(p);
-               
+
                if (kev->flags & EV_DELETE) {
                        knote_dequeue(kn);
                        kn->kn_status |= KN_DISABLED;
                if (kev->flags & EV_DELETE) {
                        knote_dequeue(kn);
                        kn->kn_status |= KN_DISABLED;
@@ -1636,7 +1783,7 @@ kevent_register(struct kqueue *kq, struct kevent64_s *kev, __unused struct proc
                        }
                        goto done;
                }
                        }
                        goto done;
                }
-                       
+
                /* update status flags for existing knote */
                if (kev->flags & EV_DISABLE) {
                        knote_dequeue(kn);
                /* update status flags for existing knote */
                if (kev->flags & EV_DISABLE) {
                        knote_dequeue(kn);
@@ -1649,13 +1796,13 @@ kevent_register(struct kqueue *kq, struct kevent64_s *kev, __unused struct proc
 
                /*
                 * The user may change some filter values after the
 
                /*
                 * The user may change some filter values after the
-                * initial EV_ADD, but doing so will not reset any 
+                * initial EV_ADD, but doing so will not reset any
                 * filter which have already been triggered.
                 */
                kn->kn_kevent.udata = kev->udata;
                if (fops->f_isfd || fops->f_touch == NULL) {
                 * filter which have already been triggered.
                 */
                kn->kn_kevent.udata = kev->udata;
                if (fops->f_isfd || fops->f_touch == NULL) {
-                       kn->kn_sfflags = kev->fflags;
-                       kn->kn_sdata = kev->data;
+                       kn->kn_sfflags = kev->fflags;
+                       kn->kn_sdata = kev->data;
                }
 
                /*
                }
 
                /*
@@ -1676,7 +1823,7 @@ kevent_register(struct kqueue *kq, struct kevent64_s *kev, __unused struct proc
                 * in filter values.
                 */
                if (!fops->f_isfd && fops->f_touch != NULL)
                 * in filter values.
                 */
                if (!fops->f_isfd && fops->f_touch != NULL)
-                       fops->f_touch(kn, kev, EVENT_REGISTER);
+                       fops->f_touch(kn, kev, EVENT_REGISTER);
        }
        /* still have use ref on knote */
 
        }
        /* still have use ref on knote */
 
@@ -1714,11 +1861,11 @@ done:
  *     kqueue locked on entry and exit - but may be dropped
  */
 static int
  *     kqueue locked on entry and exit - but may be dropped
  */
 static int
-knote_process(struct knote     *kn,
-             kevent_callback_t callback,
-             void              *data, 
-             struct kqtailq    *inprocessp, 
-             struct proc       *p)
+knote_process(struct knote *kn,
+    kevent_callback_t callback,
+    void *data,
+    struct kqtailq *inprocessp,
+    struct proc *p)
 {
        struct kqueue *kq = kn->kn_kq;
        struct kevent64_s kev;
 {
        struct kqueue *kq = kn->kn_kq;
        struct kevent64_s kev;
@@ -1747,52 +1894,67 @@ knote_process(struct knote      *kn,
 
                result = 1;
                revalidate = ((kn->kn_status & KN_STAYQUEUED) != 0 ||
 
                result = 1;
                revalidate = ((kn->kn_status & KN_STAYQUEUED) != 0 ||
-                             (kn->kn_flags & EV_ONESHOT) == 0);
-               touch = (!kn->kn_fop->f_isfd && kn->kn_fop->f_touch != NULL);
+                   (kn->kn_flags & EV_ONESHOT) == 0);
+               touch = (!kn->kn_fop->f_isfd && kn->kn_fop->f_touch != NULL);
 
                if (revalidate || touch) {
                        if (revalidate)
                                knote_deactivate(kn);
 
                if (revalidate || touch) {
                        if (revalidate)
                                knote_deactivate(kn);
-                       
+
                        /* call the filter/touch routines with just a ref */
                        if (kqlock2knoteuse(kq, kn)) {
                        /* call the filter/touch routines with just a ref */
                        if (kqlock2knoteuse(kq, kn)) {
-                       
                                /* if we have to revalidate, call the filter */
                                if (revalidate) {
                                        result = kn->kn_fop->f_event(kn, 0);
                                }
 
                                /* if we have to revalidate, call the filter */
                                if (revalidate) {
                                        result = kn->kn_fop->f_event(kn, 0);
                                }
 
-                               /* capture the kevent data - using touch if specified */
+                               /*
+                                * capture the kevent data - using touch if
+                                * specified
+                                */
                                if (result && touch) {
                                if (result && touch) {
-                                       kn->kn_fop->f_touch(kn, &kev, EVENT_PROCESS);
+                                       kn->kn_fop->f_touch(kn, &kev,
+                                           EVENT_PROCESS);
                                }
 
                                }
 
-                               /* convert back to a kqlock - bail if the knote went away */
+                               /*
+                                * convert back to a kqlock - bail if the knote
+                                * went away
+                                */
                                if (!knoteuse2kqlock(kq, kn)) {
                                if (!knoteuse2kqlock(kq, kn)) {
-                                       return EJUSTRETURN;
+                                       return (EJUSTRETURN);
                                } else if (result) {
                                } else if (result) {
-                                       /* if revalidated as alive, make sure it's active */
+                                       /*
+                                        * if revalidated as alive, make sure
+                                        * it's active
+                                        */
                                        if (!(kn->kn_status & KN_ACTIVE)) {
                                                knote_activate(kn, 0);
                                        }
 
                                        if (!(kn->kn_status & KN_ACTIVE)) {
                                                knote_activate(kn, 0);
                                        }
 
-                                       /* capture all events that occurred during filter */
+                                       /*
+                                        * capture all events that occurred
+                                        * during filter
+                                        */
                                        if (!touch) {
                                                kev = kn->kn_kevent;
                                        }
 
                                } else if ((kn->kn_status & KN_STAYQUEUED) == 0) {
                                        if (!touch) {
                                                kev = kn->kn_kevent;
                                        }
 
                                } else if ((kn->kn_status & KN_STAYQUEUED) == 0) {
-                                       /* was already dequeued, so just bail on this one */
-                                       return EJUSTRETURN;
+                                       /*
+                                        * was already dequeued, so just bail on
+                                        * this one
+                                        */
+                                       return (EJUSTRETURN);
                                }
                        } else {
                                }
                        } else {
-                               return EJUSTRETURN;
+                               return (EJUSTRETURN);
                        }
                } else {
                        kev = kn->kn_kevent;
                }
        }
                        }
                } else {
                        kev = kn->kn_kevent;
                }
        }
-               
+
        /* move knote onto inprocess queue */
        assert(kn->kn_tq == &kq->kq_head);
        TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
        /* move knote onto inprocess queue */
        assert(kn->kn_tq == &kq->kq_head);
        TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
@@ -1809,7 +1971,7 @@ knote_process(struct knote        *kn,
         */
 
        if (result == 0) {
         */
 
        if (result == 0) {
-               return EJUSTRETURN;
+               return (EJUSTRETURN);
        } else if ((kn->kn_flags & EV_ONESHOT) != 0) {
                knote_deactivate(kn);
                if (kqlock2knotedrop(kq, kn)) {
        } else if ((kn->kn_flags & EV_ONESHOT) != 0) {
                knote_deactivate(kn);
                if (kqlock2knotedrop(kq, kn)) {
@@ -1843,9 +2005,9 @@ knote_process(struct knote        *kn,
 
        /* callback to handle each event as we find it */
        error = (callback)(kq, &kev, data);
 
        /* callback to handle each event as we find it */
        error = (callback)(kq, &kev, data);
-       
+
        kqlock(kq);
        kqlock(kq);
-       return error;
+       return (error);
 }
 
 /*
 }
 
 /*
@@ -1860,19 +2022,20 @@ kqueue_begin_processing(struct kqueue *kq)
 {
        for (;;) {
                if (kq->kq_count == 0) {
 {
        for (;;) {
                if (kq->kq_count == 0) {
-                       return -1;
+                       return (-1);
                }
 
                /* if someone else is processing the queue, wait */
                if (kq->kq_nprocess != 0) {
                }
 
                /* if someone else is processing the queue, wait */
                if (kq->kq_nprocess != 0) {
-                       wait_queue_assert_wait((wait_queue_t)kq->kq_wqs, &kq->kq_nprocess, THREAD_UNINT, 0);
+                       wait_queue_assert_wait((wait_queue_t)kq->kq_wqs,
+                           &kq->kq_nprocess, THREAD_UNINT, 0);
                        kq->kq_state |= KQ_PROCWAIT;
                        kqunlock(kq);
                        thread_block(THREAD_CONTINUE_NULL);
                        kqlock(kq);
                } else {
                        kq->kq_nprocess = 1;
                        kq->kq_state |= KQ_PROCWAIT;
                        kqunlock(kq);
                        thread_block(THREAD_CONTINUE_NULL);
                        kqlock(kq);
                } else {
                        kq->kq_nprocess = 1;
-                       return 0;
+                       return (0);
                }
        }
 }
                }
        }
 }
@@ -1886,7 +2049,8 @@ kqueue_end_processing(struct kqueue *kq)
        kq->kq_nprocess = 0;
        if (kq->kq_state & KQ_PROCWAIT) {
                kq->kq_state &= ~KQ_PROCWAIT;
        kq->kq_nprocess = 0;
        if (kq->kq_state & KQ_PROCWAIT) {
                kq->kq_state &= ~KQ_PROCWAIT;
-               wait_queue_wakeup_all((wait_queue_t)kq->kq_wqs, &kq->kq_nprocess, THREAD_AWAKENED);
+               wait_queue_wakeup_all((wait_queue_t)kq->kq_wqs,
+                   &kq->kq_nprocess, THREAD_AWAKENED);
        }
 }
 
        }
 }
 
@@ -1907,27 +2071,27 @@ kqueue_end_processing(struct kqueue *kq)
 
 static int
 kqueue_process(struct kqueue *kq,
 
 static int
 kqueue_process(struct kqueue *kq,
-              kevent_callback_t callback,
-              void *data, 
-              int *countp,
-              struct proc *p)
+    kevent_callback_t callback,
+    void *data,
+    int *countp,
+    struct proc *p)
 {
 {
-        struct kqtailq inprocess;
+       struct kqtailq inprocess;
        struct knote *kn;
        int nevents;
        int error;
 
        struct knote *kn;
        int nevents;
        int error;
 
-        TAILQ_INIT(&inprocess);
+       TAILQ_INIT(&inprocess);
 
        if (kqueue_begin_processing(kq) == -1) {
                *countp = 0;
                /* Nothing to process */
 
        if (kqueue_begin_processing(kq) == -1) {
                *countp = 0;
                /* Nothing to process */
-               return 0;
+               return (0);
        }
 
        /*
        }
 
        /*
-        * Clear any pre-posted status from previous runs, so we only
-        * detect events that occur during this run.
+        * Clear any pre-posted status from previous runs, so we
+        * only detect events that occur during this run.
         */
        wait_queue_sub_clearrefs(kq->kq_wqs);
 
         */
        wait_queue_sub_clearrefs(kq->kq_wqs);
 
@@ -1940,7 +2104,7 @@ kqueue_process(struct kqueue *kq,
        nevents = 0;
 
        while (error == 0 &&
        nevents = 0;
 
        while (error == 0 &&
-              (kn = TAILQ_FIRST(&kq->kq_head)) != NULL) {
+           (kn = TAILQ_FIRST(&kq->kq_head)) != NULL) {
                error = knote_process(kn, callback, data, &inprocess, p);
                if (error == EJUSTRETURN)
                        error = 0;
                error = knote_process(kn, callback, data, &inprocess, p);
                if (error == EJUSTRETURN)
                        error = 0;
@@ -1963,7 +2127,7 @@ kqueue_process(struct kqueue *kq,
        kqueue_end_processing(kq);
 
        *countp = nevents;
        kqueue_end_processing(kq);
 
        *countp = nevents;
-       return error;
+       return (error);
 }
 
 
 }
 
 
@@ -1981,10 +2145,11 @@ kqueue_scan_continue(void *data, wait_result_t wait_result)
        switch (wait_result) {
        case THREAD_AWAKENED:
                kqlock(kq);
        switch (wait_result) {
        case THREAD_AWAKENED:
                kqlock(kq);
-               error = kqueue_process(kq, cont_args->call, cont_args, &count, current_proc());
+               error = kqueue_process(kq, cont_args->call, cont_args, &count,
+                   current_proc());
                if (error == 0 && count == 0) {
                if (error == 0 && count == 0) {
-                       wait_queue_assert_wait((wait_queue_t)kq->kq_wqs, KQ_EVENT, 
-                                              THREAD_ABORTSAFE, cont_args->deadline); 
+                       wait_queue_assert_wait((wait_queue_t)kq->kq_wqs,
+                           KQ_EVENT, THREAD_ABORTSAFE, cont_args->deadline);
                        kq->kq_state |= KQ_SLEEP;
                        kqunlock(kq);
                        thread_block_parameter(kqueue_scan_continue, kq);
                        kq->kq_state |= KQ_SLEEP;
                        kqunlock(kq);
                        thread_block_parameter(kqueue_scan_continue, kq);
@@ -1993,16 +2158,17 @@ kqueue_scan_continue(void *data, wait_result_t wait_result)
                kqunlock(kq);
                break;
        case THREAD_TIMED_OUT:
                kqunlock(kq);
                break;
        case THREAD_TIMED_OUT:
-               error = EWOULDBLOCK; 
+               error = EWOULDBLOCK;
                break;
        case THREAD_INTERRUPTED:
                error = EINTR;
                break;
        default:
                break;
        case THREAD_INTERRUPTED:
                error = EINTR;
                break;
        default:
-               panic("kevent_scan_cont() - invalid wait_result (%d)", wait_result);
+               panic("%s: - invalid wait_result (%d)", __func__,
+                   wait_result);
                error = 0;
        }
                error = 0;
        }
-       
+
        /* call the continuation with the results */
        assert(cont_args->cont != NULL);
        (cont_args->cont)(kq, cont_args->data, error);
        /* call the continuation with the results */
        assert(cont_args->cont != NULL);
        (cont_args->cont)(kq, cont_args->data, error);
@@ -2024,7 +2190,7 @@ kqueue_scan_continue(void *data, wait_result_t wait_result)
  */
 
 int
  */
 
 int
-kqueue_scan(struct kqueue *kq, 
+kqueue_scan(struct kqueue *kq,
            kevent_callback_t callback,
            kqueue_continue_t continuation,
            void *data,
            kevent_callback_t callback,
            kqueue_continue_t continuation,
            void *data,
@@ -2045,7 +2211,7 @@ kqueue_scan(struct kqueue *kq,
 
                /*
                 * Make a pass through the kq to find events already
 
                /*
                 * Make a pass through the kq to find events already
-                * triggered.  
+                * triggered.
                 */
                kqlock(kq);
                error = kqueue_process(kq, callback, data, &count, p);
                 */
                kqlock(kq);
                error = kqueue_process(kq, callback, data, &count, p);
@@ -2058,10 +2224,10 @@ kqueue_scan(struct kqueue *kq,
                        /* convert the timeout to a deadline once */
                        if (atvp->tv_sec || atvp->tv_usec) {
                                uint64_t now;
                        /* convert the timeout to a deadline once */
                        if (atvp->tv_sec || atvp->tv_usec) {
                                uint64_t now;
-                               
+
                                clock_get_uptime(&now);
                                nanoseconds_to_absolutetime((uint64_t)atvp->tv_sec * NSEC_PER_SEC +
                                clock_get_uptime(&now);
                                nanoseconds_to_absolutetime((uint64_t)atvp->tv_sec * NSEC_PER_SEC +
-                                                           atvp->tv_usec * NSEC_PER_USEC,
+                                                           atvp->tv_usec * (long)NSEC_PER_USEC,
                                                            &deadline);
                                if (now >= deadline) {
                                        /* non-blocking call */
                                                            &deadline);
                                if (now >= deadline) {
                                        /* non-blocking call */
@@ -2077,7 +2243,7 @@ kqueue_scan(struct kqueue *kq,
                        if (continuation) {
                                uthread_t ut = (uthread_t)get_bsdthread_info(current_thread());
                                struct _kqueue_scan *cont_args = &ut->uu_kevent.ss_kqueue_scan;
                        if (continuation) {
                                uthread_t ut = (uthread_t)get_bsdthread_info(current_thread());
                                struct _kqueue_scan *cont_args = &ut->uu_kevent.ss_kqueue_scan;
-                               
+
                                cont_args->call = callback;
                                cont_args->cont = continuation;
                                cont_args->deadline = deadline;
                                cont_args->call = callback;
                                cont_args->cont = continuation;
                                cont_args->deadline = deadline;
@@ -2087,7 +2253,9 @@ kqueue_scan(struct kqueue *kq,
                }
 
                /* go ahead and wait */
                }
 
                /* go ahead and wait */
-               wait_queue_assert_wait((wait_queue_t)kq->kq_wqs, KQ_EVENT, THREAD_ABORTSAFE, deadline);
+               wait_queue_assert_wait_with_leeway((wait_queue_t)kq->kq_wqs,
+                   KQ_EVENT, THREAD_ABORTSAFE, TIMEOUT_URGENCY_USER_NORMAL,
+                   deadline, 0);
                kq->kq_state |= KQ_SLEEP;
                kqunlock(kq);
                wait_result = thread_block_parameter(cont, kq);
                kq->kq_state |= KQ_SLEEP;
                kqunlock(kq);
                wait_result = thread_block_parameter(cont, kq);
@@ -2097,17 +2265,17 @@ kqueue_scan(struct kqueue *kq,
                case THREAD_AWAKENED:
                        continue;
                case THREAD_TIMED_OUT:
                case THREAD_AWAKENED:
                        continue;
                case THREAD_TIMED_OUT:
-                       return EWOULDBLOCK; 
+                       return (EWOULDBLOCK);
                case THREAD_INTERRUPTED:
                case THREAD_INTERRUPTED:
-                       return EINTR;
+                       return (EINTR);
                default:
                default:
-                       panic("kevent_scan - bad wait_result (%d)",
-                             wait_result);
+                       panic("%s: - bad wait_result (%d)", __func__,
+                           wait_result);
                        error = 0;
                }
        }
        kqunlock(kq);
                        error = 0;
                }
        }
        kqunlock(kq);
-       return error;
+       return (error);
 }
 
 
 }
 
 
@@ -2117,50 +2285,51 @@ kqueue_scan(struct kqueue *kq,
  */
 /*ARGSUSED*/
 static int
  */
 /*ARGSUSED*/
 static int
-kqueue_read(__unused struct fileproc *fp, 
-                       __unused struct uio *uio, 
-                       __unused int flags, 
-                       __unused vfs_context_t ctx)
+kqueue_read(__unused struct fileproc *fp,
+    __unused struct uio *uio,
+    __unused int flags,
+    __unused vfs_context_t ctx)
 {
        return (ENXIO);
 }
 
 /*ARGSUSED*/
 static int
 {
        return (ENXIO);
 }
 
 /*ARGSUSED*/
 static int
-kqueue_write(__unused struct fileproc *fp, 
-                        __unused struct uio *uio, 
-                        __unused int flags, 
-                        __unused vfs_context_t ctx)
+kqueue_write(__unused struct fileproc *fp,
+    __unused struct uio *uio,
+    __unused int flags,
+    __unused vfs_context_t ctx)
 {
        return (ENXIO);
 }
 
 /*ARGSUSED*/
 static int
 {
        return (ENXIO);
 }
 
 /*ARGSUSED*/
 static int
-kqueue_ioctl(__unused struct fileproc *fp, 
-                        __unused u_long com, 
-                        __unused caddr_t data, 
-                        __unused vfs_context_t ctx)
+kqueue_ioctl(__unused struct fileproc *fp,
+    __unused u_long com,
+    __unused caddr_t data,
+    __unused vfs_context_t ctx)
 {
        return (ENOTTY);
 }
 
 /*ARGSUSED*/
 static int
 {
        return (ENOTTY);
 }
 
 /*ARGSUSED*/
 static int
-kqueue_select(struct fileproc *fp, int which, void *wql, __unused vfs_context_t ctx)
+kqueue_select(struct fileproc *fp, int which, void *wql,
+    __unused vfs_context_t ctx)
 {
        struct kqueue *kq = (struct kqueue *)fp->f_data;
        struct knote *kn;
        struct kqtailq inprocessq;
        int retnum = 0;
 {
        struct kqueue *kq = (struct kqueue *)fp->f_data;
        struct knote *kn;
        struct kqtailq inprocessq;
        int retnum = 0;
-       
+
        if (which != FREAD)
        if (which != FREAD)
-               return 0;
+               return (0);
 
        TAILQ_INIT(&inprocessq);
 
        kqlock(kq);
 
        TAILQ_INIT(&inprocessq);
 
        kqlock(kq);
-       /* 
+       /*
         * If this is the first pass, link the wait queue associated with the
         * the kqueue onto the wait queue set for the select().  Normally we
         * use selrecord() for this, but it uses the wait queue within the
         * If this is the first pass, link the wait queue associated with the
         * the kqueue onto the wait queue set for the select().  Normally we
         * use selrecord() for this, but it uses the wait queue within the
@@ -2169,17 +2338,17 @@ kqueue_select(struct fileproc *fp, int which, void *wql, __unused vfs_context_t
         * (The select() call will unlink them when it ends).
         */
        if (wql != NULL) {
         * (The select() call will unlink them when it ends).
         */
        if (wql != NULL) {
-               thread_t        cur_act = current_thread();
+               thread_t cur_act = current_thread();
                struct uthread * ut = get_bsdthread_info(cur_act);
 
                kq->kq_state |= KQ_SEL;
                wait_queue_link_noalloc((wait_queue_t)kq->kq_wqs, ut->uu_wqset,
                struct uthread * ut = get_bsdthread_info(cur_act);
 
                kq->kq_state |= KQ_SEL;
                wait_queue_link_noalloc((wait_queue_t)kq->kq_wqs, ut->uu_wqset,
-                                       (wait_queue_link_t)wql);
+                   (wait_queue_link_t)wql);
        }
 
        if (kqueue_begin_processing(kq) == -1) {
                kqunlock(kq);
        }
 
        if (kqueue_begin_processing(kq) == -1) {
                kqunlock(kq);
-               return 0;
+               return (0);
        }
 
        if (kq->kq_count != 0) {
        }
 
        if (kq->kq_count != 0) {
@@ -2190,7 +2359,7 @@ kqueue_select(struct fileproc *fp, int which, void *wql, __unused vfs_context_t
                 * list of knotes to see, and peek at the stay-
                 * queued ones to be really sure.
                 */
                 * list of knotes to see, and peek at the stay-
                 * queued ones to be really sure.
                 */
-               while ((kn = (struct knote*)TAILQ_FIRST(&kq->kq_head)) != NULL) {
+               while ((kn = (struct knote *)TAILQ_FIRST(&kq->kq_head)) != NULL) {
                        if ((kn->kn_status & KN_STAYQUEUED) == 0) {
                                retnum = 1;
                                goto out;
                        if ((kn->kn_status & KN_STAYQUEUED) == 0) {
                                retnum = 1;
                                goto out;
@@ -2211,7 +2380,7 @@ kqueue_select(struct fileproc *fp, int which, void *wql, __unused vfs_context_t
                                } else {
                                        retnum = 0;
                                }
                                } else {
                                        retnum = 0;
                                }
-                       } 
+                       }
                }
        }
 
                }
        }
 
@@ -2225,7 +2394,7 @@ out:
 
        kqueue_end_processing(kq);
        kqunlock(kq);
 
        kqueue_end_processing(kq);
        kqunlock(kq);
-       return retnum;
+       return (retnum);
 }
 
 /*
 }
 
 /*
@@ -2270,7 +2439,7 @@ kqueue_kqfilter(__unused struct fileproc *fp, struct knote *kn, __unused vfs_con
         */
 
        kqlock(parentkq);
         */
 
        kqlock(parentkq);
-       if (parentkq->kq_level > 0 && 
+       if (parentkq->kq_level > 0 &&
            parentkq->kq_level < kq->kq_level)
        {
                kqunlock(parentkq);
            parentkq->kq_level < kq->kq_level)
        {
                kqunlock(parentkq);
@@ -2305,15 +2474,14 @@ kqueue_drain(struct fileproc *fp, __unused vfs_context_t ctx)
        kqlock(kq);
        kqueue_wakeup(kq, 1);
        kqunlock(kq);
        kqlock(kq);
        kqueue_wakeup(kq, 1);
        kqunlock(kq);
-       return 0;
+       return (0);
 }
 
 /*ARGSUSED*/
 int
 }
 
 /*ARGSUSED*/
 int
-kqueue_stat(struct fileproc *fp, void *ub, int isstat64,  __unused vfs_context_t ctx)
+kqueue_stat(struct kqueue *kq, void *ub, int isstat64, proc_t p)
 {
 {
-
-       struct kqueue *kq = (struct kqueue *)fp->f_data;
+       kqlock(kq);
        if (isstat64 != 0) {
                struct stat64 *sb64 = (struct stat64 *)ub;
 
        if (isstat64 != 0) {
                struct stat64 *sb64 = (struct stat64 *)ub;
 
@@ -2322,7 +2490,7 @@ kqueue_stat(struct fileproc *fp, void *ub, int isstat64,  __unused vfs_context_t
                if (kq->kq_state & KQ_KEV64)
                        sb64->st_blksize = sizeof(struct kevent64_s);
                else
                if (kq->kq_state & KQ_KEV64)
                        sb64->st_blksize = sizeof(struct kevent64_s);
                else
-                       sb64->st_blksize = sizeof(struct kevent);
+                       sb64->st_blksize = IS_64BIT_PROCESS(p) ? sizeof(struct user64_kevent) : sizeof(struct user32_kevent);
                sb64->st_mode = S_IFIFO;
        } else {
                struct stat *sb = (struct stat *)ub;
                sb64->st_mode = S_IFIFO;
        } else {
                struct stat *sb = (struct stat *)ub;
@@ -2332,10 +2500,10 @@ kqueue_stat(struct fileproc *fp, void *ub, int isstat64,  __unused vfs_context_t
                if (kq->kq_state & KQ_KEV64)
                        sb->st_blksize = sizeof(struct kevent64_s);
                else
                if (kq->kq_state & KQ_KEV64)
                        sb->st_blksize = sizeof(struct kevent64_s);
                else
-                       sb->st_blksize = sizeof(struct kevent);
+                       sb->st_blksize = IS_64BIT_PROCESS(p) ? sizeof(struct user64_kevent) : sizeof(struct user32_kevent);
                sb->st_mode = S_IFIFO;
        }
                sb->st_mode = S_IFIFO;
        }
-
+       kqunlock(kq);
        return (0);
 }
 
        return (0);
 }
 
@@ -2347,8 +2515,8 @@ kqueue_wakeup(struct kqueue *kq, int closed)
 {
        if ((kq->kq_state & (KQ_SLEEP | KQ_SEL)) != 0 || kq->kq_nprocess > 0) {
                kq->kq_state &= ~(KQ_SLEEP | KQ_SEL);
 {
        if ((kq->kq_state & (KQ_SLEEP | KQ_SEL)) != 0 || kq->kq_nprocess > 0) {
                kq->kq_state &= ~(KQ_SLEEP | KQ_SEL);
-               wait_queue_wakeup_all((wait_queue_t)kq->kq_wqs, KQ_EVENT, 
-                                     (closed) ? THREAD_INTERRUPTED : THREAD_AWAKENED);
+               wait_queue_wakeup_all((wait_queue_t)kq->kq_wqs, KQ_EVENT,
+                   (closed) ? THREAD_INTERRUPTED : THREAD_AWAKENED);
        }
 }
 
        }
 }
 
@@ -2404,7 +2572,7 @@ knote_attach(struct klist *list, struct knote *kn)
 {
        int ret = SLIST_EMPTY(list);
        SLIST_INSERT_HEAD(list, kn, kn_selnext);
 {
        int ret = SLIST_EMPTY(list);
        SLIST_INSERT_HEAD(list, kn, kn_selnext);
-       return ret;
+       return (ret);
 }
 
 /*
 }
 
 /*
@@ -2415,12 +2583,12 @@ int
 knote_detach(struct klist *list, struct knote *kn)
 {
        SLIST_REMOVE(list, kn, knote, kn_selnext);
 knote_detach(struct klist *list, struct knote *kn)
 {
        SLIST_REMOVE(list, kn, knote, kn_selnext);
-       return SLIST_EMPTY(list);
+       return (SLIST_EMPTY(list));
 }
 
 /*
  * For a given knote, link a provided wait queue directly with the kqueue.
 }
 
 /*
  * For a given knote, link a provided wait queue directly with the kqueue.
- * Wakeups will happen via recursive wait queue support.  But nothing will move 
+ * Wakeups will happen via recursive wait queue support.  But nothing will move
  * the knote to the active list at wakeup (nothing calls knote()).  Instead,
  * we permanently enqueue them here.
  *
  * the knote to the active list at wakeup (nothing calls knote()).  Instead,
  * we permanently enqueue them here.
  *
@@ -2437,9 +2605,9 @@ knote_link_wait_queue(struct knote *kn, struct wait_queue *wq, wait_queue_link_t
        kr = wait_queue_link_noalloc(wq, kq->kq_wqs, wql);
        if (kr == KERN_SUCCESS) {
                knote_markstayqueued(kn);
        kr = wait_queue_link_noalloc(wq, kq->kq_wqs, wql);
        if (kr == KERN_SUCCESS) {
                knote_markstayqueued(kn);
-               return 0;
+               return (0);
        } else {
        } else {
-               return EINVAL;
+               return (EINVAL);
        }
 }
 
        }
 }
 
@@ -2459,11 +2627,8 @@ knote_unlink_wait_queue(struct knote *kn, struct wait_queue *wq, wait_queue_link
        kern_return_t kr;
 
        kr = wait_queue_unlink_nofree(wq, kq->kq_wqs, wqlp);
        kern_return_t kr;
 
        kr = wait_queue_unlink_nofree(wq, kq->kq_wqs, wqlp);
-       kqlock(kq);
-       kn->kn_status &= ~KN_STAYQUEUED;
-       knote_dequeue(kn);
-       kqunlock(kq);
-       return (kr != KERN_SUCCESS) ? EINVAL : 0;
+       knote_clearstayqueued(kn);
+       return ((kr != KERN_SUCCESS) ? EINVAL : 0);
 }
 
 /*
 }
 
 /*
@@ -2471,7 +2636,7 @@ knote_unlink_wait_queue(struct knote *kn, struct wait_queue *wq, wait_queue_link
  *
  * Essentially an inlined knote_remove & knote_drop
  * when we know for sure that the thing is a file
  *
  * Essentially an inlined knote_remove & knote_drop
  * when we know for sure that the thing is a file
- * 
+ *
  * Entered with the proc_fd lock already held.
  * It returns the same way, but may drop it temporarily.
  */
  * Entered with the proc_fd lock already held.
  * It returns the same way, but may drop it temporarily.
  */
@@ -2487,7 +2652,8 @@ knote_fdclose(struct proc *p, int fd)
                struct kqueue *kq = kn->kn_kq;
 
                if (kq->kq_p != p)
                struct kqueue *kq = kn->kn_kq;
 
                if (kq->kq_p != p)
-                       panic("knote_fdclose: proc mismatch (kq->kq_p=%p != p=%p)", kq->kq_p, p);
+                       panic("%s: proc mismatch (kq->kq_p=%p != p=%p)",
+                           __func__, kq->kq_p, p);
 
                kqlock(kq);
                proc_fdunlock(p);
 
                kqlock(kq);
                proc_fdunlock(p);
@@ -2503,7 +2669,7 @@ knote_fdclose(struct proc *p, int fd)
                        kn->kn_fop->f_detach(kn);
                        knote_drop(kn, p);
                }
                        kn->kn_fop->f_detach(kn);
                        knote_drop(kn, p);
                }
-                       
+
                proc_fdlock(p);
 
                /* the fd tables may have changed - start over */
                proc_fdlock(p);
 
                /* the fd tables may have changed - start over */
@@ -2526,10 +2692,10 @@ knote_fdpattach(struct knote *kn, struct filedesc *fdp, struct proc *p)
                if ((u_int)fdp->fd_knlistsize <= kn->kn_id) {
                        u_int size = 0;
 
                if ((u_int)fdp->fd_knlistsize <= kn->kn_id) {
                        u_int size = 0;
 
-                       if (kn->kn_id >= (uint64_t)p->p_rlimit[RLIMIT_NOFILE].rlim_cur 
+                       if (kn->kn_id >= (uint64_t)p->p_rlimit[RLIMIT_NOFILE].rlim_cur
                            || kn->kn_id >= (uint64_t)maxfiles)
                                return (EINVAL);
                            || kn->kn_id >= (uint64_t)maxfiles)
                                return (EINVAL);
-               
+
                        /* have to grow the fd_knlist */
                        size = fdp->fd_knlistsize;
                        while (size <= kn->kn_id)
                        /* have to grow the fd_knlist */
                        size = fdp->fd_knlistsize;
                        while (size <= kn->kn_id)
@@ -2539,15 +2705,15 @@ knote_fdpattach(struct knote *kn, struct filedesc *fdp, struct proc *p)
                                return (EINVAL);
 
                        MALLOC(list, struct klist *,
                                return (EINVAL);
 
                        MALLOC(list, struct klist *,
-                              size * sizeof(struct klist *), M_KQUEUE, M_WAITOK);
+                           size * sizeof(struct klist *), M_KQUEUE, M_WAITOK);
                        if (list == NULL)
                                return (ENOMEM);
                        if (list == NULL)
                                return (ENOMEM);
-                       
+
                        bcopy((caddr_t)fdp->fd_knlist, (caddr_t)list,
                        bcopy((caddr_t)fdp->fd_knlist, (caddr_t)list,
-                             fdp->fd_knlistsize * sizeof(struct klist *));
+                           fdp->fd_knlistsize * sizeof(struct klist *));
                        bzero((caddr_t)list +
                        bzero((caddr_t)list +
-                             fdp->fd_knlistsize * sizeof(struct klist *),
-                             (size - fdp->fd_knlistsize) * sizeof(struct klist *));
+                           fdp->fd_knlistsize * sizeof(struct klist *),
+                           (size - fdp->fd_knlistsize) * sizeof(struct klist *));
                        FREE(fdp->fd_knlist, M_KQUEUE);
                        fdp->fd_knlist = list;
                        fdp->fd_knlistsize = size;
                        FREE(fdp->fd_knlist, M_KQUEUE);
                        fdp->fd_knlist = list;
                        fdp->fd_knlistsize = size;
@@ -2569,7 +2735,7 @@ knote_drop(struct knote *kn, __unused struct proc *ctxp)
 {
        struct kqueue *kq = kn->kn_kq;
        struct proc *p = kq->kq_p;
 {
        struct kqueue *kq = kn->kn_kq;
        struct proc *p = kq->kq_p;
-        struct filedesc *fdp = p->p_fd;
+       struct filedesc *fdp = p->p_fd;
        struct klist *list;
        int needswakeup;
 
        struct klist *list;
        int needswakeup;
 
@@ -2587,7 +2753,8 @@ knote_drop(struct knote *kn, __unused struct proc *ctxp)
        proc_fdunlock(p);
 
        if (needswakeup)
        proc_fdunlock(p);
 
        if (needswakeup)
-               wait_queue_wakeup_all((wait_queue_t)kq->kq_wqs, &kn->kn_status, THREAD_AWAKENED);
+               wait_queue_wakeup_all((wait_queue_t)kq->kq_wqs, &kn->kn_status,
+                   THREAD_AWAKENED);
 
        if (kn->kn_fop->f_isfd)
                fp_drop(p, kn->kn_id, kn->kn_fp, 0);
 
        if (kn->kn_fop->f_isfd)
                fp_drop(p, kn->kn_id, kn->kn_fp, 0);
@@ -2613,7 +2780,7 @@ knote_activate(struct knote *kn, int propagate)
 /* called with kqueue lock held */
 static void
 knote_deactivate(struct knote *kn)
 /* called with kqueue lock held */
 static void
 knote_deactivate(struct knote *kn)
-{      
+{
        kn->kn_status &= ~KN_ACTIVE;
        knote_dequeue(kn);
 }
        kn->kn_status &= ~KN_ACTIVE;
        knote_dequeue(kn);
 }
@@ -2627,7 +2794,7 @@ knote_enqueue(struct knote *kn)
                struct kqtailq *tq = kn->kn_tq;
                struct kqueue *kq = kn->kn_kq;
 
                struct kqtailq *tq = kn->kn_tq;
                struct kqueue *kq = kn->kn_kq;
 
-               TAILQ_INSERT_TAIL(tq, kn, kn_tqe); 
+               TAILQ_INSERT_TAIL(tq, kn, kn_tqe);
                kn->kn_status |= KN_QUEUED;
                kq->kq_count++;
        }
                kn->kn_status |= KN_QUEUED;
                kq->kq_count++;
        }
@@ -2642,7 +2809,7 @@ knote_dequeue(struct knote *kn)
        if ((kn->kn_status & (KN_QUEUED | KN_STAYQUEUED)) == KN_QUEUED) {
                struct kqtailq *tq = kn->kn_tq;
 
        if ((kn->kn_status & (KN_QUEUED | KN_STAYQUEUED)) == KN_QUEUED) {
                struct kqtailq *tq = kn->kn_tq;
 
-               TAILQ_REMOVE(tq, kn, kn_tqe); 
+               TAILQ_REMOVE(tq, kn, kn_tqe);
                kn->kn_tq = &kq->kq_head;
                kn->kn_status &= ~KN_QUEUED;
                kq->kq_count--;
                kn->kn_tq = &kq->kq_head;
                kn->kn_status &= ~KN_QUEUED;
                kq->kq_count--;
@@ -2652,10 +2819,11 @@ knote_dequeue(struct knote *kn)
 void
 knote_init(void)
 {
 void
 knote_init(void)
 {
-       knote_zone = zinit(sizeof(struct knote), 8192*sizeof(struct knote), 8192, "knote zone");
+       knote_zone = zinit(sizeof(struct knote), 8192*sizeof(struct knote),
+           8192, "knote zone");
 
        /* allocate kq lock group attribute and group */
 
        /* allocate kq lock group attribute and group */
-       kq_lck_grp_attr= lck_grp_attr_alloc_init();
+       kq_lck_grp_attr = lck_grp_attr_alloc_init();
 
        kq_lck_grp = lck_grp_alloc_init("kqueue",  kq_lck_grp_attr);
 
 
        kq_lck_grp = lck_grp_alloc_init("kqueue",  kq_lck_grp_attr);
 
@@ -2664,11 +2832,16 @@ knote_init(void)
 
        /* Initialize the timer filter lock */
        lck_mtx_init(&_filt_timerlock, kq_lck_grp, kq_lck_attr);
 
        /* Initialize the timer filter lock */
        lck_mtx_init(&_filt_timerlock, kq_lck_grp, kq_lck_attr);
-       
+
 #if VM_PRESSURE_EVENTS
        /* Initialize the vm pressure list lock */
        vm_pressure_init(kq_lck_grp, kq_lck_attr);
 #endif
 #if VM_PRESSURE_EVENTS
        /* Initialize the vm pressure list lock */
        vm_pressure_init(kq_lck_grp, kq_lck_attr);
 #endif
+
+#if CONFIG_MEMORYSTATUS
+       /* Initialize the memorystatus list lock */
+       memorystatus_kevent_init(kq_lck_grp, kq_lck_attr);
+#endif
 }
 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL)
 
 }
 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL)
 
@@ -2695,264 +2868,620 @@ knote_free(struct knote *kn)
 #include <sys/sys_domain.h>
 #include <sys/syslog.h>
 
 #include <sys/sys_domain.h>
 #include <sys/syslog.h>
 
+#ifndef ROUNDUP64
+#define        ROUNDUP64(x) P2ROUNDUP((x), sizeof (u_int64_t))
+#endif
+
+#ifndef ADVANCE64
+#define        ADVANCE64(p, n) (void*)((char *)(p) + ROUNDUP64(n))
+#endif
+
+static lck_grp_attr_t *kev_lck_grp_attr;
+static lck_attr_t *kev_lck_attr;
+static lck_grp_t *kev_lck_grp;
+static decl_lck_rw_data(,kev_lck_data);
+static lck_rw_t *kev_rwlock = &kev_lck_data;
 
 static int kev_attach(struct socket *so, int proto, struct proc *p);
 static int kev_detach(struct socket *so);
 
 static int kev_attach(struct socket *so, int proto, struct proc *p);
 static int kev_detach(struct socket *so);
-static int kev_control(struct socket *so, u_long cmd, caddr_t data, struct ifnet *ifp, struct proc *p);
-
-struct pr_usrreqs event_usrreqs = {
-     pru_abort_notsupp, pru_accept_notsupp, kev_attach, pru_bind_notsupp, pru_connect_notsupp,
-     pru_connect2_notsupp, kev_control, kev_detach, pru_disconnect_notsupp,
-     pru_listen_notsupp, pru_peeraddr_notsupp, pru_rcvd_notsupp, pru_rcvoob_notsupp,
-     pru_send_notsupp, pru_sense_null, pru_shutdown_notsupp, pru_sockaddr_notsupp,
-     pru_sosend_notsupp, soreceive, pru_sopoll_notsupp
+static int kev_control(struct socket *so, u_long cmd, caddr_t data,
+    struct ifnet *ifp, struct proc *p);
+static lck_mtx_t * event_getlock(struct socket *, int);
+static int event_lock(struct socket *, int, void *);
+static int event_unlock(struct socket *, int, void *);
+
+static int event_sofreelastref(struct socket *);
+static void kev_delete(struct kern_event_pcb *);
+
+static struct pr_usrreqs event_usrreqs = {
+       .pru_attach =           kev_attach,
+       .pru_control =          kev_control,
+       .pru_detach =           kev_detach,
+       .pru_soreceive =        soreceive,
 };
 
 };
 
-struct protosw eventsw[] = {
-     {
-         .pr_type = SOCK_RAW,
-         .pr_domain = &systemdomain,
-         .pr_protocol = SYSPROTO_EVENT,
-         .pr_flags = PR_ATOMIC,
-         .pr_usrreqs = &event_usrreqs,
-     }
+static struct protosw eventsw[] = {
+{
+       .pr_type =              SOCK_RAW,
+       .pr_protocol =          SYSPROTO_EVENT,
+       .pr_flags =             PR_ATOMIC,
+       .pr_usrreqs =           &event_usrreqs,
+       .pr_lock =              event_lock,
+       .pr_unlock =            event_unlock,
+       .pr_getlock =           event_getlock,
+}
 };
 
 };
 
+__private_extern__ int kevt_getstat SYSCTL_HANDLER_ARGS;
+__private_extern__ int kevt_pcblist SYSCTL_HANDLER_ARGS;
+
+SYSCTL_NODE(_net_systm, OID_AUTO, kevt,
+       CTLFLAG_RW|CTLFLAG_LOCKED, 0, "Kernel event family");
+
+struct kevtstat kevtstat;
+SYSCTL_PROC(_net_systm_kevt, OID_AUTO, stats,
+    CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0,
+    kevt_getstat, "S,kevtstat", "");
+
+SYSCTL_PROC(_net_systm_kevt, OID_AUTO, pcblist,
+       CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0,
+       kevt_pcblist, "S,xkevtpcb", "");
+
+static lck_mtx_t *
+event_getlock(struct socket *so, int locktype)
+{
+#pragma unused(locktype)
+       struct kern_event_pcb *ev_pcb = (struct kern_event_pcb *)so->so_pcb;
+
+       if (so->so_pcb != NULL)  {
+               if (so->so_usecount < 0)
+                       panic("%s: so=%p usecount=%d lrh= %s\n", __func__,
+                           so, so->so_usecount, solockhistory_nr(so));
+                       /* NOTREACHED */
+       } else {
+               panic("%s: so=%p NULL NO so_pcb %s\n", __func__,
+                   so, solockhistory_nr(so));
+               /* NOTREACHED */
+       }
+       return (&ev_pcb->evp_mtx);
+}
+
+static int
+event_lock(struct socket *so, int refcount, void *lr)
+{
+       void *lr_saved;
+
+       if (lr == NULL)
+               lr_saved = __builtin_return_address(0);
+       else
+               lr_saved = lr;
+
+       if (so->so_pcb != NULL) {
+               lck_mtx_lock(&((struct kern_event_pcb *)so->so_pcb)->evp_mtx);
+       } else  {
+               panic("%s: so=%p NO PCB! lr=%p lrh= %s\n", __func__,
+                   so, lr_saved, solockhistory_nr(so));
+               /* NOTREACHED */
+       }
+
+       if (so->so_usecount < 0) {
+               panic("%s: so=%p so_pcb=%p lr=%p ref=%d lrh= %s\n", __func__,
+                   so, so->so_pcb, lr_saved, so->so_usecount,
+                   solockhistory_nr(so));
+               /* NOTREACHED */
+       }
+
+       if (refcount)
+               so->so_usecount++;
+
+       so->lock_lr[so->next_lock_lr] = lr_saved;
+       so->next_lock_lr = (so->next_lock_lr+1) % SO_LCKDBG_MAX;
+       return (0);
+}
+
+static int
+event_unlock(struct socket *so, int refcount, void *lr)
+{
+       void *lr_saved;
+       lck_mtx_t *mutex_held;
+
+       if (lr == NULL)
+               lr_saved = __builtin_return_address(0);
+       else
+               lr_saved = lr;
+
+       if (refcount)
+               so->so_usecount--;
+
+       if (so->so_usecount < 0) {
+               panic("%s: so=%p usecount=%d lrh= %s\n", __func__,
+                   so, so->so_usecount, solockhistory_nr(so));
+               /* NOTREACHED */
+       }
+       if (so->so_pcb == NULL) {
+               panic("%s: so=%p NO PCB usecount=%d lr=%p lrh= %s\n", __func__,
+                   so, so->so_usecount, (void *)lr_saved,
+                   solockhistory_nr(so));
+               /* NOTREACHED */
+       }
+       mutex_held = (&((struct kern_event_pcb *)so->so_pcb)->evp_mtx);
+
+       lck_mtx_assert(mutex_held, LCK_MTX_ASSERT_OWNED);
+       so->unlock_lr[so->next_unlock_lr] = lr_saved;
+       so->next_unlock_lr = (so->next_unlock_lr+1) % SO_LCKDBG_MAX;
+
+       if (so->so_usecount == 0) {
+               VERIFY(so->so_flags & SOF_PCBCLEARING);
+               event_sofreelastref(so);
+       } else {
+               lck_mtx_unlock(mutex_held);
+       }
+
+       return (0);
+}
+
+static int
+event_sofreelastref(struct socket *so)
+{
+       struct kern_event_pcb *ev_pcb = (struct kern_event_pcb *)so->so_pcb;
+
+       lck_mtx_assert(&(ev_pcb->evp_mtx), LCK_MTX_ASSERT_OWNED);
+
+       so->so_pcb = NULL;
+
+       /*
+        * Disable upcall in the event another thread is in kev_post_msg()
+        * appending record to the receive socket buffer, since sbwakeup()
+        * may release the socket lock otherwise.
+        */
+       so->so_rcv.sb_flags &= ~SB_UPCALL;
+       so->so_snd.sb_flags &= ~SB_UPCALL;
+       so->so_event = sonullevent;
+       lck_mtx_unlock(&(ev_pcb->evp_mtx));
+
+       lck_mtx_assert(&(ev_pcb->evp_mtx), LCK_MTX_ASSERT_NOTOWNED);
+       lck_rw_lock_exclusive(kev_rwlock);
+       LIST_REMOVE(ev_pcb, evp_link);
+       kevtstat.kes_pcbcount--;
+       kevtstat.kes_gencnt++;
+       lck_rw_done(kev_rwlock);
+       kev_delete(ev_pcb);
+
+       sofreelastref(so, 1);
+       return (0);
+}
+
+static int event_proto_count = (sizeof (eventsw) / sizeof (struct protosw));
+
 static
 struct kern_event_head kern_event_head;
 
 static u_int32_t static_event_id = 0;
 static
 struct kern_event_head kern_event_head;
 
 static u_int32_t static_event_id = 0;
-struct domain *sysdom = &systemdomain;
-static lck_mtx_t *sys_mtx;
+
+#define        EVPCB_ZONE_MAX          65536
+#define        EVPCB_ZONE_NAME         "kerneventpcb"
+static struct zone *ev_pcb_zone;
 
 /*
 
 /*
- * Install the protosw's for the NKE manager.  Invoked at
- *  extension load time
+ * Install the protosw's for the NKE manager.  Invoked at extension load time
  */
  */
-int
-kern_event_init(void)
+void
+kern_event_init(struct domain *dp)
 {
 {
-    int retval;
+       struct protosw *pr;
+       int i;
+
+       VERIFY(!(dp->dom_flags & DOM_INITIALIZED));
+       VERIFY(dp == systemdomain);
+
+       kev_lck_grp_attr = lck_grp_attr_alloc_init();
+       if (kev_lck_grp_attr == NULL) {
+               panic("%s: lck_grp_attr_alloc_init failed\n", __func__);
+               /* NOTREACHED */
+       }
+
+       kev_lck_grp = lck_grp_alloc_init("Kernel Event Protocol",
+           kev_lck_grp_attr);
+       if (kev_lck_grp == NULL) {
+               panic("%s: lck_grp_alloc_init failed\n", __func__);
+               /* NOTREACHED */
+       }
+
+       kev_lck_attr = lck_attr_alloc_init();
+       if (kev_lck_attr == NULL) {
+               panic("%s: lck_attr_alloc_init failed\n", __func__);
+               /* NOTREACHED */
+       }
+
+       lck_rw_init(kev_rwlock, kev_lck_grp, kev_lck_attr);
+       if (kev_rwlock == NULL) {
+               panic("%s: lck_mtx_alloc_init failed\n", __func__);
+               /* NOTREACHED */
+       }
+
+       for (i = 0, pr = &eventsw[0]; i < event_proto_count; i++, pr++)
+               net_add_proto(pr, dp, 1);
 
 
-    if ((retval = net_add_proto(eventsw, &systemdomain)) != 0) {
-           log(LOG_WARNING, "Can't install kernel events protocol (%d)\n", retval);
-            return(retval);
+       ev_pcb_zone = zinit(sizeof(struct kern_event_pcb),
+           EVPCB_ZONE_MAX * sizeof(struct kern_event_pcb), 0, EVPCB_ZONE_NAME);
+       if (ev_pcb_zone == NULL) {
+               panic("%s: failed allocating ev_pcb_zone", __func__);
+               /* NOTREACHED */
        }
        }
-   
-    /*
-     * Use the domain mutex for all system event sockets
-     */ 
-    sys_mtx = sysdom->dom_mtx;
-       
-    return(KERN_SUCCESS);
+       zone_change(ev_pcb_zone, Z_EXPAND, TRUE);
+       zone_change(ev_pcb_zone, Z_CALLERACCT, TRUE);
 }
 
 static int
 kev_attach(struct socket *so, __unused int proto, __unused struct proc *p)
 {
 }
 
 static int
 kev_attach(struct socket *so, __unused int proto, __unused struct proc *p)
 {
-     int error;
-     struct kern_event_pcb  *ev_pcb;
+       int error = 0;
+       struct kern_event_pcb *ev_pcb;
 
 
-     error = soreserve(so, KEV_SNDSPACE, KEV_RECVSPACE);
-     if (error)
-          return error;
+       error = soreserve(so, KEV_SNDSPACE, KEV_RECVSPACE);
+       if (error != 0)
+               return (error);
 
 
-     MALLOC(ev_pcb, struct kern_event_pcb *, sizeof(struct kern_event_pcb), M_PCB, M_WAITOK);
-     if (ev_pcb == 0)
-         return ENOBUFS;
+       if ((ev_pcb = (struct kern_event_pcb *)zalloc(ev_pcb_zone)) == NULL) {
+               return (ENOBUFS);
+       }
+       bzero(ev_pcb, sizeof(struct kern_event_pcb));
+       lck_mtx_init(&ev_pcb->evp_mtx, kev_lck_grp, kev_lck_attr);
 
 
-     ev_pcb->ev_socket = so;
-     ev_pcb->vendor_code_filter = 0xffffffff;
+       ev_pcb->evp_socket = so;
+       ev_pcb->evp_vendor_code_filter = 0xffffffff;
 
 
-     so->so_pcb = (caddr_t) ev_pcb;
-     lck_mtx_lock(sys_mtx);
-     LIST_INSERT_HEAD(&kern_event_head, ev_pcb, ev_link);
-     lck_mtx_unlock(sys_mtx);
+       so->so_pcb = (caddr_t) ev_pcb;
+       lck_rw_lock_exclusive(kev_rwlock);
+       LIST_INSERT_HEAD(&kern_event_head, ev_pcb, evp_link);
+       kevtstat.kes_pcbcount++;
+       kevtstat.kes_gencnt++;
+       lck_rw_done(kev_rwlock);
 
 
-     return 0;
+       return (error);
 }
 
 }
 
+static void
+kev_delete(struct kern_event_pcb *ev_pcb)
+{
+       VERIFY(ev_pcb != NULL);
+       lck_mtx_destroy(&ev_pcb->evp_mtx, kev_lck_grp);
+       zfree(ev_pcb_zone, ev_pcb);
+}
 
 static int
 kev_detach(struct socket *so)
 {
 
 static int
 kev_detach(struct socket *so)
 {
-     struct kern_event_pcb *ev_pcb = (struct kern_event_pcb *) so->so_pcb;
+       struct kern_event_pcb *ev_pcb = (struct kern_event_pcb *) so->so_pcb;
 
 
-     if (ev_pcb != 0) {
-               LIST_REMOVE(ev_pcb, ev_link);
-               FREE(ev_pcb, M_PCB);
-               so->so_pcb = 0;
+       if (ev_pcb != NULL) {
+               soisdisconnected(so);
                so->so_flags |= SOF_PCBCLEARING;
                so->so_flags |= SOF_PCBCLEARING;
-     }
+       }
 
 
-     return 0;
+       return (0);
 }
 
 /*
  * For now, kev_vendor_code and mbuf_tags use the same
  * mechanism.
  */
 }
 
 /*
  * For now, kev_vendor_code and mbuf_tags use the same
  * mechanism.
  */
-
 errno_t kev_vendor_code_find(
        const char      *string,
        u_int32_t       *out_vendor_code)
 {
        if (strlen(string) >= KEV_VENDOR_CODE_MAX_STR_LEN) {
 errno_t kev_vendor_code_find(
        const char      *string,
        u_int32_t       *out_vendor_code)
 {
        if (strlen(string) >= KEV_VENDOR_CODE_MAX_STR_LEN) {
-               return EINVAL;
+               return (EINVAL);
        }
        }
-       return net_str_id_find_internal(string, out_vendor_code, NSI_VENDOR_CODE, 1);
+       return (net_str_id_find_internal(string, out_vendor_code,
+           NSI_VENDOR_CODE, 1));
 }
 
 }
 
-errno_t  kev_msg_post(struct kev_msg *event_msg)
+errno_t
+kev_msg_post(struct kev_msg *event_msg)
 {
 {
-       mbuf_tag_id_t   min_vendor, max_vendor;
-       
+       mbuf_tag_id_t min_vendor, max_vendor;
+
        net_str_id_first_last(&min_vendor, &max_vendor, NSI_VENDOR_CODE);
        net_str_id_first_last(&min_vendor, &max_vendor, NSI_VENDOR_CODE);
-       
+
        if (event_msg == NULL)
        if (event_msg == NULL)
-               return EINVAL;
-       
-       /* Limit third parties to posting events for registered vendor codes only */
+               return (EINVAL);
+
+       /* 
+        * Limit third parties to posting events for registered vendor codes
+        * only
+        */
        if (event_msg->vendor_code < min_vendor ||
        if (event_msg->vendor_code < min_vendor ||
-               event_msg->vendor_code > max_vendor)
-       {
-               return EINVAL;
+           event_msg->vendor_code > max_vendor) {
+               OSIncrementAtomic64((SInt64 *)&kevtstat.kes_badvendor);
+               return (EINVAL);
        }
        }
-       
-       return kev_post_msg(event_msg);
+       return (kev_post_msg(event_msg));
 }
 }
-       
 
 
-int  kev_post_msg(struct kev_msg *event_msg)
+int
+kev_post_msg(struct kev_msg *event_msg)
 {
 {
-     struct mbuf *m, *m2;
-     struct kern_event_pcb  *ev_pcb;
-     struct kern_event_msg  *ev;
-     char              *tmp;
-     u_int32_t     total_size;
-     int               i;
+       struct mbuf *m, *m2;
+       struct kern_event_pcb *ev_pcb;
+       struct kern_event_msg *ev;
+       char *tmp;
+       u_int32_t total_size;
+       int i;
 
        /* Verify the message is small enough to fit in one mbuf w/o cluster */
        total_size = KEV_MSG_HEADER_SIZE;
 
        /* Verify the message is small enough to fit in one mbuf w/o cluster */
        total_size = KEV_MSG_HEADER_SIZE;
-       
+
        for (i = 0; i < 5; i++) {
                if (event_msg->dv[i].data_length == 0)
                        break;
                total_size += event_msg->dv[i].data_length;
        }
        for (i = 0; i < 5; i++) {
                if (event_msg->dv[i].data_length == 0)
                        break;
                total_size += event_msg->dv[i].data_length;
        }
-       
+
        if (total_size > MLEN) {
        if (total_size > MLEN) {
-               return EMSGSIZE;
-       }
-
-     m = m_get(M_DONTWAIT, MT_DATA);
-     if (m == 0)
-         return ENOBUFS;
-
-     ev = mtod(m, struct kern_event_msg *);
-     total_size = KEV_MSG_HEADER_SIZE;
-
-     tmp = (char *) &ev->event_data[0];
-     for (i = 0; i < 5; i++) {
-         if (event_msg->dv[i].data_length == 0)
-              break;
-
-         total_size += event_msg->dv[i].data_length;
-         bcopy(event_msg->dv[i].data_ptr, tmp, 
-               event_msg->dv[i].data_length);
-         tmp += event_msg->dv[i].data_length;
-     }
-
-     ev->id = ++static_event_id;
-     ev->total_size   = total_size;
-     ev->vendor_code  = event_msg->vendor_code;
-     ev->kev_class    = event_msg->kev_class;
-     ev->kev_subclass = event_msg->kev_subclass;
-     ev->event_code   = event_msg->event_code;
-
-     m->m_len = total_size;
-     lck_mtx_lock(sys_mtx);
-     for (ev_pcb = LIST_FIRST(&kern_event_head); 
-         ev_pcb; 
-         ev_pcb = LIST_NEXT(ev_pcb, ev_link)) {
-
-         if (ev_pcb->vendor_code_filter != KEV_ANY_VENDOR) {
-              if (ev_pcb->vendor_code_filter != ev->vendor_code)
-                   continue;
-
-              if (ev_pcb->class_filter != KEV_ANY_CLASS) {
-                   if (ev_pcb->class_filter != ev->kev_class)
-                        continue;
-
-                   if ((ev_pcb->subclass_filter != KEV_ANY_SUBCLASS) &&
-                       (ev_pcb->subclass_filter != ev->kev_subclass))
-                        continue;
-              }
-         }
-
-         m2 = m_copym(m, 0, m->m_len, M_NOWAIT);
-         if (m2 == 0) {
-              m_free(m);
-                  lck_mtx_unlock(sys_mtx);
-              return ENOBUFS;
-         }
-         /* the socket is already locked because we hold the sys_mtx here */
-         if (sbappendrecord(&ev_pcb->ev_socket->so_rcv, m2))
-                 sorwakeup(ev_pcb->ev_socket);
-     }
-
-     m_free(m);
-     lck_mtx_unlock(sys_mtx);
-     return 0;
+               OSIncrementAtomic64((SInt64 *)&kevtstat.kes_toobig);
+               return (EMSGSIZE);
+       }
+
+       m = m_get(M_DONTWAIT, MT_DATA);
+       if (m == 0) {
+               OSIncrementAtomic64((SInt64 *)&kevtstat.kes_nomem);
+               return (ENOMEM);
+       }
+       ev = mtod(m, struct kern_event_msg *);
+       total_size = KEV_MSG_HEADER_SIZE;
+
+       tmp = (char *) &ev->event_data[0];
+       for (i = 0; i < 5; i++) {
+               if (event_msg->dv[i].data_length == 0)
+                       break;
+
+               total_size += event_msg->dv[i].data_length;
+               bcopy(event_msg->dv[i].data_ptr, tmp,
+                   event_msg->dv[i].data_length);
+               tmp += event_msg->dv[i].data_length;
+       }
+
+       ev->id = ++static_event_id;
+       ev->total_size   = total_size;
+       ev->vendor_code  = event_msg->vendor_code;
+       ev->kev_class    = event_msg->kev_class;
+       ev->kev_subclass = event_msg->kev_subclass;
+       ev->event_code   = event_msg->event_code;
+
+       m->m_len = total_size;
+       lck_rw_lock_shared(kev_rwlock);
+       for (ev_pcb = LIST_FIRST(&kern_event_head);
+           ev_pcb;
+           ev_pcb = LIST_NEXT(ev_pcb, evp_link)) {
+               lck_mtx_lock(&ev_pcb->evp_mtx);
+               if (ev_pcb->evp_socket->so_pcb == NULL) {
+                       lck_mtx_unlock(&ev_pcb->evp_mtx);
+                       continue;
+               }
+               if (ev_pcb->evp_vendor_code_filter != KEV_ANY_VENDOR) {
+                       if (ev_pcb->evp_vendor_code_filter != ev->vendor_code) {
+                               lck_mtx_unlock(&ev_pcb->evp_mtx);
+                               continue;
+                       }
+
+                       if (ev_pcb->evp_class_filter != KEV_ANY_CLASS) {
+                               if (ev_pcb->evp_class_filter != ev->kev_class) {
+                                       lck_mtx_unlock(&ev_pcb->evp_mtx);
+                                       continue;
+                               }
+
+                               if ((ev_pcb->evp_subclass_filter !=
+                                   KEV_ANY_SUBCLASS) &&
+                                   (ev_pcb->evp_subclass_filter !=
+                                   ev->kev_subclass)) {
+                                       lck_mtx_unlock(&ev_pcb->evp_mtx);
+                                       continue;
+                               }
+                       }
+               }
+
+               m2 = m_copym(m, 0, m->m_len, M_NOWAIT);
+               if (m2 == 0) {
+                       OSIncrementAtomic64((SInt64 *)&kevtstat.kes_nomem);
+                       m_free(m);
+                       lck_mtx_unlock(&ev_pcb->evp_mtx);
+                       lck_rw_done(kev_rwlock);
+                       return (ENOMEM);
+               }
+               if (sbappendrecord(&ev_pcb->evp_socket->so_rcv, m2)) {
+                       /*
+                        * We use "m" for the socket stats as it would be
+                        * unsafe to use "m2"
+                        */
+                       so_inc_recv_data_stat(ev_pcb->evp_socket,
+                           1, m->m_len, SO_TC_BE);
+
+                       sorwakeup(ev_pcb->evp_socket);
+                       OSIncrementAtomic64((SInt64 *)&kevtstat.kes_posted);
+               } else {
+                       OSIncrementAtomic64((SInt64 *)&kevtstat.kes_fullsock);
+               }
+               lck_mtx_unlock(&ev_pcb->evp_mtx);
+       }
+       m_free(m);
+       lck_rw_done(kev_rwlock);
+
+       return (0);
 }
 
 static int
 }
 
 static int
-kev_control(struct socket *so, 
-                       u_long cmd, 
-                       caddr_t data, 
-                       __unused struct ifnet *ifp, 
-                       __unused struct proc *p)
+kev_control(struct socket *so,
+    u_long cmd,
+    caddr_t data,
+    __unused struct ifnet *ifp,
+    __unused struct proc *p)
 {
        struct kev_request *kev_req = (struct kev_request *) data;
        struct kern_event_pcb  *ev_pcb;
        struct kev_vendor_code *kev_vendor;
        u_int32_t  *id_value = (u_int32_t *) data;
 {
        struct kev_request *kev_req = (struct kev_request *) data;
        struct kern_event_pcb  *ev_pcb;
        struct kev_vendor_code *kev_vendor;
        u_int32_t  *id_value = (u_int32_t *) data;
-       
-       
+
        switch (cmd) {
        switch (cmd) {
-               
                case SIOCGKEVID:
                        *id_value = static_event_id;
                        break;
                case SIOCGKEVID:
                        *id_value = static_event_id;
                        break;
-               
                case SIOCSKEVFILT:
                        ev_pcb = (struct kern_event_pcb *) so->so_pcb;
                case SIOCSKEVFILT:
                        ev_pcb = (struct kern_event_pcb *) so->so_pcb;
-                       ev_pcb->vendor_code_filter = kev_req->vendor_code;
-                       ev_pcb->class_filter     = kev_req->kev_class;
-                       ev_pcb->subclass_filter  = kev_req->kev_subclass;
+                       ev_pcb->evp_vendor_code_filter = kev_req->vendor_code;
+                       ev_pcb->evp_class_filter = kev_req->kev_class;
+                       ev_pcb->evp_subclass_filter  = kev_req->kev_subclass;
                        break;
                        break;
-               
                case SIOCGKEVFILT:
                        ev_pcb = (struct kern_event_pcb *) so->so_pcb;
                case SIOCGKEVFILT:
                        ev_pcb = (struct kern_event_pcb *) so->so_pcb;
-                       kev_req->vendor_code = ev_pcb->vendor_code_filter;
-                       kev_req->kev_class   = ev_pcb->class_filter;
-                       kev_req->kev_subclass = ev_pcb->subclass_filter;
+                       kev_req->vendor_code = ev_pcb->evp_vendor_code_filter;
+                       kev_req->kev_class   = ev_pcb->evp_class_filter;
+                       kev_req->kev_subclass = ev_pcb->evp_subclass_filter;
                        break;
                        break;
-               
                case SIOCGKEVVENDOR:
                case SIOCGKEVVENDOR:
-                       kev_vendor = (struct kev_vendor_code*)data;
-                       
+                       kev_vendor = (struct kev_vendor_code *)data;
                        /* Make sure string is NULL terminated */
                        kev_vendor->vendor_string[KEV_VENDOR_CODE_MAX_STR_LEN-1] = 0;
                        /* Make sure string is NULL terminated */
                        kev_vendor->vendor_string[KEV_VENDOR_CODE_MAX_STR_LEN-1] = 0;
-               
-                       return net_str_id_find_internal(kev_vendor->vendor_string, 
-                                       &kev_vendor->vendor_code, NSI_VENDOR_CODE, 0);
-               
+                       return (net_str_id_find_internal(kev_vendor->vendor_string,
+                           &kev_vendor->vendor_code, NSI_VENDOR_CODE, 0));
                default:
                default:
-                       return ENOTSUP;
+                       return (ENOTSUP);
+       }
+
+       return (0);
+}
+
+int
+kevt_getstat SYSCTL_HANDLER_ARGS
+{
+#pragma unused(oidp, arg1, arg2)
+       int error = 0;
+
+       lck_rw_lock_shared(kev_rwlock);
+
+       if (req->newptr != USER_ADDR_NULL) {
+               error = EPERM;
+               goto done;
+       }
+       if (req->oldptr == USER_ADDR_NULL) {
+               req->oldidx = sizeof(struct kevtstat);
+               goto done;
+       }
+
+       error = SYSCTL_OUT(req, &kevtstat,
+           MIN(sizeof(struct kevtstat), req->oldlen));
+done:
+       lck_rw_done(kev_rwlock);
+
+       return (error);
+}
+
+__private_extern__ int
+kevt_pcblist SYSCTL_HANDLER_ARGS
+{
+#pragma unused(oidp, arg1, arg2)
+       int error = 0;
+       int n, i;
+       struct xsystmgen xsg;
+       void *buf = NULL;
+       size_t item_size = ROUNDUP64(sizeof (struct xkevtpcb)) +
+               ROUNDUP64(sizeof (struct xsocket_n)) +
+               2 * ROUNDUP64(sizeof (struct xsockbuf_n)) +
+               ROUNDUP64(sizeof (struct xsockstat_n));
+       struct kern_event_pcb  *ev_pcb;
+
+       buf = _MALLOC(item_size, M_TEMP, M_WAITOK | M_ZERO);
+       if (buf == NULL)
+               return (ENOMEM);
+
+       lck_rw_lock_shared(kev_rwlock);
+
+       n = kevtstat.kes_pcbcount;
+
+       if (req->oldptr == USER_ADDR_NULL) {
+               req->oldidx = (n + n/8) * item_size;
+               goto done;
+       }
+       if (req->newptr != USER_ADDR_NULL) {
+               error = EPERM;
+               goto done;
+       }
+       bzero(&xsg, sizeof (xsg));
+       xsg.xg_len = sizeof (xsg);
+       xsg.xg_count = n;
+       xsg.xg_gen = kevtstat.kes_gencnt;
+       xsg.xg_sogen = so_gencnt;
+       error = SYSCTL_OUT(req, &xsg, sizeof (xsg));
+       if (error) {
+               goto done;
+       }
+       /*
+        * We are done if there is no pcb
+        */
+       if (n == 0) {
+               goto done;
+       }
+
+       i = 0;
+       for (i = 0, ev_pcb = LIST_FIRST(&kern_event_head);
+           i < n && ev_pcb != NULL;
+           i++, ev_pcb = LIST_NEXT(ev_pcb, evp_link)) {
+               struct xkevtpcb *xk = (struct xkevtpcb *)buf;
+               struct xsocket_n *xso = (struct xsocket_n *)
+                       ADVANCE64(xk, sizeof (*xk));
+               struct xsockbuf_n *xsbrcv = (struct xsockbuf_n *)
+                       ADVANCE64(xso, sizeof (*xso));
+               struct xsockbuf_n *xsbsnd = (struct xsockbuf_n *)
+                       ADVANCE64(xsbrcv, sizeof (*xsbrcv));
+               struct xsockstat_n *xsostats = (struct xsockstat_n *)
+                       ADVANCE64(xsbsnd, sizeof (*xsbsnd));
+
+               bzero(buf, item_size);
+
+               lck_mtx_lock(&ev_pcb->evp_mtx);
+
+               xk->kep_len = sizeof(struct xkevtpcb);
+               xk->kep_kind = XSO_EVT;
+               xk->kep_evtpcb = (uint64_t)VM_KERNEL_ADDRPERM(ev_pcb);
+               xk->kep_vendor_code_filter = ev_pcb->evp_vendor_code_filter;
+               xk->kep_class_filter = ev_pcb->evp_class_filter;
+               xk->kep_subclass_filter = ev_pcb->evp_subclass_filter;
+
+               sotoxsocket_n(ev_pcb->evp_socket, xso);
+               sbtoxsockbuf_n(ev_pcb->evp_socket ?
+                       &ev_pcb->evp_socket->so_rcv : NULL, xsbrcv);
+               sbtoxsockbuf_n(ev_pcb->evp_socket ?
+                       &ev_pcb->evp_socket->so_snd : NULL, xsbsnd);
+               sbtoxsockstat_n(ev_pcb->evp_socket, xsostats);
+
+               lck_mtx_unlock(&ev_pcb->evp_mtx);
+
+               error = SYSCTL_OUT(req, buf, item_size);
+       }
+
+       if (error == 0) {
+               /*
+                * Give the user an updated idea of our state.
+                * If the generation differs from what we told
+                * her before, she knows that something happened
+                * while we were processing this request, and it
+                * might be necessary to retry.
+                */
+               bzero(&xsg, sizeof (xsg));
+               xsg.xg_len = sizeof (xsg);
+               xsg.xg_count = n;
+               xsg.xg_gen = kevtstat.kes_gencnt;
+               xsg.xg_sogen = so_gencnt;
+               error = SYSCTL_OUT(req, &xsg, sizeof (xsg));
+               if (error) {
+                       goto done;
+               }
        }
        }
-       
-       return 0;
+
+done:
+       lck_rw_done(kev_rwlock);
+
+       return (error);
 }
 
 #endif /* SOCKETS */
 }
 
 #endif /* SOCKETS */
@@ -2963,8 +3492,6 @@ fill_kqueueinfo(struct kqueue *kq, struct kqueue_info * kinfo)
 {
        struct vinfo_stat * st;
 
 {
        struct vinfo_stat * st;
 
-       /* No need for the funnel as fd is kept alive */
-       
        st = &kinfo->kq_stat;
 
        st->vst_size = kq->kq_count;
        st = &kinfo->kq_stat;
 
        st->vst_size = kq->kq_count;
@@ -2978,7 +3505,7 @@ fill_kqueueinfo(struct kqueue *kq, struct kqueue_info * kinfo)
        if (kq->kq_state & KQ_SLEEP)
                kinfo->kq_state |= PROC_KQUEUE_SLEEP;
 
        if (kq->kq_state & KQ_SLEEP)
                kinfo->kq_state |= PROC_KQUEUE_SLEEP;
 
-       return(0);
+       return (0);
 }
 
 
 }
 
 
@@ -2990,3 +3517,12 @@ knote_markstayqueued(struct knote *kn)
        knote_enqueue(kn);
        kqunlock(kn->kn_kq);
 }
        knote_enqueue(kn);
        kqunlock(kn->kn_kq);
 }
+
+void
+knote_clearstayqueued(struct knote *kn)
+{
+       kqlock(kn->kn_kq);
+       kn->kn_status &= ~KN_STAYQUEUED;
+       knote_dequeue(kn);
+       kqunlock(kn->kn_kq);
+}