+
+ /*
+ * waitq_set_deinit() remove the KQ's waitq set from
+ * any select sets to which it may belong.
+ */
+ waitq_set_deinit(&kq->kq_wqs);
+ lck_spin_destroy(&kq->kq_lock, kq_lck_grp);
+ lck_spin_destroy(&kq->kq_reqlock, kq_lck_grp);
+
+ if (kq->kq_state & KQ_WORKQ) {
+ zfree(kqworkq_zone, (struct kqworkq *)kq);
+ } else if (kq->kq_state & KQ_WORKLOOP) {
+ struct kqworkloop *kqwl = (struct kqworkloop *)kq;
+
+ assert(kqwl->kqwl_retains == 0);
+ lck_mtx_destroy(&kqwl->kqwl_statelock, kq_lck_grp);
+ zfree(kqworkloop_zone, kqwl);
+ } else {
+ zfree(kqfile_zone, (struct kqfile *)kq);
+ }
+}
+
+static inline void
+kqueue_retain(struct kqueue *kq)
+{
+ struct kqworkloop *kqwl = (struct kqworkloop *)kq;
+ uint32_t previous;
+
+ if ((kq->kq_state & KQ_DYNAMIC) == 0)
+ return;
+
+ previous = OSIncrementAtomic(&kqwl->kqwl_retains);
+ if (previous == KQ_WORKLOOP_RETAINS_MAX)
+ panic("kq(%p) retain overflow", kq);
+
+ if (previous == 0)
+ panic("kq(%p) resurrection", kq);
+}
+
+#define KQUEUE_CANT_BE_LAST_REF 0
+#define KQUEUE_MIGHT_BE_LAST_REF 1
+
+static inline int
+kqueue_release(kqueue_t kqu, __assert_only int possibly_last)
+{
+ if ((kqu.kq->kq_state & KQ_DYNAMIC) == 0) {
+ return 0;
+ }
+
+ assert(kqu.kq->kq_state & KQ_WORKLOOP); /* for now */
+ uint32_t refs = OSDecrementAtomic(&kqu.kqwl->kqwl_retains);
+ if (__improbable(refs == 0)) {
+ panic("kq(%p) over-release", kqu.kq);
+ }
+ if (refs == 1) {
+ assert(possibly_last);
+ }
+ return refs == 1;
+}
+
+int
+kqueue_body(struct proc *p, fp_allocfn_t fp_zalloc, void *cra, int32_t *retval)
+{
+ struct kqueue *kq;
+ struct fileproc *fp;
+ int fd, error;
+
+ error = falloc_withalloc(p,
+ &fp, &fd, vfs_context_current(), fp_zalloc, cra);
+ if (error) {
+ return (error);
+ }
+
+ kq = kqueue_alloc(p, 0);
+ if (kq == NULL) {
+ fp_free(p, fd, fp);
+ return (ENOMEM);
+ }
+
+ fp->f_flag = FREAD | FWRITE;
+ fp->f_ops = &kqueueops;
+ fp->f_data = kq;
+
+ proc_fdlock(p);
+ *fdflags(p, fd) |= UF_EXCLOSE;
+ procfdtbl_releasefd(p, fd, NULL);
+ fp_drop(p, fd, fp, 1);
+ proc_fdunlock(p);
+
+ *retval = fd;
+ 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
+kevent_copyin(user_addr_t *addrp, struct kevent_internal_s *kevp, struct proc *p,
+ unsigned int flags)
+{
+ int advance;
+ int error;
+
+ if (flags & KEVENT_FLAG_LEGACY32) {
+ bzero(kevp, sizeof (*kevp));
+
+ if (IS_64BIT_PROCESS(p)) {
+ struct user64_kevent kev64;
+
+ advance = sizeof (kev64);
+ error = copyin(*addrp, (caddr_t)&kev64, advance);
+ if (error)
+ return (error);
+ kevp->ident = kev64.ident;
+ kevp->filter = kev64.filter;
+ kevp->flags = kev64.flags;
+ kevp->udata = kev64.udata;
+ kevp->fflags = kev64.fflags;
+ kevp->data = kev64.data;
+ } else {
+ struct user32_kevent kev32;
+
+ advance = sizeof (kev32);
+ error = copyin(*addrp, (caddr_t)&kev32, advance);
+ if (error)
+ return (error);
+ kevp->ident = (uintptr_t)kev32.ident;
+ kevp->filter = kev32.filter;
+ kevp->flags = kev32.flags;
+ kevp->udata = CAST_USER_ADDR_T(kev32.udata);
+ kevp->fflags = kev32.fflags;
+ kevp->data = (intptr_t)kev32.data;
+ }
+ } else if (flags & KEVENT_FLAG_LEGACY64) {
+ struct kevent64_s kev64;
+
+ bzero(kevp, sizeof (*kevp));
+
+ advance = sizeof (struct kevent64_s);
+ error = copyin(*addrp, (caddr_t)&kev64, advance);
+ if (error)
+ return(error);
+ kevp->ident = kev64.ident;
+ kevp->filter = kev64.filter;
+ kevp->flags = kev64.flags;
+ kevp->udata = kev64.udata;
+ kevp->fflags = kev64.fflags;
+ kevp->data = kev64.data;
+ kevp->ext[0] = kev64.ext[0];
+ kevp->ext[1] = kev64.ext[1];
+
+ } else {
+ struct kevent_qos_s kevqos;
+
+ bzero(kevp, sizeof (*kevp));
+
+ advance = sizeof (struct kevent_qos_s);
+ error = copyin(*addrp, (caddr_t)&kevqos, advance);
+ if (error)
+ return error;
+ kevp->ident = kevqos.ident;
+ kevp->filter = kevqos.filter;
+ kevp->flags = kevqos.flags;
+ kevp->qos = kevqos.qos;
+// kevp->xflags = kevqos.xflags;
+ kevp->udata = kevqos.udata;
+ kevp->fflags = kevqos.fflags;
+ kevp->data = kevqos.data;
+ kevp->ext[0] = kevqos.ext[0];
+ kevp->ext[1] = kevqos.ext[1];
+ kevp->ext[2] = kevqos.ext[2];
+ kevp->ext[3] = kevqos.ext[3];
+ }
+ if (!error)
+ *addrp += advance;
+ return (error);
+}
+
+static int
+kevent_copyout(struct kevent_internal_s *kevp, user_addr_t *addrp, struct proc *p,
+ unsigned int flags)
+{
+ user_addr_t addr = *addrp;
+ int advance;
+ int error;
+
+ /*
+ * fully initialize the differnt output event structure
+ * types from the internal kevent (and some universal
+ * defaults for fields not represented in the internal
+ * form).
+ */
+ if (flags & KEVENT_FLAG_LEGACY32) {
+ assert((flags & KEVENT_FLAG_STACK_EVENTS) == 0);
+
+ if (IS_64BIT_PROCESS(p)) {
+ struct user64_kevent kev64;
+
+ advance = sizeof (kev64);
+ bzero(&kev64, advance);
+
+ /*
+ * deal with the special case of a user-supplied
+ * value of (uintptr_t)-1.
+ */
+ kev64.ident = (kevp->ident == (uintptr_t)-1) ?
+ (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;
+ error = copyout((caddr_t)&kev64, addr, advance);
+ } else {
+ struct user32_kevent kev32;
+
+ advance = sizeof (kev32);
+ bzero(&kev32, advance);
+ kev32.ident = (uint32_t)kevp->ident;
+ kev32.filter = kevp->filter;
+ kev32.flags = kevp->flags;
+ kev32.fflags = kevp->fflags;
+ kev32.data = (int32_t)kevp->data;
+ kev32.udata = kevp->udata;
+ error = copyout((caddr_t)&kev32, addr, advance);
+ }
+ } else if (flags & KEVENT_FLAG_LEGACY64) {
+ struct kevent64_s kev64;
+
+ advance = sizeof (struct kevent64_s);
+ if (flags & KEVENT_FLAG_STACK_EVENTS) {
+ addr -= advance;
+ }
+ bzero(&kev64, advance);
+ kev64.ident = 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.ext[0] = kevp->ext[0];
+ kev64.ext[1] = kevp->ext[1];
+ error = copyout((caddr_t)&kev64, addr, advance);
+ } else {
+ struct kevent_qos_s kevqos;
+
+ advance = sizeof (struct kevent_qos_s);
+ if (flags & KEVENT_FLAG_STACK_EVENTS) {
+ addr -= advance;
+ }
+ bzero(&kevqos, advance);
+ kevqos.ident = kevp->ident;
+ kevqos.filter = kevp->filter;
+ kevqos.flags = kevp->flags;
+ kevqos.qos = kevp->qos;
+ kevqos.udata = kevp->udata;
+ kevqos.fflags = kevp->fflags;
+ kevqos.xflags = 0;
+ kevqos.data = (int64_t) kevp->data;
+ kevqos.ext[0] = kevp->ext[0];
+ kevqos.ext[1] = kevp->ext[1];
+ kevqos.ext[2] = kevp->ext[2];
+ kevqos.ext[3] = kevp->ext[3];
+ error = copyout((caddr_t)&kevqos, addr, advance);
+ }
+ if (!error) {
+ if (flags & KEVENT_FLAG_STACK_EVENTS)
+ *addrp = addr;
+ else
+ *addrp = addr + advance;
+ }
+ return (error);
+}
+
+static int
+kevent_get_data_size(
+ struct proc *p,
+ uint64_t data_available,
+ unsigned int flags,
+ user_size_t *residp)
+{
+ user_size_t resid;
+ int error = 0;
+
+ if (data_available != USER_ADDR_NULL) {
+ if (flags & KEVENT_FLAG_KERNEL) {
+ resid = *(user_size_t *)(uintptr_t)data_available;
+ } else if (IS_64BIT_PROCESS(p)) {
+ user64_size_t usize;
+ error = copyin((user_addr_t)data_available, &usize, sizeof(usize));
+ resid = (user_size_t)usize;
+ } else {
+ user32_size_t usize;
+ error = copyin((user_addr_t)data_available, &usize, sizeof(usize));
+ resid = (user_size_t)usize;
+ }
+ if (error)
+ return(error);
+ } else {
+ resid = 0;
+ }
+ *residp = resid;
+ return 0;
+}
+
+static int
+kevent_put_data_size(
+ struct proc *p,
+ uint64_t data_available,
+ unsigned int flags,
+ user_size_t resid)
+{
+ int error = 0;
+
+ if (data_available) {
+ if (flags & KEVENT_FLAG_KERNEL) {
+ *(user_size_t *)(uintptr_t)data_available = resid;
+ } else if (IS_64BIT_PROCESS(p)) {
+ user64_size_t usize = (user64_size_t)resid;
+ error = copyout(&usize, (user_addr_t)data_available, sizeof(usize));
+ } else {
+ user32_size_t usize = (user32_size_t)resid;
+ error = copyout(&usize, (user_addr_t)data_available, sizeof(usize));
+ }
+ }
+ return error;
+}
+
+/*
+ * kevent_continue - continue a kevent syscall after blocking
+ *
+ * assume we inherit a use count on the kq fileglob.
+ */
+__attribute__((noreturn))
+static void
+kevent_continue(__unused struct kqueue *kq, void *data, int error)
+{
+ struct _kevent *cont_args;
+ struct fileproc *fp;
+ uint64_t data_available;
+ user_size_t data_size;
+ user_size_t data_resid;
+ unsigned int flags;
+ int32_t *retval;
+ int noutputs;
+ int fd;
+ struct proc *p = current_proc();
+
+ cont_args = (struct _kevent *)data;
+ data_available = cont_args->data_available;
+ flags = cont_args->process_data.fp_flags;
+ data_size = cont_args->process_data.fp_data_size;
+ data_resid = cont_args->process_data.fp_data_resid;
+ noutputs = cont_args->eventout;
+ retval = cont_args->retval;
+ fd = cont_args->fd;
+ fp = cont_args->fp;
+
+ kevent_put_kq(p, fd, fp, kq);
+
+ /* don't abandon other output just because of residual copyout failures */
+ if (error == 0 && data_available && data_resid != data_size) {
+ (void)kevent_put_data_size(p, data_available, flags, data_resid);
+ }
+
+ /* don't restart after signals... */
+ if (error == ERESTART)
+ error = EINTR;
+ else if (error == EWOULDBLOCK)
+ error = 0;
+ if (error == 0)
+ *retval = noutputs;
+ unix_syscall_return(error);
+}
+
+/*
+ * kevent - [syscall] register and wait for kernel events
+ *
+ */
+int
+kevent(struct proc *p, struct kevent_args *uap, int32_t *retval)
+{
+ unsigned int flags = KEVENT_FLAG_LEGACY32;
+
+ return kevent_internal(p,
+ (kqueue_id_t)uap->fd, NULL,
+ uap->changelist, uap->nchanges,
+ uap->eventlist, uap->nevents,
+ 0ULL, 0ULL,
+ flags,
+ uap->timeout,
+ kevent_continue,
+ retval);
+}
+
+int
+kevent64(struct proc *p, struct kevent64_args *uap, int32_t *retval)
+{
+ unsigned int flags;
+
+ /* restrict to user flags and set legacy64 */
+ flags = uap->flags & KEVENT_FLAG_USER;
+ flags |= KEVENT_FLAG_LEGACY64;
+
+ return kevent_internal(p,
+ (kqueue_id_t)uap->fd, NULL,
+ uap->changelist, uap->nchanges,
+ uap->eventlist, uap->nevents,
+ 0ULL, 0ULL,
+ flags,
+ uap->timeout,
+ kevent_continue,
+ retval);
+}
+
+int
+kevent_qos(struct proc *p, struct kevent_qos_args *uap, int32_t *retval)
+{
+ /* restrict to user flags */
+ uap->flags &= KEVENT_FLAG_USER;
+
+ return kevent_internal(p,
+ (kqueue_id_t)uap->fd, NULL,
+ uap->changelist, uap->nchanges,
+ uap->eventlist, uap->nevents,
+ uap->data_out, (uint64_t)uap->data_available,
+ uap->flags,
+ 0ULL,
+ kevent_continue,
+ retval);
+}
+
+int
+kevent_qos_internal(struct proc *p, int fd,
+ user_addr_t changelist, int nchanges,
+ user_addr_t eventlist, int nevents,
+ user_addr_t data_out, user_size_t *data_available,
+ unsigned int flags,
+ int32_t *retval)
+{
+ return kevent_internal(p,
+ (kqueue_id_t)fd, NULL,
+ changelist, nchanges,
+ eventlist, nevents,
+ data_out, (uint64_t)data_available,
+ (flags | KEVENT_FLAG_KERNEL),
+ 0ULL,
+ NULL,
+ retval);
+}
+
+int
+kevent_id(struct proc *p, struct kevent_id_args *uap, int32_t *retval)
+{
+ /* restrict to user flags */
+ uap->flags &= KEVENT_FLAG_USER;
+
+ return kevent_internal(p,
+ (kqueue_id_t)uap->id, NULL,
+ uap->changelist, uap->nchanges,
+ uap->eventlist, uap->nevents,
+ uap->data_out, (uint64_t)uap->data_available,
+ (uap->flags | KEVENT_FLAG_DYNAMIC_KQUEUE),
+ 0ULL,
+ kevent_continue,
+ retval);
+}
+
+int
+kevent_id_internal(struct proc *p, kqueue_id_t *id,
+ user_addr_t changelist, int nchanges,
+ user_addr_t eventlist, int nevents,
+ user_addr_t data_out, user_size_t *data_available,
+ unsigned int flags,
+ int32_t *retval)
+{
+ return kevent_internal(p,
+ *id, id,
+ changelist, nchanges,
+ eventlist, nevents,
+ data_out, (uint64_t)data_available,
+ (flags | KEVENT_FLAG_KERNEL | KEVENT_FLAG_DYNAMIC_KQUEUE),
+ 0ULL,
+ NULL,
+ retval);
+}
+
+static int
+kevent_get_timeout(struct proc *p,
+ user_addr_t utimeout,
+ unsigned int flags,
+ struct timeval *atvp)
+{
+ struct timeval atv;
+ int error = 0;
+
+ if (flags & KEVENT_FLAG_IMMEDIATE) {
+ getmicrouptime(&atv);
+ } else if (utimeout != USER_ADDR_NULL) {
+ struct timeval rtv;
+ if (flags & KEVENT_FLAG_KERNEL) {
+ struct timespec *tsp = (struct timespec *)utimeout;
+ TIMESPEC_TO_TIMEVAL(&rtv, tsp);
+ } else if (IS_64BIT_PROCESS(p)) {
+ struct user64_timespec ts;
+ error = copyin(utimeout, &ts, sizeof(ts));
+ if ((ts.tv_sec & 0xFFFFFFFF00000000ull) != 0)
+ error = EINVAL;
+ else
+ TIMESPEC_TO_TIMEVAL(&rtv, &ts);
+ } else {
+ struct user32_timespec ts;
+ error = copyin(utimeout, &ts, sizeof(ts));
+ TIMESPEC_TO_TIMEVAL(&rtv, &ts);
+ }
+ if (error)
+ return (error);
+ if (itimerfix(&rtv))
+ return (EINVAL);
+ getmicrouptime(&atv);
+ timevaladd(&atv, &rtv);
+ } else {
+ /* wait forever value */
+ atv.tv_sec = 0;
+ atv.tv_usec = 0;
+ }
+ *atvp = atv;
+ return 0;
+}
+
+static int
+kevent_set_kq_mode(struct kqueue *kq, unsigned int flags)
+{
+ /* each kq should only be used for events of one type */
+ kqlock(kq);
+ if (kq->kq_state & (KQ_KEV32 | KQ_KEV64 | KQ_KEV_QOS)) {
+ if (flags & KEVENT_FLAG_LEGACY32) {
+ if ((kq->kq_state & KQ_KEV32) == 0) {
+ kqunlock(kq);
+ return EINVAL;
+ }
+ } else if (kq->kq_state & KQ_KEV32) {
+ kqunlock(kq);
+ return EINVAL;
+ }
+ } else if (flags & KEVENT_FLAG_LEGACY32) {
+ kq->kq_state |= KQ_KEV32;
+ } else if (flags & KEVENT_FLAG_LEGACY64) {
+ kq->kq_state |= KQ_KEV64;
+ } else {
+ kq->kq_state |= KQ_KEV_QOS;
+ }
+ kqunlock(kq);
+ return 0;
+}
+
+#define KQ_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
+#define CONFIG_KQ_HASHSIZE CONFIG_KN_HASHSIZE
+
+static inline void
+kqhash_lock(proc_t p)
+{
+ lck_mtx_lock_spin_always(&p->p_fd->fd_kqhashlock);
+}
+
+static inline void
+kqhash_lock_held(__assert_only proc_t p)
+{
+ LCK_MTX_ASSERT(&p->p_fd->fd_kqhashlock, LCK_MTX_ASSERT_OWNED);
+}
+
+static inline void
+kqhash_unlock(proc_t p)
+{
+ lck_mtx_unlock(&p->p_fd->fd_kqhashlock);
+}
+
+static void
+kqueue_hash_init_if_needed(proc_t p)
+{
+ struct filedesc *fdp = p->p_fd;
+
+ kqhash_lock_held(p);
+
+ if (__improbable(fdp->fd_kqhash == NULL)) {
+ struct kqlist *alloc_hash;
+ u_long alloc_mask;
+
+ kqhash_unlock(p);
+ alloc_hash = hashinit(CONFIG_KQ_HASHSIZE, M_KQUEUE, &alloc_mask);
+ kqhash_lock(p);
+
+ /* See if we won the race */
+ if (fdp->fd_kqhashmask == 0) {
+ fdp->fd_kqhash = alloc_hash;
+ fdp->fd_kqhashmask = alloc_mask;
+ } else {
+ kqhash_unlock(p);
+ FREE(alloc_hash, M_KQUEUE);
+ kqhash_lock(p);
+ }
+ }
+}
+
+/*
+ * Called with the kqhash_lock() held
+ */
+static void
+kqueue_hash_insert(
+ struct proc *p,
+ kqueue_id_t id,
+ struct kqueue *kq)
+{
+ struct kqworkloop *kqwl = (struct kqworkloop *)kq;
+ struct filedesc *fdp = p->p_fd;
+ struct kqlist *list;
+
+ /* should hold the kq hash lock */
+ kqhash_lock_held(p);
+
+ if ((kq->kq_state & KQ_DYNAMIC) == 0) {
+ assert(kq->kq_state & KQ_DYNAMIC);
+ return;
+ }
+
+ /* only dynamically allocate workloop kqs for now */
+ assert(kq->kq_state & KQ_WORKLOOP);
+ assert(fdp->fd_kqhash);
+
+ kqwl->kqwl_dynamicid = id;
+
+ list = &fdp->fd_kqhash[KQ_HASH(id, fdp->fd_kqhashmask)];
+ SLIST_INSERT_HEAD(list, kqwl, kqwl_hashlink);
+}
+
+/* Called with kqhash_lock held */
+static void
+kqueue_hash_remove(
+ struct proc *p,
+ struct kqueue *kq)
+{
+ struct kqworkloop *kqwl = (struct kqworkloop *)kq;
+ struct filedesc *fdp = p->p_fd;
+ struct kqlist *list;
+
+ /* should hold the kq hash lock */
+ kqhash_lock_held(p);
+
+ if ((kq->kq_state & KQ_DYNAMIC) == 0) {
+ assert(kq->kq_state & KQ_DYNAMIC);
+ return;
+ }
+ assert(kq->kq_state & KQ_WORKLOOP); /* for now */
+ list = &fdp->fd_kqhash[KQ_HASH(kqwl->kqwl_dynamicid, fdp->fd_kqhashmask)];
+ SLIST_REMOVE(list, kqwl, kqworkloop, kqwl_hashlink);
+}
+
+/* Called with kqhash_lock held */
+static struct kqueue *
+kqueue_hash_lookup(struct proc *p, kqueue_id_t id)
+{
+ struct filedesc *fdp = p->p_fd;
+ struct kqlist *list;
+ struct kqworkloop *kqwl;
+
+ /* should hold the kq hash lock */
+ kqhash_lock_held(p);
+
+ if (fdp->fd_kqhashmask == 0) return NULL;
+
+ list = &fdp->fd_kqhash[KQ_HASH(id, fdp->fd_kqhashmask)];
+ SLIST_FOREACH(kqwl, list, kqwl_hashlink) {
+ if (kqwl->kqwl_dynamicid == id) {
+ struct kqueue *kq = (struct kqueue *)kqwl;
+
+ assert(kq->kq_state & KQ_DYNAMIC);
+ assert(kq->kq_state & KQ_WORKLOOP); /* for now */
+ return kq;
+ }
+ }
+ return NULL;
+}
+
+static inline void
+kqueue_release_last(struct proc *p, kqueue_t kqu)
+{
+ struct kqueue *kq = kqu.kq;
+ if (kq->kq_state & KQ_DYNAMIC) {
+ kqhash_lock(p);
+ if (kqueue_release(kq, KQUEUE_MIGHT_BE_LAST_REF)) {
+ thread_t cur_owner = kqworkloop_invalidate(kqu.kqwl);
+ kqueue_hash_remove(p, kq);
+ kqhash_unlock(p);
+ if (cur_owner) thread_deallocate(cur_owner);
+ kqueue_dealloc(kq);
+ } else {
+ kqhash_unlock(p);
+ }
+ }
+}
+
+/*
+ * kqworkloops_dealloc - rebalance retains on kqworkloops created with
+ * scheduling parameters
+ *
+ * Called with proc_fdlock held.
+ * Returns with it locked.
+ * Process is in such a state that it will not try to allocate
+ * any more knotes during this process (stopped for exit or exec).
+ */
+void
+kqworkloops_dealloc(proc_t p)
+{
+ struct filedesc *fdp = p->p_fd;
+ struct kqlist *list;
+ struct kqworkloop *kqwl, *kqwln;
+ struct kqlist tofree;
+ int i;
+
+ if (!(fdp->fd_flags & FD_WORKLOOP)) {
+ return;
+ }
+
+ SLIST_INIT(&tofree);
+
+ kqhash_lock(p);
+ assert(fdp->fd_kqhashmask != 0);
+
+ for (i = 0; i <= (int)fdp->fd_kqhashmask; i++) {
+ list = &fdp->fd_kqhash[i];
+ SLIST_FOREACH_SAFE(kqwl, list, kqwl_hashlink, kqwln) {
+ /*
+ * kqworkloops that have scheduling parameters have an
+ * implicit retain from kqueue_workloop_ctl that needs
+ * to be balanced on process exit.
+ */
+ assert(kqwl->kqwl_params);
+ SLIST_REMOVE(list, kqwl, kqworkloop, kqwl_hashlink);
+ SLIST_INSERT_HEAD(&tofree, kqwl, kqwl_hashlink);
+ }
+ }
+
+ kqhash_unlock(p);
+
+ SLIST_FOREACH_SAFE(kqwl, &tofree, kqwl_hashlink, kqwln) {
+ struct kqueue *kq = (struct kqueue *)kqwl;
+ __assert_only bool released;
+ released = kqueue_release(kq, KQUEUE_MIGHT_BE_LAST_REF);
+ assert(released);
+ kqueue_dealloc(kq);
+ }
+}
+
+static struct kqueue *
+kevent_get_bound_kqworkloop(thread_t thread)
+{
+ struct uthread *ut = get_bsdthread_info(thread);
+ struct kqrequest *kqr = ut->uu_kqr_bound;
+
+ return kqr ? (struct kqueue *)kqr_kqworkloop(kqr) : NULL;
+}
+
+static int
+kevent_get_kq(struct proc *p, kqueue_id_t id, workq_threadreq_param_t *trp,
+ unsigned int flags, struct fileproc **fpp, int *fdp,
+ struct kqueue **kqp)
+{
+ struct filedesc *descp = p->p_fd;
+ struct fileproc *fp = NULL;
+ struct kqueue *kq = NULL;
+ int fd = 0;
+ int error = 0;
+ thread_t th = current_thread();
+
+ assert(!trp || (flags & KEVENT_FLAG_WORKLOOP));
+
+ /* Was the workloop flag passed? Then it is for sure only a workloop */
+ if (flags & KEVENT_FLAG_DYNAMIC_KQUEUE) {
+ assert(flags & KEVENT_FLAG_WORKLOOP);
+ assert(!trp || (flags & KEVENT_FLAG_DYNAMIC_KQ_MUST_NOT_EXIST));
+ kq = kevent_get_bound_kqworkloop(th);
+
+ /*
+ * when kevent_id_internal is called from within the
+ * kernel, and the passed 'id' value is '-1' then we
+ * look for the currently bound workloop kq.
+ */
+ if (id == (kqueue_id_t)-1 &&
+ (flags & KEVENT_FLAG_KERNEL) &&
+ (flags & KEVENT_FLAG_WORKLOOP)) {
+
+ if (!is_workqueue_thread(th) || !kq) {
+ return EINVAL;
+ }
+
+ kqueue_retain(kq);
+ goto out;
+ }
+
+ if (id == 0 || id == (kqueue_id_t)-1) {
+ return EINVAL;
+ }
+
+ /* try shortcut on kq lookup for bound threads */
+ if (kq != NULL && ((struct kqworkloop *)kq)->kqwl_dynamicid == id) {
+
+ if (flags & KEVENT_FLAG_DYNAMIC_KQ_MUST_NOT_EXIST) {
+ return EEXIST;
+ }
+
+ /* retain a reference while working with this kq. */
+ assert(kq->kq_state & KQ_DYNAMIC);
+ kqueue_retain(kq);
+ goto out;
+ }
+
+ /* look for the kq on the hash table */
+ kqhash_lock(p);
+ kq = kqueue_hash_lookup(p, id);
+ if (kq == NULL) {
+ kqhash_unlock(p);
+
+ if (flags & KEVENT_FLAG_DYNAMIC_KQ_MUST_EXIST) {
+ return ENOENT;
+ }
+
+ struct kqueue *alloc_kq;
+ alloc_kq = kqueue_alloc(p, flags);
+ if (!alloc_kq) {
+ return ENOMEM;
+ }
+
+ kqhash_lock(p);
+ kqueue_hash_init_if_needed(p);
+ kq = kqueue_hash_lookup(p, id);
+ if (kq == NULL) {
+ /* insert our new one */
+ kq = alloc_kq;
+ if (trp) {
+ struct kqworkloop *kqwl = (struct kqworkloop *)kq;
+ kqwl->kqwl_params = trp->trp_value;
+ }
+ kqueue_hash_insert(p, id, kq);
+ kqhash_unlock(p);
+ } else if (flags & KEVENT_FLAG_DYNAMIC_KQ_MUST_NOT_EXIST) {
+ /* lost race and caller wants an error */
+ kqhash_unlock(p);
+ kqueue_release(alloc_kq, KQUEUE_MIGHT_BE_LAST_REF);
+ kqueue_dealloc(alloc_kq);
+ return EEXIST;
+ } else {
+ /* lost race, retain existing workloop */
+ kqueue_retain(kq);
+ kqhash_unlock(p);
+ kqueue_release(alloc_kq, KQUEUE_MIGHT_BE_LAST_REF);
+ kqueue_dealloc(alloc_kq);
+ }
+ } else {
+
+ if (flags & KEVENT_FLAG_DYNAMIC_KQ_MUST_NOT_EXIST) {
+ kqhash_unlock(p);
+ return EEXIST;
+ }
+
+ /* retain a reference while working with this kq. */
+ assert(kq->kq_state & KQ_DYNAMIC);
+ kqueue_retain(kq);
+ kqhash_unlock(p);
+ }
+
+ } else if (flags & KEVENT_FLAG_WORKQ) {
+ /* must already exist for bound threads. */
+ if (flags & KEVENT_FLAG_KERNEL) {
+ assert(descp->fd_wqkqueue != NULL);
+ }
+
+ /*
+ * use the private kq associated with the proc workq.
+ * Just being a thread within the process (and not
+ * being the exit/exec thread) is enough to hold a
+ * reference on this special kq.
+ */
+ kq = descp->fd_wqkqueue;
+ if (kq == NULL) {
+ struct kqueue *alloc_kq = kqueue_alloc(p, KEVENT_FLAG_WORKQ);
+ if (alloc_kq == NULL) {
+ return ENOMEM;
+ }
+
+ knhash_lock(p);
+ if (descp->fd_wqkqueue == NULL) {
+ kq = descp->fd_wqkqueue = alloc_kq;
+ knhash_unlock(p);
+ } else {
+ knhash_unlock(p);
+ kq = descp->fd_wqkqueue;
+ kqueue_dealloc(alloc_kq);
+ }
+ }
+ } else {
+ /* get a usecount for the kq itself */
+ fd = (int)id;
+ if ((error = fp_getfkq(p, fd, &fp, &kq)) != 0)
+ return (error);
+ }
+ if ((error = kevent_set_kq_mode(kq, flags)) != 0) {
+ /* drop the usecount */
+ if (fp != NULL)
+ fp_drop(p, fd, fp, 0);
+ return error;
+ }
+
+out:
+ *fpp = fp;
+ *fdp = fd;
+ *kqp = kq;
+
+ return error;
+}
+
+static void
+kevent_put_kq(
+ struct proc *p,
+ kqueue_id_t id,
+ struct fileproc *fp,
+ struct kqueue *kq)
+{
+ kqueue_release_last(p, kq);
+ if (fp != NULL) {
+ assert((kq->kq_state & KQ_WORKQ) == 0);
+ fp_drop(p, (int)id, fp, 0);
+ }
+}
+
+static uint64_t
+kevent_workloop_serial_no_copyin(proc_t p, uint64_t workloop_id)
+{
+ uint64_t serial_no = 0;
+ user_addr_t addr;
+ int rc;
+
+ if (workloop_id == 0 || p->p_dispatchqueue_serialno_offset == 0) {
+ return 0;
+ }
+ addr = (user_addr_t)(workloop_id + p->p_dispatchqueue_serialno_offset);
+
+ if (proc_is64bit(p)) {
+ rc = copyin(addr, (caddr_t)&serial_no, sizeof(serial_no));
+ } else {
+ uint32_t serial_no32 = 0;
+ rc = copyin(addr, (caddr_t)&serial_no32, sizeof(serial_no32));
+ serial_no = serial_no32;
+ }
+ return rc == 0 ? serial_no : 0;
+}
+
+int
+kevent_exit_on_workloop_ownership_leak(thread_t thread)
+{
+ proc_t p = current_proc();
+ struct filedesc *fdp = p->p_fd;
+ kqueue_id_t workloop_id = 0;
+ os_reason_t reason = OS_REASON_NULL;
+ mach_vm_address_t addr;
+ uint32_t reason_size;
+
+ kqhash_lock(p);
+ if (fdp->fd_kqhashmask > 0) {
+ for (uint32_t i = 0; i < fdp->fd_kqhashmask + 1; i++) {
+ struct kqworkloop *kqwl;
+
+ SLIST_FOREACH(kqwl, &fdp->fd_kqhash[i], kqwl_hashlink) {
+ struct kqueue *kq = &kqwl->kqwl_kqueue;
+ if ((kq->kq_state & KQ_DYNAMIC) && kqwl->kqwl_owner == thread) {
+ workloop_id = kqwl->kqwl_dynamicid;
+ break;
+ }
+ }
+ }
+ }
+ kqhash_unlock(p);
+
+ reason = os_reason_create(OS_REASON_LIBSYSTEM,
+ OS_REASON_LIBSYSTEM_CODE_WORKLOOP_OWNERSHIP_LEAK);
+ if (reason == OS_REASON_NULL) {
+ goto out;
+ }
+
+ reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
+ reason_size = 2 * sizeof(uint64_t);
+ reason_size = kcdata_estimate_required_buffer_size(2, reason_size);
+ if (os_reason_alloc_buffer(reason, reason_size) != 0) {
+ goto out;
+ }
+
+ if (workloop_id) {
+ struct kcdata_descriptor *kcd = &reason->osr_kcd_descriptor;
+
+ if (kcdata_get_memory_addr(kcd, EXIT_REASON_WORKLOOP_ID,
+ sizeof(workloop_id), &addr) == KERN_SUCCESS) {
+ kcdata_memcpy(kcd, addr, &workloop_id, sizeof(workloop_id));
+ }
+
+ uint64_t serial_no = kevent_workloop_serial_no_copyin(p, workloop_id);
+ if (serial_no && kcdata_get_memory_addr(kcd, EXIT_REASON_DISPATCH_QUEUE_NO,
+ sizeof(serial_no), &addr) == KERN_SUCCESS) {
+ kcdata_memcpy(kcd, addr, &serial_no, sizeof(serial_no));
+ }
+ }
+out:
+#if DEVELOPMENT || DEBUG
+ if (kevent_debug_flags() & KEVENT_PANIC_ON_WORKLOOP_OWNERSHIP_LEAK) {
+ panic("thread %p in task %p is leaked workloop 0x%016llx ownership",
+ thread, p->task, workloop_id);
+ }
+ psignal_try_thread_with_reason(p, thread, SIGABRT, reason);
+ return 0;
+#else
+ return exit_with_reason(p, W_EXITCODE(0, SIGKILL), (int *)NULL,
+ FALSE, FALSE, 0, reason);
+#endif
+}
+
+static inline boolean_t
+kevent_args_requesting_events(unsigned int flags, int nevents)
+{
+ return (!(flags & KEVENT_FLAG_ERROR_EVENTS) && nevents > 0);
+}
+
+static int
+kevent_internal(struct proc *p,
+ kqueue_id_t id, kqueue_id_t *id_out,
+ user_addr_t changelist, int nchanges,
+ user_addr_t ueventlist, int nevents,
+ user_addr_t data_out, uint64_t data_available,
+ unsigned int flags,
+ user_addr_t utimeout,
+ kqueue_continue_t continuation,
+ int32_t *retval)
+{
+ uthread_t ut;
+ struct kqueue *kq;
+ struct fileproc *fp = NULL;
+ int fd = 0;
+ struct kevent_internal_s kev;
+ int error, noutputs, register_rc;
+ bool needs_end_processing = false;
+ struct timeval atv;
+ user_size_t data_size;
+ user_size_t data_resid;
+ thread_t thread = current_thread();
+ KNOTE_LOCK_CTX(knlc);
+
+ /* Don't allow user-space threads to process output events from the workq kqs */
+ if (((flags & (KEVENT_FLAG_WORKQ | KEVENT_FLAG_KERNEL)) == KEVENT_FLAG_WORKQ) &&
+ kevent_args_requesting_events(flags, nevents))
+ return EINVAL;
+
+ if (flags & KEVENT_FLAG_PARKING) {
+ if (!kevent_args_requesting_events(flags, nevents) || id != (kqueue_id_t)-1)
+ return EINVAL;
+ }
+
+ /* restrict dynamic kqueue allocation to workloops (for now) */
+ if ((flags & (KEVENT_FLAG_DYNAMIC_KQUEUE | KEVENT_FLAG_WORKLOOP)) == KEVENT_FLAG_DYNAMIC_KQUEUE)
+ return EINVAL;
+
+ if ((flags & (KEVENT_FLAG_WORKLOOP)) && (flags & (KEVENT_FLAG_WORKQ)))
+ return EINVAL;
+
+ if (flags & (KEVENT_FLAG_DYNAMIC_KQ_MUST_EXIST | KEVENT_FLAG_DYNAMIC_KQ_MUST_NOT_EXIST)) {
+
+ /* allowed only on workloops when calling kevent_id from user-space */
+ if (!(flags & KEVENT_FLAG_WORKLOOP) || (flags & KEVENT_FLAG_KERNEL) || !(flags & KEVENT_FLAG_DYNAMIC_KQUEUE))
+ return EINVAL;
+ }
+
+ /* prepare to deal with stack-wise allocation of out events */
+ if (flags & KEVENT_FLAG_STACK_EVENTS) {
+ int scale = ((flags & KEVENT_FLAG_LEGACY32) ?
+ (IS_64BIT_PROCESS(p) ? sizeof(struct user64_kevent) :
+ sizeof(struct user32_kevent)) :
+ ((flags & KEVENT_FLAG_LEGACY64) ? sizeof(struct kevent64_s) :
+ sizeof(struct kevent_qos_s)));
+ ueventlist += nevents * scale;
+ }
+
+ /* convert timeout to absolute - if we have one (and not immediate) */
+ error = kevent_get_timeout(p, utimeout, flags, &atv);
+ if (error)
+ return error;
+
+ /* copyin initial value of data residual from data_available */
+ error = kevent_get_data_size(p, data_available, flags, &data_size);
+ if (error)
+ return error;
+
+ /* get the kq we are going to be working on */
+ error = kevent_get_kq(p, id, NULL, flags, &fp, &fd, &kq);
+#if CONFIG_WORKLOOP_DEBUG
+ ut = (uthread_t)get_bsdthread_info(thread);
+ UU_KEVENT_HISTORY_WRITE_ENTRY(ut, {
+ .uu_kqid = id,
+ .uu_kq = error ? NULL : kq,
+ .uu_error = error,
+ .uu_nchanges = nchanges,
+ .uu_nevents = nevents,
+ .uu_flags = flags,
+ });
+#endif // CONFIG_WORKLOOP_DEBUG
+ if (error)
+ return error;
+
+ /* only bound threads can receive events on workloops */
+ if (flags & KEVENT_FLAG_WORKLOOP) {
+ struct kqworkloop *kqwl = (struct kqworkloop *)kq;
+ struct kqrequest *kqr = &kqwl->kqwl_request;
+
+ assert(kq->kq_state & KQ_WORKLOOP);
+
+ if (kevent_args_requesting_events(flags, nevents)) {
+ if (kq != kevent_get_bound_kqworkloop(thread)) {
+ error = EXDEV;
+ goto out;
+ }
+
+ kq_req_lock(kqwl);
+ /*
+ * Disable the R2K notification while doing a register, if the
+ * caller wants events too, we don't want the AST to be set if we
+ * will process these events soon.
+ */
+ kqr->kqr_state &= ~KQR_R2K_NOTIF_ARMED;
+ needs_end_processing = true;
+ kq_req_unlock(kq);
+ }
+
+ if (id_out) {
+ *id_out = kqwl->kqwl_dynamicid;
+ }
+
+ }
+
+ /* register all the change requests the user provided... */
+ noutputs = 0;
+ while (nchanges > 0 && error == 0) {
+ error = kevent_copyin(&changelist, &kev, p, flags);
+ if (error)
+ break;
+
+ /* Make sure user doesn't pass in any system flags */
+ kev.flags &= ~EV_SYSFLAGS;
+
+ register_rc = kevent_register(kq, &kev, &knlc);
+ if (register_rc & FILTER_REGISTER_WAIT) {
+ kqlock_held(kq);
+
+ // f_post_register_wait is meant to call a continuation and not to
+ // return, which is why we don't support FILTER_REGISTER_WAIT if
+ // KEVENT_FLAG_ERROR_EVENTS is not passed, or if the event that
+ // waits isn't the last.
+ //
+ // It is implementable, but not used by any userspace code at the
+ // moment, so for now return ENOTSUP if someone tries to do it.
+ if (nchanges == 1 && nevents >= 1 && (flags & KEVENT_FLAG_ERROR_EVENTS)) {
+ struct _kevent_register *cont_args;
+ /* store the continuation/completion data in the uthread */
+ ut = (uthread_t)get_bsdthread_info(thread);
+ cont_args = &ut->uu_save.uus_kevent_register;
+ cont_args->kev = kev;
+ cont_args->kq = kq;
+ cont_args->fp = fp;
+ cont_args->fd = fd;
+ cont_args->ueventlist = ueventlist;
+ cont_args->flags = flags;
+ cont_args->retval = retval;
+ cont_args->eventcount = nevents;
+ cont_args->eventout = noutputs;
+ knote_fops(cont_args->knote)->f_post_register_wait(ut, &knlc, cont_args);
+ panic("f_post_register_wait returned (kev: %p)", &kev);
+ }
+
+ kev.flags |= EV_ERROR;
+ kev.data = ENOTSUP;
+ knote_unlock(kq, knlc.knlc_knote, &knlc, KNOTE_KQ_UNLOCK);
+ }
+
+ // keep in sync with kevent_register_wait_return()
+ if (nevents > 0 && (kev.flags & (EV_ERROR|EV_RECEIPT))) {
+ if ((kev.flags & EV_ERROR) == 0) {
+ kev.flags |= EV_ERROR;
+ kev.data = 0;
+ }
+ error = kevent_copyout(&kev, &ueventlist, p, flags);
+ if (error == 0) {
+ nevents--;
+ noutputs++;
+ }
+ } else if (kev.flags & EV_ERROR) {
+ error = kev.data;
+ }
+ nchanges--;
+ }
+
+ /* short-circuit the scan if we only want error events */
+ if (flags & KEVENT_FLAG_ERROR_EVENTS)
+ nevents = 0;
+
+ /* process pending events */
+ if (nevents > 0 && noutputs == 0 && error == 0) {
+ struct _kevent *cont_args;
+ /* store the continuation/completion data in the uthread */
+ ut = (uthread_t)get_bsdthread_info(thread);
+ cont_args = &ut->uu_save.uus_kevent;
+ cont_args->fp = fp;
+ cont_args->fd = fd;
+ cont_args->retval = retval;
+ cont_args->eventlist = ueventlist;
+ cont_args->eventcount = nevents;
+ cont_args->eventout = noutputs;
+ cont_args->data_available = data_available;
+ cont_args->process_data.fp_fd = (int)id;
+ cont_args->process_data.fp_flags = flags;
+ cont_args->process_data.fp_data_out = data_out;
+ cont_args->process_data.fp_data_size = data_size;
+ cont_args->process_data.fp_data_resid = data_size;
+
+ /*
+ * kqworkloop_end_processing() will happen at the end of kqueue_scan()
+ */
+ needs_end_processing = false;
+
+ error = kqueue_scan(kq, kevent_callback,
+ continuation, cont_args,
+ &cont_args->process_data,
+ &atv, p);
+
+ /* process remaining outputs */
+ noutputs = cont_args->eventout;
+ data_resid = cont_args->process_data.fp_data_resid;
+
+ /* copyout residual data size value (if it needs to be copied out) */
+ /* don't abandon other output just because of residual copyout failures */
+ if (error == 0 && data_available && data_resid != data_size) {
+ (void)kevent_put_data_size(p, data_available, flags, data_resid);
+ }
+ }
+
+out:
+ if (__improbable(needs_end_processing)) {
+ /*
+ * If we didn't through kqworkloop_end_processing(),
+ * we need to do it here.
+ */
+ kqlock(kq);
+ kqworkloop_end_processing((struct kqworkloop *)kq, 0, 0);
+ kqunlock(kq);
+ }
+ kevent_put_kq(p, id, fp, kq);
+
+ /* don't restart after signals... */
+ if (error == ERESTART)
+ error = EINTR;
+ else if (error == EWOULDBLOCK)
+ error = 0;
+ if (error == 0)
+ *retval = noutputs;
+ return (error);
+}
+
+
+/*
+ * kevent_callback - callback for each individual event
+ *
+ * called with nothing locked
+ * caller holds a reference on the kqueue
+ */
+static int
+kevent_callback(__unused struct kqueue *kq, struct kevent_internal_s *kevp,
+ void *data)
+{
+ struct _kevent *cont_args;
+ int error;
+
+ cont_args = (struct _kevent *)data;
+ assert(cont_args->eventout < cont_args->eventcount);
+
+ /*
+ * Copy out the appropriate amount of event data for this user.
+ */
+ error = kevent_copyout(kevp, &cont_args->eventlist, current_proc(),
+ cont_args->process_data.fp_flags);
+
+ /*
+ * 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);
+}
+
+/*
+ * kevent_description - format a description of a kevent for diagnostic output
+ *
+ * called with a 256-byte string buffer
+ */
+
+char *
+kevent_description(struct kevent_internal_s *kevp, char *s, size_t n)
+{
+ snprintf(s, n,
+ "kevent="
+ "{.ident=%#llx, .filter=%d, .flags=%#x, .udata=%#llx, .fflags=%#x, .data=%#llx, .ext[0]=%#llx, .ext[1]=%#llx}",
+ kevp->ident,
+ kevp->filter,
+ kevp->flags,
+ kevp->udata,
+ kevp->fflags,
+ kevp->data,
+ kevp->ext[0],
+ kevp->ext[1] );
+
+ return (s);
+}
+
+static int
+kevent_register_validate_priority(struct kqueue *kq, struct knote *kn,
+ struct kevent_internal_s *kev)
+{
+ /* We don't care about the priority of a disabled or deleted knote */
+ if (kev->flags & (EV_DISABLE | EV_DELETE)) {
+ return 0;
+ }
+
+ if (kq->kq_state & KQ_WORKLOOP) {
+ /*
+ * Workloops need valid priorities with a QOS (excluding manager) for
+ * any enabled knote.
+ *
+ * When it is pre-existing, just make sure it has a valid QoS as
+ * kevent_register() will not use the incoming priority (filters who do
+ * have the responsibility to validate it again, see filt_wltouch).
+ *
+ * If the knote is being made, validate the incoming priority.
+ */
+ if (!_pthread_priority_thread_qos(kn ? kn->kn_qos : kev->qos)) {
+ return ERANGE;
+ }
+ }
+
+ return 0;
+}
+
+/*
+ * Prepare a filter for waiting after register.
+ *
+ * The f_post_register_wait hook will be called later by kevent_register()
+ * and should call kevent_register_wait_block()
+ */
+static int
+kevent_register_wait_prepare(struct knote *kn, struct kevent_internal_s *kev)
+{
+ thread_t thread = current_thread();
+ struct uthread *uth = get_bsdthread_info(thread);
+
+ assert(knote_fops(kn)->f_extended_codes);
+
+ if (kn->kn_hook == NULL) {
+ thread_reference(thread);
+ kn->kn_hook = thread;
+ } else if (kn->kn_hook != thread) {
+ /*
+ * kn_hook may be set from a previous aborted wait
+ * However, it has to be from the same thread.
+ */
+ kev->flags |= EV_ERROR;
+ kev->data = EXDEV;
+ return 0;
+ }
+
+ uth->uu_save.uus_kevent_register.knote = kn;
+ return FILTER_REGISTER_WAIT;
+}
+
+/*
+ * Cleanup a kevent_register_wait_prepare() effect for threads that have been
+ * aborted instead of properly woken up with thread_wakeup_thread().
+ */
+static void
+kevent_register_wait_cleanup(struct knote *kn)
+{
+ thread_t thread = kn->kn_hook;
+ kn->kn_hook = NULL;
+ thread_deallocate(thread);
+}
+
+/*
+ * Must be called at the end of a f_post_register_wait call from a filter.
+ */
+static void
+kevent_register_wait_block(struct turnstile *ts, thread_t thread,
+ struct knote_lock_ctx *knlc, thread_continue_t cont,
+ struct _kevent_register *cont_args)
+{
+ knote_unlock(cont_args->kq, cont_args->knote, knlc, KNOTE_KQ_UNLOCK);
+ turnstile_update_inheritor_complete(ts, TURNSTILE_INTERLOCK_NOT_HELD);
+ cont_args->handoff_thread = thread;
+ thread_handoff_parameter(thread, cont, cont_args);
+}
+
+/*
+ * Called by Filters using a f_post_register_wait to return from their wait.
+ */
+static void
+kevent_register_wait_return(struct _kevent_register *cont_args)
+{
+ struct kqueue *kq = cont_args->kq;
+ proc_t p = kq->kq_p;
+ struct kevent_internal_s *kev = &cont_args->kev;
+ int error = 0;
+
+ if (cont_args->handoff_thread) {
+ thread_deallocate(cont_args->handoff_thread);
+ }
+
+ if (kev->flags & (EV_ERROR|EV_RECEIPT)) {
+ if ((kev->flags & EV_ERROR) == 0) {
+ kev->flags |= EV_ERROR;
+ kev->data = 0;
+ }
+ error = kevent_copyout(kev, &cont_args->ueventlist, p, cont_args->flags);
+ if (error == 0) cont_args->eventout++;
+ }
+
+ kevent_put_kq(p, cont_args->fd, cont_args->fp, kq);
+ if (error == 0) {
+ *cont_args->retval = cont_args->eventout;
+ }
+ unix_syscall_return(error);
+}
+
+/*
+ * kevent_register - add a new event to a kqueue
+ *
+ * Creates a mapping between the event source and
+ * the kqueue via a knote data structure.
+ *
+ * Because many/most the event sources are file
+ * descriptor related, the knote is linked off
+ * the filedescriptor table for quick access.
+ *
+ * called with nothing locked
+ * caller holds a reference on the kqueue
+ */
+
+int
+kevent_register(struct kqueue *kq, struct kevent_internal_s *kev,
+ struct knote_lock_ctx *knlc)
+{
+ struct proc *p = kq->kq_p;
+ const struct filterops *fops;
+ struct knote *kn = NULL;
+ int result = 0, error = 0;
+ unsigned short kev_flags = kev->flags;
+
+ if (kev->filter < 0) {
+ if (kev->filter + EVFILT_SYSCOUNT < 0) {
+ error = EINVAL;
+ goto out;
+ }
+ fops = sysfilt_ops[~kev->filter]; /* to 0-base index */
+ } else {
+ error = EINVAL;
+ goto out;
+ }
+
+ /* restrict EV_VANISHED to adding udata-specific dispatch kevents */
+ if ((kev->flags & EV_VANISHED) &&
+ (kev->flags & (EV_ADD | EV_DISPATCH2)) != (EV_ADD | EV_DISPATCH2)) {
+ error = EINVAL;
+ goto out;
+ }
+
+ /* Simplify the flags - delete and disable overrule */
+ if (kev->flags & EV_DELETE)
+ kev->flags &= ~EV_ADD;
+ if (kev->flags & EV_DISABLE)
+ kev->flags &= ~EV_ENABLE;
+
+ if (kq->kq_state & KQ_WORKLOOP) {
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQWL_REGISTER),
+ ((struct kqworkloop *)kq)->kqwl_dynamicid,
+ kev->udata, kev->flags, kev->filter);
+ } else if (kq->kq_state & KQ_WORKQ) {
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQWQ_REGISTER),
+ 0, kev->udata, kev->flags, kev->filter);
+ } else {
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQ_REGISTER),
+ VM_KERNEL_UNSLIDE_OR_PERM(kq),
+ kev->udata, kev->flags, kev->filter);
+ }
+
+restart:
+ /* find the matching knote from the fd tables/hashes */
+ kn = kq_find_knote_and_kq_lock(kq, kev, fops->f_isfd, p);
+ error = kevent_register_validate_priority(kq, kn, kev);
+ result = 0;
+ if (error) {
+ goto out;
+ }
+
+ if (kn == NULL && (kev->flags & EV_ADD) == 0) {
+ /*
+ * No knote found, EV_ADD wasn't specified
+ */
+
+ if ((kev_flags & EV_ADD) && (kev_flags & EV_DELETE) &&
+ (kq->kq_state & KQ_WORKLOOP)) {
+ /*
+ * For workloops, understand EV_ADD|EV_DELETE as a "soft" delete
+ * that doesn't care about ENOENT, so just pretend the deletion
+ * happened.
+ */
+ } else {
+ error = ENOENT;
+ }
+ goto out;
+
+ } else if (kn == NULL) {
+ /*
+ * No knote found, need to attach a new one (attach)
+ */
+
+ struct fileproc *knote_fp = NULL;
+
+ /* grab a file reference for the new knote */
+ if (fops->f_isfd) {
+ if ((error = fp_lookup(p, kev->ident, &knote_fp, 0)) != 0) {
+ goto out;
+ }
+ }
+
+ kn = knote_alloc();
+ if (kn == NULL) {
+ error = ENOMEM;
+ if (knote_fp != NULL)
+ fp_drop(p, kev->ident, knote_fp, 0);
+ goto out;
+ }
+
+ kn->kn_fp = knote_fp;
+ kn->kn_kq_packed = (intptr_t)(struct kqueue *)kq;
+ kqueue_retain(kq); /* retain a kq ref */
+ kn->kn_filtid = ~kev->filter;
+ kn->kn_status = KN_ATTACHING | KN_ATTACHED;
+
+ /* was vanish support requested */
+ if (kev->flags & EV_VANISHED) {
+ kev->flags &= ~EV_VANISHED;
+ kn->kn_status |= KN_REQVANISH;
+ }
+
+ /* snapshot matching/dispatching protcol flags into knote */
+ if (kev->flags & EV_DISPATCH)
+ kn->kn_status |= KN_DISPATCH;
+ if (kev->flags & EV_UDATA_SPECIFIC)
+ kn->kn_status |= KN_UDATA_SPECIFIC;
+ if (kev->flags & EV_DISABLE)
+ kn->kn_status |= KN_DISABLED;
+
+ /*
+ * copy the kevent state into knote
+ * protocol is that fflags and data
+ * are saved off, and cleared before
+ * calling the attach routine.
+ */
+ kn->kn_kevent = *kev;
+ kn->kn_sfflags = kev->fflags;
+ kn->kn_sdata = kev->data;
+ kn->kn_fflags = 0;
+ kn->kn_data = 0;
+ knote_reset_priority(kn, kev->qos);
+
+ /* Add the knote for lookup thru the fd table */
+ error = kq_add_knote(kq, kn, knlc, p);
+ if (error) {
+ (void)kqueue_release(kq, KQUEUE_CANT_BE_LAST_REF);
+ knote_free(kn);
+ if (knote_fp != NULL)
+ fp_drop(p, kev->ident, knote_fp, 0);
+
+ if (error == ERESTART) {
+ goto restart;
+ }
+ goto out;
+ }
+
+ /* fp reference count now applies to knote */
+
+ /*
+ * we can't use filter_call() because f_attach can change the filter ops
+ * for a filter that supports f_extended_codes, so we need to reload
+ * knote_fops() and not use `fops`.
+ */
+ result = fops->f_attach(kn, kev);
+ if (result && !knote_fops(kn)->f_extended_codes) {
+ result = FILTER_ACTIVE;
+ }
+
+ kqlock(kq);
+
+ if (kn->kn_flags & EV_ERROR) {
+ /*
+ * Failed to attach correctly, so drop.
+ */
+ kn->kn_status &= ~(KN_ATTACHED | KN_ATTACHING);
+ error = kn->kn_data;
+ knote_drop(kq, kn, knlc);
+ result = 0;
+ goto out;
+ }
+
+ /*
+ * end "attaching" phase - now just attached
+ *
+ * Mark the thread request overcommit, if appropos
+ *
+ * If the attach routine indicated that an
+ * event is already fired, activate the knote.
+ */
+ kn->kn_status &= ~KN_ATTACHING;
+ knote_set_qos_overcommit(kn);
+
+ if (result & FILTER_ACTIVE) {
+ if (result & FILTER_ADJUST_EVENT_QOS_BIT)
+ knote_adjust_qos(kq, kn, result);
+ knote_activate(kn);
+ }
+
+ } else if (!knote_lock(kq, kn, knlc, KNOTE_KQ_LOCK_ON_SUCCESS)) {
+
+ /*
+ * The knote was dropped while we were waiting for the lock,
+ * we need to re-evaluate entirely
+ */
+
+ goto restart;
+
+ } else if (kev->flags & EV_DELETE) {
+ /*
+ * Deletion of a knote (drop)
+ *
+ * If the filter wants to filter drop events, let it do so.
+ *
+ * defer-delete: when trying to delete a disabled EV_DISPATCH2 knote,
+ * we must wait for the knote to be re-enabled (unless it is being
+ * re-enabled atomically here).
+ */
+
+ if (knote_fops(kn)->f_allow_drop) {
+ bool drop;
+
+ kqunlock(kq);
+ drop = knote_fops(kn)->f_allow_drop(kn, kev);
+ kqlock(kq);
+
+ if (!drop) goto out_unlock;
+ }
+
+ if ((kev->flags & EV_ENABLE) == 0 &&
+ (kn->kn_status & (KN_DISPATCH2 | KN_DISABLED)) ==
+ (KN_DISPATCH2 | KN_DISABLED)) {
+ kn->kn_status |= KN_DEFERDELETE;
+ error = EINPROGRESS;
+ goto out_unlock;
+ }
+
+ knote_drop(kq, kn, knlc);
+ goto out;
+
+ } else {
+ /*
+ * Regular update of a knote (touch)
+ *
+ * Call touch routine to notify filter of changes in filter values
+ * (and to re-determine if any events are fired).
+ *
+ * If the knote is in defer-delete, avoid calling the filter touch
+ * routine (it has delivered its last event already).
+ *
+ * If the touch routine had no failure,
+ * apply the requested side effects to the knote.
+ */
+
+ if (kn->kn_status & (KN_DEFERDELETE | KN_VANISHED)) {
+ if (kev->flags & EV_ENABLE) {
+ result = FILTER_ACTIVE;
+ }
+ } else {
+ kqunlock(kq);
+ result = filter_call(knote_fops(kn), f_touch(kn, kev));
+ kqlock(kq);
+ }
+
+ if (kev->flags & EV_ERROR) {
+ result = 0;
+ } else {
+ /* accept new kevent state */
+ if ((kn->kn_status & KN_UDATA_SPECIFIC) == 0)
+ kn->kn_udata = kev->udata;
+ if (kev->flags & EV_DISABLE)
+ knote_disable(kn);
+ if (result & (FILTER_UPDATE_REQ_QOS | FILTER_ADJUST_EVENT_QOS_BIT))
+ knote_dequeue(kn);
+ if ((result & FILTER_UPDATE_REQ_QOS) &&
+ kev->qos && kev->qos != kn->kn_qos) {
+ knote_reset_priority(kn, kev->qos);
+ }
+ if (result & FILTER_ACTIVE) {
+ thread_qos_t qos;
+ if (result & FILTER_ADJUST_EVENT_QOS_BIT) {
+ if (knote_should_apply_qos_override(kq, kn, result, &qos)) {
+ knote_apply_qos_override(kn, qos);
+ }
+ }
+ knote_activate(kn);
+ }
+ if (result & (FILTER_UPDATE_REQ_QOS | FILTER_ADJUST_EVENT_QOS_BIT)) {
+ if (knote_enqueue(kn) && (kn->kn_status & KN_ACTIVE)) {
+ knote_wakeup(kn);
+ }
+ }
+ if (kev->flags & EV_ENABLE)
+ knote_enable(kn);
+ }
+ }
+
+out_unlock:
+ if ((result & FILTER_REGISTER_WAIT) == 0) {
+ /*
+ * When the filter asked for a post-register wait,
+ * we leave the knote and kqueue locked for kevent_register()
+ * to call the filter's f_post_register_wait hook.
+ */
+ knote_unlock(kq, kn, knlc, KNOTE_KQ_UNLOCK);
+ }
+
+out:
+ /* output local errors through the kevent */
+ if (error) {
+ kev->flags |= EV_ERROR;
+ kev->data = error;
+ }
+ return result;
+}
+
+/*
+ * knote_process - process a triggered event
+ *
+ * Validate that it is really still a triggered event
+ * by calling the filter routines (if necessary). Hold
+ * a use reference on the knote to avoid it being detached.
+ *
+ * If it is still considered triggered, we will have taken
+ * a copy of the state under the filter lock. We use that
+ * snapshot to dispatch the knote for future processing (or
+ * not, if this was a lost event).
+ *
+ * Our caller assures us that nobody else can be processing
+ * events from this knote during the whole operation. But
+ * others can be touching or posting events to the knote
+ * interspersed with our processing it.
+ *
+ * caller holds a reference on the kqueue.
+ * kqueue locked on entry and exit - but may be dropped
+ */
+static int
+knote_process(struct knote *kn,
+ kevent_callback_t callback,
+ void *callback_data,
+ struct filt_process_s *process_data)
+{
+ struct kevent_internal_s kev;
+ struct kqueue *kq = knote_get_kq(kn);
+ KNOTE_LOCK_CTX(knlc);
+ int result = FILTER_ACTIVE;
+ int error = 0;
+ bool drop = false;
+
+ bzero(&kev, sizeof(kev));
+
+ /*
+ * Must be active or stayactive
+ * Must be queued and not disabled/suppressed
+ */
+ assert(kn->kn_status & KN_QUEUED);
+ assert(kn->kn_status & (KN_ACTIVE|KN_STAYACTIVE));
+ assert(!(kn->kn_status & (KN_DISABLED|KN_SUPPRESSED|KN_DROPPING)));
+
+ if (kq->kq_state & KQ_WORKLOOP) {
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQWL_PROCESS),
+ ((struct kqworkloop *)kq)->kqwl_dynamicid,
+ kn->kn_udata, kn->kn_status | (kn->kn_id << 32),
+ kn->kn_filtid);
+ } else if (kq->kq_state & KQ_WORKQ) {
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQWQ_PROCESS),
+ 0, kn->kn_udata, kn->kn_status | (kn->kn_id << 32),
+ kn->kn_filtid);
+ } else {
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQ_PROCESS),
+ VM_KERNEL_UNSLIDE_OR_PERM(kq), kn->kn_udata,
+ kn->kn_status | (kn->kn_id << 32), kn->kn_filtid);
+ }
+
+ if ((kn->kn_status & KN_DROPPING) ||
+ !knote_lock(kq, kn, &knlc, KNOTE_KQ_LOCK_ALWAYS)) {
+ /*
+ * When the knote is dropping or has dropped,
+ * then there's nothing we want to process.
+ */
+ return EJUSTRETURN;
+ }
+
+ /*
+ * For deferred-drop or vanished events, we just create a fake
+ * event to acknowledge end-of-life. Otherwise, we call the
+ * filter's process routine to snapshot the kevent state under
+ * the filter's locking protocol.
+ *
+ * suppress knotes to avoid returning the same event multiple times in
+ * a single call.
+ */
+ knote_suppress(kn);
+
+ if (kn->kn_status & (KN_DEFERDELETE | KN_VANISHED)) {
+ /* create fake event */
+ kev.filter = kn->kn_filter;
+ kev.ident = kn->kn_id;
+ kev.flags = (kn->kn_status & KN_DEFERDELETE) ? EV_DELETE : EV_VANISHED;
+ kev.flags |= (EV_DISPATCH2 | EV_ONESHOT);
+ kev.udata = kn->kn_udata;
+ } else {
+ /* deactivate - so new activations indicate a wakeup */
+ knote_deactivate(kn);
+
+ kqunlock(kq);
+ result = filter_call(knote_fops(kn), f_process(kn, process_data, &kev));
+ kqlock(kq);
+ }
+
+ /*
+ * Determine how to dispatch the knote for future event handling.
+ * not-fired: just return (do not callout, leave deactivated).
+ * One-shot: If dispatch2, enter deferred-delete mode (unless this is
+ * is the deferred delete event delivery itself). Otherwise,
+ * drop it.
+ * Dispatch: don't clear state, just mark it disabled.
+ * Cleared: just leave it deactivated.
+ * Others: re-activate as there may be more events to handle.
+ * This will not wake up more handlers right now, but
+ * at the completion of handling events it may trigger
+ * more handler threads (TODO: optimize based on more than
+ * just this one event being detected by the filter).
+ */
+ if ((result & FILTER_ACTIVE) == 0) {
+ if ((kn->kn_status & (KN_ACTIVE | KN_STAYACTIVE)) == 0) {
+ /*
+ * Stay active knotes should not be unsuppressed or we'd create an
+ * infinite loop.
+ *
+ * Some knotes (like EVFILT_WORKLOOP) can be reactivated from
+ * within f_process() but that doesn't necessarily make them
+ * ready to process, so we should leave them be.
+ *
+ * For other knotes, since we will not return an event,
+ * there's no point keeping the knote suppressed.
+ */
+ knote_unsuppress(kn);
+ }
+ knote_unlock(kq, kn, &knlc, KNOTE_KQ_LOCK_ALWAYS);
+ return EJUSTRETURN;
+ }
+
+ if (result & FILTER_ADJUST_EVENT_QOS_BIT)
+ knote_adjust_qos(kq, kn, result);
+ kev.qos = _pthread_priority_combine(kn->kn_qos, kn->kn_qos_override);
+
+ if (kev.flags & EV_ONESHOT) {
+ if ((kn->kn_status & (KN_DISPATCH2 | KN_DEFERDELETE)) == KN_DISPATCH2) {
+ /* defer dropping non-delete oneshot dispatch2 events */
+ kn->kn_status |= KN_DEFERDELETE;
+ knote_disable(kn);
+ } else {
+ drop = true;
+ }
+ } else if (kn->kn_status & KN_DISPATCH) {
+ /* disable all dispatch knotes */
+ knote_disable(kn);
+ } else if ((kev.flags & EV_CLEAR) == 0) {
+ /* re-activate in case there are more events */
+ knote_activate(kn);
+ }
+
+ /*
+ * callback to handle each event as we find it.
+ * If we have to detach and drop the knote, do
+ * it while we have the kq unlocked.
+ */
+ if (drop) {
+ knote_drop(kq, kn, &knlc);
+ } else {
+ knote_unlock(kq, kn, &knlc, KNOTE_KQ_UNLOCK);
+ }
+
+ if (kev.flags & EV_VANISHED) {
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KNOTE_VANISHED),
+ kev.ident, kn->kn_udata, kn->kn_status | (kn->kn_id << 32),
+ kn->kn_filtid);
+ }
+
+ error = (callback)(kq, &kev, callback_data);
+ kqlock(kq);
+ return error;
+}
+
+/*
+ * Returns -1 if the kqueue was unbound and processing should not happen
+ */
+#define KQWQAE_BEGIN_PROCESSING 1
+#define KQWQAE_END_PROCESSING 2
+#define KQWQAE_UNBIND 3
+static int
+kqworkq_acknowledge_events(struct kqworkq *kqwq, struct kqrequest *kqr,
+ int kevent_flags, int kqwqae_op)
+{
+ thread_qos_t old_override = THREAD_QOS_UNSPECIFIED;
+ thread_t thread = kqr->kqr_thread;
+ struct knote *kn;
+ int rc = 0;
+ bool seen_stayactive = false, unbind;
+
+ kqlock_held(&kqwq->kqwq_kqueue);
+
+ if (!TAILQ_EMPTY(&kqr->kqr_suppressed)) {
+ /*
+ * Return suppressed knotes to their original state.
+ * For workq kqueues, suppressed ones that are still
+ * truly active (not just forced into the queue) will
+ * set flags we check below to see if anything got
+ * woken up.
+ */
+ while ((kn = TAILQ_FIRST(&kqr->kqr_suppressed)) != NULL) {
+ assert(kn->kn_status & KN_SUPPRESSED);
+ knote_unsuppress(kn);
+ if (kn->kn_status & KN_STAYACTIVE) {
+ seen_stayactive = true;
+ }
+ }
+ }
+
+ kq_req_lock(kqwq);
+
+#if DEBUG || DEVELOPMENT
+ thread_t self = current_thread();
+ struct uthread *ut = get_bsdthread_info(self);
+
+ assert(kqr->kqr_state & KQR_THREQUESTED);
+ assert(kqr->kqr_thread == self);
+ assert(ut->uu_kqr_bound == kqr);
+#endif // DEBUG || DEVELOPMENT
+
+ if (kqwqae_op == KQWQAE_UNBIND) {
+ unbind = true;
+ } else if ((kevent_flags & KEVENT_FLAG_PARKING) == 0) {
+ unbind = false;
+ } else if (kqwqae_op == KQWQAE_BEGIN_PROCESSING && seen_stayactive) {
+ /*
+ * When we unsuppress stayactive knotes, for the kind that are hooked
+ * through select, we need to process once before we can assert there's
+ * no event pending. Hence we can't unbind during BEGIN PROCESSING.
+ */
+ unbind = false;
+ } else {
+ unbind = ((kqr->kqr_state & KQR_WAKEUP) == 0);
+ }
+ if (unbind) {
+ old_override = kqworkq_unbind_locked(kqwq, kqr, thread);
+ rc = -1;
+ /*
+ * request a new thread if we didn't process the whole queue or real events
+ * have happened (not just putting stay-active events back).
+ */
+ if (kqr->kqr_state & KQR_WAKEUP) {
+ kqueue_threadreq_initiate(&kqwq->kqwq_kqueue, kqr,
+ kqr->kqr_qos_index, 0);
+ }
+ }
+
+ if (rc == 0) {
+ /*
+ * Reset wakeup bit to notice events firing while we are processing,
+ * as we cannot rely on the bucket queue emptiness because of stay
+ * active knotes.
+ */
+ kqr->kqr_state &= ~KQR_WAKEUP;
+ }
+
+ kq_req_unlock(kqwq);
+
+ if (old_override) {
+ thread_drop_ipc_override(thread);
+ }
+
+ return rc;
+}
+
+/*
+ * Return 0 to indicate that processing should proceed,
+ * -1 if there is nothing to process.
+ *
+ * Called with kqueue locked and returns the same way,
+ * but may drop lock temporarily.
+ */
+static int
+kqworkq_begin_processing(struct kqworkq *kqwq, struct kqrequest *kqr,
+ int kevent_flags)
+{
+ int rc = 0;
+
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQWQ_PROCESS_BEGIN) | DBG_FUNC_START,
+ 0, kqr->kqr_qos_index);
+
+ rc = kqworkq_acknowledge_events(kqwq, kqr, kevent_flags,
+ KQWQAE_BEGIN_PROCESSING);
+
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQWQ_PROCESS_BEGIN) | DBG_FUNC_END,
+ thread_tid(kqr->kqr_thread), kqr->kqr_state);
+
+ return rc;
+}
+
+static inline bool
+kqworkloop_is_processing_on_current_thread(struct kqworkloop *kqwl)
+{
+ struct kqueue *kq = &kqwl->kqwl_kqueue;
+
+ kqlock_held(kq);
+
+ if (kq->kq_state & KQ_PROCESSING) {
+ /*
+ * KQ_PROCESSING is unset with the kqlock held, and the kqr thread is
+ * never modified while KQ_PROCESSING is set, meaning that peeking at
+ * its value is safe from this context.
+ */
+ return kqwl->kqwl_request.kqr_thread == current_thread();
+ }
+ return false;
+}
+
+static thread_qos_t
+kqworkloop_acknowledge_events(struct kqworkloop *kqwl)
+{
+ struct kqrequest *kqr = &kqwl->kqwl_request;
+ kq_index_t qos = THREAD_QOS_UNSPECIFIED;
+ struct knote *kn, *tmp;
+
+ kqlock_held(&kqwl->kqwl_kqueue);
+
+ TAILQ_FOREACH_SAFE(kn, &kqr->kqr_suppressed, kn_tqe, tmp) {
+ /*
+ * If a knote that can adjust QoS is disabled because of the automatic
+ * behavior of EV_DISPATCH, the knotes should stay suppressed so that
+ * further overrides keep pushing.
+ */
+ if (knote_fops(kn)->f_adjusts_qos && (kn->kn_status & KN_DISABLED) &&
+ (kn->kn_status & (KN_STAYACTIVE | KN_DROPPING)) == 0 &&
+ (kn->kn_flags & (EV_DISPATCH | EV_DISABLE)) == EV_DISPATCH) {
+ qos = MAX(qos, knote_get_qos_override_index(kn));
+ continue;
+ }
+ knote_unsuppress(kn);
+ }
+
+ return qos;
+}
+
+static int
+kqworkloop_begin_processing(struct kqworkloop *kqwl, unsigned int kevent_flags)
+{
+ struct kqrequest *kqr = &kqwl->kqwl_request;
+ struct kqueue *kq = &kqwl->kqwl_kqueue;
+ thread_qos_t old_override = THREAD_QOS_UNSPECIFIED, qos_override;
+ thread_t thread = kqr->kqr_thread;
+ int rc = 0, op = KQWL_UTQ_NONE;
+
+ kqlock_held(kq);
+
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQWL_PROCESS_BEGIN) | DBG_FUNC_START,
+ kqwl->kqwl_dynamicid, 0, 0);
+
+ /* nobody else should still be processing */
+ assert((kq->kq_state & KQ_PROCESSING) == 0);
+
+ kq->kq_state |= KQ_PROCESSING;
+
+ if (!TAILQ_EMPTY(&kqr->kqr_suppressed)) {
+ op = KQWL_UTQ_RESET_WAKEUP_OVERRIDE;
+ }
+
+ if (kevent_flags & KEVENT_FLAG_PARKING) {
+ /*
+ * When "parking" we want to process events and if no events are found
+ * unbind.
+ *
+ * However, non overcommit threads sometimes park even when they have
+ * more work so that the pool can narrow. For these, we need to unbind
+ * early, so that calling kqworkloop_update_threads_qos() can ask the
+ * workqueue subsystem whether the thread should park despite having
+ * pending events.
+ */
+ if (kqr->kqr_state & KQR_THOVERCOMMIT) {
+ op = KQWL_UTQ_PARKING;
+ } else {
+ op = KQWL_UTQ_UNBINDING;
+ }
+ }
+ if (op == KQWL_UTQ_NONE) {
+ goto done;
+ }
+
+ qos_override = kqworkloop_acknowledge_events(kqwl);
+
+ kq_req_lock(kqwl);
+
+ if (op == KQWL_UTQ_UNBINDING) {
+ old_override = kqworkloop_unbind_locked(kqwl, thread);
+ (void)kqueue_release(kqwl, KQUEUE_CANT_BE_LAST_REF);
+ }
+ kqworkloop_update_threads_qos(kqwl, op, qos_override);
+ if (op == KQWL_UTQ_PARKING) {
+ if (!TAILQ_EMPTY(&kqwl->kqwl_queue[KQWL_BUCKET_STAYACTIVE])) {
+ /*
+ * We cannot trust KQR_WAKEUP when looking at stay active knotes.
+ * We need to process once, and kqworkloop_end_processing will
+ * handle the unbind.
+ */
+ } else if ((kqr->kqr_state & KQR_WAKEUP) == 0 || kqwl->kqwl_owner) {
+ old_override = kqworkloop_unbind_locked(kqwl, thread);
+ (void)kqueue_release(kqwl, KQUEUE_CANT_BE_LAST_REF);
+ rc = -1;
+ }
+ } else if (op == KQWL_UTQ_UNBINDING) {
+ if (kqr->kqr_thread == thread) {
+ /*
+ * The thread request fired again, passed the admission check and
+ * got bound to the current thread again.
+ */
+ } else {
+ rc = -1;
+ }
+ }
+
+ if (rc == 0) {
+ /*
+ * Reset wakeup bit to notice stay active events firing while we are
+ * processing, as we cannot rely on the stayactive bucket emptiness.
+ */
+ kqr->kqr_wakeup_indexes &= ~KQWL_STAYACTIVE_FIRED_BIT;
+ } else {
+ kq->kq_state &= ~KQ_PROCESSING;
+ }
+
+ kq_req_unlock(kqwl);
+
+ if (old_override) {
+ thread_drop_ipc_override(thread);
+ }
+
+done:
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQWL_PROCESS_BEGIN) | DBG_FUNC_END,
+ kqwl->kqwl_dynamicid, 0, 0);
+
+ return rc;
+}
+
+/*
+ * Return 0 to indicate that processing should proceed,
+ * -1 if there is nothing to process.
+ *
+ * Called with kqueue locked and returns the same way,
+ * but may drop lock temporarily.
+ * May block.
+ */
+static int
+kqfile_begin_processing(struct kqueue *kq)
+{
+ struct kqtailq *suppressq;
+
+ kqlock_held(kq);
+
+ assert((kq->kq_state & (KQ_WORKQ | KQ_WORKLOOP)) == 0);
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQ_PROCESS_BEGIN) | DBG_FUNC_START,
+ VM_KERNEL_UNSLIDE_OR_PERM(kq), 0);
+
+ /* wait to become the exclusive processing thread */
+ for (;;) {
+ if (kq->kq_state & KQ_DRAIN) {
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQ_PROCESS_BEGIN) | DBG_FUNC_END,
+ VM_KERNEL_UNSLIDE_OR_PERM(kq), 2);
+ return -1;
+ }
+
+ if ((kq->kq_state & KQ_PROCESSING) == 0)
+ break;
+
+ /* if someone else is processing the queue, wait */
+ kq->kq_state |= KQ_PROCWAIT;
+ suppressq = kqueue_get_suppressed_queue(kq, NULL);
+ waitq_assert_wait64((struct waitq *)&kq->kq_wqs,
+ CAST_EVENT64_T(suppressq), THREAD_UNINT | THREAD_WAIT_NOREPORT,
+ TIMEOUT_WAIT_FOREVER);
+
+ kqunlock(kq);
+ thread_block(THREAD_CONTINUE_NULL);
+ kqlock(kq);
+ }
+
+ /* Nobody else processing */
+
+ /* clear pre-posts and KQ_WAKEUP now, in case we bail early */
+ waitq_set_clear_preposts(&kq->kq_wqs);
+ kq->kq_state &= ~KQ_WAKEUP;
+
+ /* anything left to process? */
+ if (kqueue_queue_empty(kq, QOS_INDEX_KQFILE)) {
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQ_PROCESS_BEGIN) | DBG_FUNC_END,
+ VM_KERNEL_UNSLIDE_OR_PERM(kq), 1);
+ return -1;
+ }
+
+ /* convert to processing mode */
+ kq->kq_state |= KQ_PROCESSING;
+
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQ_PROCESS_BEGIN) | DBG_FUNC_END,
+ VM_KERNEL_UNSLIDE_OR_PERM(kq));
+
+ return 0;
+}
+
+/*
+ * Try to end the processing, only called when a workq thread is attempting to
+ * park (KEVENT_FLAG_PARKING is set).
+ *
+ * When returning -1, the kqworkq is setup again so that it is ready to be
+ * processed.
+ */
+static int
+kqworkq_end_processing(struct kqworkq *kqwq, struct kqrequest *kqr,
+ int kevent_flags)
+{
+ if (!kqueue_queue_empty(&kqwq->kqwq_kqueue, kqr->kqr_qos_index)) {
+ /* remember we didn't process everything */
+ kq_req_lock(kqwq);
+ kqr->kqr_state |= KQR_WAKEUP;
+ kq_req_unlock(kqwq);
+ }
+
+ if (kevent_flags & KEVENT_FLAG_PARKING) {
+ /*
+ * if acknowledge events "succeeds" it means there are events,
+ * which is a failure condition for end_processing.
+ */
+ int rc = kqworkq_acknowledge_events(kqwq, kqr, kevent_flags,
+ KQWQAE_END_PROCESSING);
+ if (rc == 0) {
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+/*
+ * Try to end the processing, only called when a workq thread is attempting to
+ * park (KEVENT_FLAG_PARKING is set).
+ *
+ * When returning -1, the kqworkq is setup again so that it is ready to be
+ * processed (as if kqworkloop_begin_processing had just been called).
+ *
+ * If successful and KEVENT_FLAG_PARKING was set in the kevent_flags,
+ * the kqworkloop is unbound from its servicer as a side effect.
+ */
+static int
+kqworkloop_end_processing(struct kqworkloop *kqwl, int flags, int kevent_flags)
+{
+ struct kqueue *kq = &kqwl->kqwl_kqueue;
+ struct kqrequest *kqr = &kqwl->kqwl_request;
+ thread_qos_t old_override = THREAD_QOS_UNSPECIFIED, qos_override;
+ thread_t thread = kqr->kqr_thread;
+ int rc = 0;
+
+ kqlock_held(kq);
+
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQWL_PROCESS_END) | DBG_FUNC_START,
+ kqwl->kqwl_dynamicid, 0, 0);
+
+ if (flags & KQ_PROCESSING) {
+ assert(kq->kq_state & KQ_PROCESSING);
+
+ /*
+ * If we still have queued stayactive knotes, remember we didn't finish
+ * processing all of them. This should be extremely rare and would
+ * require to have a lot of them registered and fired.
+ */
+ if (!TAILQ_EMPTY(&kqwl->kqwl_queue[KQWL_BUCKET_STAYACTIVE])) {
+ kq_req_lock(kqwl);
+ kqworkloop_update_threads_qos(kqwl, KQWL_UTQ_UPDATE_WAKEUP_QOS,
+ KQWL_BUCKET_STAYACTIVE);
+ kq_req_unlock(kqwl);
+ }
+
+ /*
+ * When KEVENT_FLAG_PARKING is set, we need to attempt an unbind while
+ * still under the lock.
+ *
+ * So we do everything kqworkloop_unbind() would do, but because we're
+ * inside kqueue_process(), if the workloop actually received events
+ * while our locks were dropped, we have the opportunity to fail the end
+ * processing and loop again.
+ *
+ * This avoids going through the process-wide workqueue lock hence
+ * scales better.
+ */
+ if (kevent_flags & KEVENT_FLAG_PARKING) {
+ qos_override = kqworkloop_acknowledge_events(kqwl);
+ }
+ }
+
+ kq_req_lock(kqwl);
+
+ if (kevent_flags & KEVENT_FLAG_PARKING) {
+ kqworkloop_update_threads_qos(kqwl, KQWL_UTQ_PARKING, qos_override);
+ if ((kqr->kqr_state & KQR_WAKEUP) && !kqwl->kqwl_owner) {
+ /*
+ * Reset wakeup bit to notice stay active events firing while we are
+ * processing, as we cannot rely on the stayactive bucket emptiness.
+ */
+ kqr->kqr_wakeup_indexes &= ~KQWL_STAYACTIVE_FIRED_BIT;
+ rc = -1;
+ } else {
+ old_override = kqworkloop_unbind_locked(kqwl, thread);
+ (void)kqueue_release(kqwl, KQUEUE_CANT_BE_LAST_REF);
+ kq->kq_state &= ~flags;
+ }
+ } else {
+ kq->kq_state &= ~flags;
+ kqr->kqr_state |= KQR_R2K_NOTIF_ARMED;
+ kqworkloop_update_threads_qos(kqwl, KQWL_UTQ_RECOMPUTE_WAKEUP_QOS, 0);
+ }
+
+ kq_req_unlock(kqwl);
+
+ if (old_override) {
+ thread_drop_ipc_override(thread);
+ }
+
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQWL_PROCESS_END) | DBG_FUNC_END,
+ kqwl->kqwl_dynamicid, 0, 0);
+
+ return rc;
+}
+
+/*
+ * Called with kqueue lock held.
+ */
+static void
+kqfile_end_processing(struct kqueue *kq)
+{
+ struct knote *kn;
+ struct kqtailq *suppressq;
+ int procwait;
+
+ kqlock_held(kq);
+
+ assert((kq->kq_state & (KQ_WORKQ|KQ_WORKLOOP)) == 0);
+
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQ_PROCESS_END),
+ VM_KERNEL_UNSLIDE_OR_PERM(kq), 0);
+
+ /*
+ * Return suppressed knotes to their original state.
+ */
+ suppressq = kqueue_get_suppressed_queue(kq, NULL);
+ while ((kn = TAILQ_FIRST(suppressq)) != NULL) {
+ assert(kn->kn_status & KN_SUPPRESSED);
+ knote_unsuppress(kn);
+ }
+
+ procwait = (kq->kq_state & KQ_PROCWAIT);
+ kq->kq_state &= ~(KQ_PROCESSING | KQ_PROCWAIT);
+
+ if (procwait) {
+ /* first wake up any thread already waiting to process */
+ waitq_wakeup64_all((struct waitq *)&kq->kq_wqs,
+ CAST_EVENT64_T(suppressq),
+ THREAD_AWAKENED,
+ WAITQ_ALL_PRIORITIES);
+ }
+}
+
+static int
+kqueue_workloop_ctl_internal(proc_t p, uintptr_t cmd, uint64_t __unused options,
+ struct kqueue_workloop_params *params, int *retval)
+{
+ int error = 0;
+ int fd;
+ struct fileproc *fp;
+ struct kqueue *kq;
+ struct kqworkloop *kqwl;
+ struct filedesc *fdp = p->p_fd;
+ workq_threadreq_param_t trp = { };
+
+ switch (cmd) {
+ case KQ_WORKLOOP_CREATE:
+ if (!params->kqwlp_flags) {
+ error = EINVAL;
+ break;
+ }
+
+ if ((params->kqwlp_flags & KQ_WORKLOOP_CREATE_SCHED_PRI) &&
+ (params->kqwlp_sched_pri < 1 ||
+ params->kqwlp_sched_pri > 63 /* MAXPRI_USER */)) {
+ error = EINVAL;
+ break;
+ }
+
+ if ((params->kqwlp_flags & KQ_WORKLOOP_CREATE_SCHED_POL) &&
+ invalid_policy(params->kqwlp_sched_pol)) {
+ error = EINVAL;
+ break;
+ }
+
+ if ((params->kqwlp_flags & KQ_WORKLOOP_CREATE_CPU_PERCENT) &&
+ (params->kqwlp_cpu_percent <= 0 ||
+ params->kqwlp_cpu_percent > 100 ||
+ params->kqwlp_cpu_refillms <= 0 ||
+ params->kqwlp_cpu_refillms > 0x00ffffff)) {
+ error = EINVAL;
+ break;
+ }
+
+ if (params->kqwlp_flags & KQ_WORKLOOP_CREATE_SCHED_PRI) {
+ trp.trp_flags |= TRP_PRIORITY;
+ trp.trp_pri = params->kqwlp_sched_pri;
+ }
+ if (params->kqwlp_flags & KQ_WORKLOOP_CREATE_SCHED_POL) {
+ trp.trp_flags |= TRP_POLICY;
+ trp.trp_pol = params->kqwlp_sched_pol;
+ }
+ if (params->kqwlp_flags & KQ_WORKLOOP_CREATE_CPU_PERCENT) {
+ trp.trp_flags |= TRP_CPUPERCENT;
+ trp.trp_cpupercent = (uint8_t)params->kqwlp_cpu_percent;
+ trp.trp_refillms = params->kqwlp_cpu_refillms;
+ }
+
+ error = kevent_get_kq(p, params->kqwlp_id, &trp,
+ KEVENT_FLAG_DYNAMIC_KQUEUE | KEVENT_FLAG_WORKLOOP |
+ KEVENT_FLAG_DYNAMIC_KQ_MUST_NOT_EXIST , &fp, &fd, &kq);
+ if (error) {
+ break;
+ }
+
+ if (!(fdp->fd_flags & FD_WORKLOOP)) {
+ /* FD_WORKLOOP indicates we've ever created a workloop
+ * via this syscall but its only ever added to a process, never
+ * removed.
+ */
+ proc_fdlock(p);
+ fdp->fd_flags |= FD_WORKLOOP;
+ proc_fdunlock(p);
+ }
+ break;
+ case KQ_WORKLOOP_DESTROY:
+ error = kevent_get_kq(p, params->kqwlp_id, NULL,
+ KEVENT_FLAG_DYNAMIC_KQUEUE | KEVENT_FLAG_WORKLOOP |
+ KEVENT_FLAG_DYNAMIC_KQ_MUST_EXIST , &fp, &fd, &kq);
+ if (error) {
+ break;
+ }
+ kqlock(kq);
+ kqwl = (struct kqworkloop *)kq;
+ trp.trp_value = kqwl->kqwl_params;
+ if (trp.trp_flags && !(trp.trp_flags & TRP_RELEASED)) {
+ trp.trp_flags |= TRP_RELEASED;
+ kqueue_release(kq, KQUEUE_CANT_BE_LAST_REF);
+ } else {
+ error = EINVAL;
+ }
+ kqunlock(kq);
+ kqueue_release_last(p, kq);
+ break;
+ }
+ *retval = 0;
+ return error;
+}
+
+int
+kqueue_workloop_ctl(proc_t p, struct kqueue_workloop_ctl_args *uap, int *retval)
+{
+ struct kqueue_workloop_params params = {
+ .kqwlp_id = 0,
+ };
+ if (uap->sz < sizeof(params.kqwlp_version)) {
+ return EINVAL;
+ }
+
+ size_t copyin_sz = MIN(sizeof(params), uap->sz);
+ int rv = copyin(uap->addr, ¶ms, copyin_sz);
+ if (rv) {
+ return rv;
+ }
+
+ if (params.kqwlp_version != (int)uap->sz) {
+ return EINVAL;
+ }
+
+ return kqueue_workloop_ctl_internal(p, uap->cmd, uap->options, ¶ms,
+ retval);
+}
+
+/*
+ * kqueue_process - process the triggered events in a kqueue
+ *
+ * Walk the queued knotes and validate that they are really still triggered
+ * events by calling the filter routines (if necessary).
+ *
+ * For each event that is still considered triggered, invoke the callback
+ * routine provided.
+ *
+ * caller holds a reference on the kqueue.
+ * kqueue locked on entry and exit - but may be dropped
+ * kqueue list locked (held for duration of call)
+ */
+static int
+kqueue_process(struct kqueue *kq,
+ kevent_callback_t callback,
+ void *callback_data,
+ struct filt_process_s *process_data,
+ int *countp)
+{
+ struct uthread *ut = get_bsdthread_info(current_thread());
+ struct kqrequest *kqr = ut->uu_kqr_bound;
+ struct knote *kn;
+ unsigned int flags = process_data ? process_data->fp_flags : 0;
+ int nevents = 0, error = 0, rc = 0;
+ struct kqtailq *base_queue, *queue;
+ kqueue_t kqu = { .kq = kq };
+#if DEBUG || DEVELOPMENT
+ int retries = 64;
+#endif
+
+ if (kq->kq_state & KQ_WORKQ) {
+ if (kqr == NULL || (kqr->kqr_state & KQR_WORKLOOP)) {
+ return EJUSTRETURN;
+ }
+ rc = kqworkq_begin_processing(kqu.kqwq, kqr, flags);
+ } else if (kq->kq_state & KQ_WORKLOOP) {
+ if (ut->uu_kqr_bound != &kqu.kqwl->kqwl_request) {
+ return EJUSTRETURN;
+ }
+ rc = kqworkloop_begin_processing(kqu.kqwl, flags);
+ } else {
+ rc = kqfile_begin_processing(kq);
+ }
+
+ if (rc == -1) {
+ /* Nothing to process */
+ *countp = 0;
+ return 0;
+ }
+
+ /*
+ * loop through the enqueued knotes associated with this request,
+ * processing each one. Each request may have several queues
+ * of knotes to process (depending on the type of kqueue) so we
+ * have to loop through all the queues as long as we have additional
+ * space.
+ */
+
+process_again:
+ if (kq->kq_state & KQ_WORKQ) {
+ base_queue = queue = &kqu.kqwq->kqwq_queue[kqr->kqr_qos_index];
+ } else if (kq->kq_state & KQ_WORKLOOP) {
+ base_queue = &kqu.kqwl->kqwl_queue[0];
+ queue = &kqu.kqwl->kqwl_queue[KQWL_NBUCKETS - 1];
+ } else {
+ base_queue = queue = &kq->kq_queue[QOS_INDEX_KQFILE];
+ }
+
+ do {
+ while (error == 0 && (kn = TAILQ_FIRST(queue)) != NULL) {
+ error = knote_process(kn, callback, callback_data, process_data);
+ if (error == EJUSTRETURN) {
+ error = 0;
+ } else {
+ nevents++;
+ }
+ /* error is EWOULDBLOCK when the out event array is full */
+ }
+
+ if (error == EWOULDBLOCK) {
+ /* break out if no more space for additional events */
+ error = 0;
+ break;
+ }
+ } while (queue-- > base_queue);
+
+ *countp = nevents;
+
+ /*
+ * If KEVENT_FLAG_PARKING is set, and no kevents have been returned,
+ * we want to unbind the kqrequest from the thread.
+ *
+ * However, because the kq locks are dropped several times during process,
+ * new knotes may have fired again, in which case, we want to fail the end
+ * processing and process again, until it converges.
+ *
+ * If we returned events however, end processing never fails.
+ */
+ if (error || nevents) flags &= ~KEVENT_FLAG_PARKING;
+ if (kq->kq_state & KQ_WORKQ) {
+ rc = kqworkq_end_processing(kqu.kqwq, kqr, flags);
+ } else if (kq->kq_state & KQ_WORKLOOP) {
+ rc = kqworkloop_end_processing(kqu.kqwl, KQ_PROCESSING, flags);
+ } else {
+ kqfile_end_processing(kq);
+ rc = 0;
+ }
+ if (rc == -1) {
+ assert(flags & KEVENT_FLAG_PARKING);
+#if DEBUG || DEVELOPMENT
+ if (retries-- == 0) {
+ panic("kevent: way too many knote_process retries, kq: %p (0x%02x)",
+ kq, kq->kq_state);
+ }
+#endif
+ goto process_again;
+ }
+ return error;
+}
+
+static void
+kqueue_scan_continue(void *data, wait_result_t wait_result)
+{
+ thread_t self = current_thread();
+ uthread_t ut = (uthread_t)get_bsdthread_info(self);
+ struct _kqueue_scan * cont_args = &ut->uu_save.uus_kqueue_scan;
+ struct kqueue *kq = (struct kqueue *)data;
+ struct filt_process_s *process_data = cont_args->process_data;
+ int error;
+ int count;
+
+ /* convert the (previous) wait_result to a proper error */
+ switch (wait_result) {
+ case THREAD_AWAKENED: {
+ kqlock(kq);
+ retry:
+ error = kqueue_process(kq, cont_args->call, cont_args->data,
+ process_data, &count);
+ if (error == 0 && count == 0) {
+ if (kq->kq_state & KQ_DRAIN) {
+ kqunlock(kq);
+ goto drain;
+ }
+
+ if (kq->kq_state & KQ_WAKEUP)
+ goto retry;
+
+ waitq_assert_wait64((struct waitq *)&kq->kq_wqs,
+ KQ_EVENT, THREAD_ABORTSAFE,
+ cont_args->deadline);
+ kq->kq_state |= KQ_SLEEP;
+ kqunlock(kq);
+ thread_block_parameter(kqueue_scan_continue, kq);
+ /* NOTREACHED */
+ }
+ kqunlock(kq);
+ } break;
+ case THREAD_TIMED_OUT:
+ error = EWOULDBLOCK;
+ break;
+ case THREAD_INTERRUPTED:
+ error = EINTR;
+ break;
+ case THREAD_RESTART:
+ drain:
+ error = EBADF;
+ break;
+ default:
+ panic("%s: - invalid wait_result (%d)", __func__,
+ wait_result);
+ error = 0;
+ }
+
+ /* call the continuation with the results */
+ assert(cont_args->cont != NULL);
+ (cont_args->cont)(kq, cont_args->data, error);
+}
+
+
+/*
+ * kqueue_scan - scan and wait for events in a kqueue
+ *
+ * Process the triggered events in a kqueue.
+ *
+ * If there are no events triggered arrange to
+ * wait for them. If the caller provided a
+ * continuation routine, then kevent_scan will
+ * also.
+ *
+ * The callback routine must be valid.
+ * The caller must hold a use-count reference on the kq.
+ */
+int
+kqueue_scan(struct kqueue *kq,
+ kevent_callback_t callback,
+ kqueue_continue_t continuation,
+ void *callback_data,
+ struct filt_process_s *process_data,
+ struct timeval *atvp,
+ __unused struct proc *p)
+{
+ thread_continue_t cont = THREAD_CONTINUE_NULL;
+ unsigned int flags;
+ uint64_t deadline;
+ int error;
+ int first;
+ int fd;
+
+ assert(callback != NULL);
+
+ /*
+ * Determine which QoS index we are servicing
+ */
+ flags = (process_data) ? process_data->fp_flags : 0;
+ fd = (process_data) ? process_data->fp_fd : -1;
+
+ first = 1;
+ for (;;) {
+ wait_result_t wait_result;
+ int count;
+
+ /*
+ * Make a pass through the kq to find events already
+ * triggered.
+ */
+ kqlock(kq);
+ error = kqueue_process(kq, callback, callback_data,
+ process_data, &count);
+ if (error || count)
+ break; /* lock still held */
+
+ /* looks like we have to consider blocking */
+ if (first) {
+ first = 0;
+ /* 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 +
+ atvp->tv_usec * (long)NSEC_PER_USEC,
+ &deadline);
+ if (now >= deadline) {
+ /* non-blocking call */
+ error = EWOULDBLOCK;
+ break; /* lock still held */
+ }
+ deadline -= now;
+ clock_absolutetime_interval_to_deadline(deadline, &deadline);
+ } else {
+ deadline = 0; /* block forever */
+ }
+
+ if (continuation) {
+ uthread_t ut = (uthread_t)get_bsdthread_info(current_thread());
+ struct _kqueue_scan *cont_args = &ut->uu_save.uus_kqueue_scan;
+
+ cont_args->call = callback;
+ cont_args->cont = continuation;
+ cont_args->deadline = deadline;
+ cont_args->data = callback_data;
+ cont_args->process_data = process_data;
+ cont = kqueue_scan_continue;
+ }
+ }
+
+ if (kq->kq_state & KQ_DRAIN) {
+ kqunlock(kq);
+ return EBADF;
+ }
+
+ /* If awakened during processing, try again */
+ if (kq->kq_state & KQ_WAKEUP) {
+ kqunlock(kq);
+ continue;
+ }
+
+ /* go ahead and wait */
+ waitq_assert_wait64_leeway((struct waitq *)&kq->kq_wqs,
+ KQ_EVENT, THREAD_ABORTSAFE,
+ TIMEOUT_URGENCY_USER_NORMAL,
+ deadline, TIMEOUT_NO_LEEWAY);
+ kq->kq_state |= KQ_SLEEP;
+ kqunlock(kq);
+ wait_result = thread_block_parameter(cont, kq);
+ /* NOTREACHED if (continuation != NULL) */
+
+ switch (wait_result) {
+ case THREAD_AWAKENED:
+ continue;
+ case THREAD_TIMED_OUT:
+ return EWOULDBLOCK;
+ case THREAD_INTERRUPTED:
+ return EINTR;
+ case THREAD_RESTART:
+ return EBADF;
+ default:
+ panic("%s: - bad wait_result (%d)", __func__,
+ wait_result);
+ error = 0;
+ }
+ }
+ kqunlock(kq);
+ return (error);
+}
+
+
+/*
+ * XXX
+ * This could be expanded to call kqueue_scan, if desired.
+ */
+/*ARGSUSED*/
+static int
+kqueue_read(__unused struct fileproc *fp,
+ __unused struct uio *uio,
+ __unused int flags,
+ __unused vfs_context_t ctx)
+{
+ return (ENXIO);
+}
+
+/*ARGSUSED*/
+static int
+kqueue_write(__unused struct fileproc *fp,
+ __unused struct uio *uio,
+ __unused int flags,
+ __unused vfs_context_t ctx)
+{
+ return (ENXIO);
+}
+
+/*ARGSUSED*/
+static int
+kqueue_ioctl(__unused struct fileproc *fp,
+ __unused u_long com,
+ __unused caddr_t data,
+ __unused vfs_context_t ctx)
+{
+ return (ENOTTY);
+}
+
+/*ARGSUSED*/
+static int
+kqueue_select(struct fileproc *fp, int which, void *wq_link_id,
+ __unused vfs_context_t ctx)
+{
+ struct kqueue *kq = (struct kqueue *)fp->f_data;
+ struct kqtailq *queue;
+ struct kqtailq *suppressq;
+ struct knote *kn;
+ int retnum = 0;
+
+ if (which != FREAD)
+ return (0);
+
+ kqlock(kq);
+
+ assert((kq->kq_state & KQ_WORKQ) == 0);
+
+ /*
+ * 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
+ * selinfo structure and we need to use the main one for the kqueue to
+ * catch events from KN_STAYQUEUED sources. So we do the linkage manually.
+ * (The select() call will unlink them when it ends).
+ */
+ if (wq_link_id != NULL) {
+ thread_t cur_act = current_thread();
+ struct uthread * ut = get_bsdthread_info(cur_act);
+
+ kq->kq_state |= KQ_SEL;
+ waitq_link((struct waitq *)&kq->kq_wqs, ut->uu_wqset,
+ WAITQ_SHOULD_LOCK, (uint64_t *)wq_link_id);
+
+ /* always consume the reserved link object */
+ waitq_link_release(*(uint64_t *)wq_link_id);
+ *(uint64_t *)wq_link_id = 0;
+
+ /*
+ * selprocess() is expecting that we send it back the waitq
+ * that was just added to the thread's waitq set. In order
+ * to not change the selrecord() API (which is exported to
+ * kexts), we pass this value back through the
+ * void *wq_link_id pointer we were passed. We need to use
+ * memcpy here because the pointer may not be properly aligned
+ * on 32-bit systems.
+ */
+ void *wqptr = &kq->kq_wqs;
+ memcpy(wq_link_id, (void *)&wqptr, sizeof(void *));
+ }
+
+ if (kqfile_begin_processing(kq) == -1) {
+ kqunlock(kq);
+ return (0);
+ }
+
+ queue = &kq->kq_queue[QOS_INDEX_KQFILE];
+ if (!TAILQ_EMPTY(queue)) {
+ /*
+ * there is something queued - but it might be a
+ * KN_STAYACTIVE knote, which may or may not have
+ * any events pending. Otherwise, we have to walk
+ * the list of knotes to see, and peek at the
+ * (non-vanished) stay-active ones to be really sure.
+ */
+ while ((kn = (struct knote *)TAILQ_FIRST(queue)) != NULL) {
+ if (kn->kn_status & KN_ACTIVE) {
+ retnum = 1;
+ goto out;
+ }
+ assert(kn->kn_status & KN_STAYACTIVE);
+ knote_suppress(kn);
+ }
+
+ /*
+ * There were no regular events on the queue, so take
+ * a deeper look at the stay-queued ones we suppressed.
+ */
+ suppressq = kqueue_get_suppressed_queue(kq, NULL);
+ while ((kn = (struct knote *)TAILQ_FIRST(suppressq)) != NULL) {
+ KNOTE_LOCK_CTX(knlc);
+ int result = 0;
+
+ /* If didn't vanish while suppressed - peek at it */
+ if ((kn->kn_status & KN_DROPPING) || !knote_lock(kq, kn, &knlc,
+ KNOTE_KQ_LOCK_ON_FAILURE)) {
+ continue;
+ }
+
+ result = filter_call(knote_fops(kn), f_peek(kn));
+
+ kqlock(kq);
+ knote_unlock(kq, kn, &knlc, KNOTE_KQ_LOCK_ALWAYS);
+
+ /* unsuppress it */
+ knote_unsuppress(kn);
+
+ /* has data or it has to report a vanish */
+ if (result & FILTER_ACTIVE) {
+ retnum = 1;
+ goto out;
+ }
+ }
+ }
+
+out:
+ kqfile_end_processing(kq);
+ kqunlock(kq);
+ return (retnum);
+}
+
+/*
+ * kqueue_close -
+ */
+/*ARGSUSED*/
+static int
+kqueue_close(struct fileglob *fg, __unused vfs_context_t ctx)
+{
+ struct kqfile *kqf = (struct kqfile *)fg->fg_data;
+
+ assert((kqf->kqf_state & KQ_WORKQ) == 0);
+ kqueue_dealloc(&kqf->kqf_kqueue);
+ fg->fg_data = NULL;
+ return (0);
+}
+
+/*
+ * Max depth of the nested kq path that can be created.
+ * Note that this has to be less than the size of kq_level
+ * to avoid wrapping around and mislabeling the level.
+ */
+#define MAX_NESTED_KQ 1000
+
+/*ARGSUSED*/
+/*
+ * The callers has taken a use-count reference on this kqueue and will donate it
+ * to the kqueue we are being added to. This keeps the kqueue from closing until
+ * that relationship is torn down.
+ */
+static int
+kqueue_kqfilter(__unused struct fileproc *fp, struct knote *kn,
+ __unused struct kevent_internal_s *kev, __unused vfs_context_t ctx)
+{
+ struct kqfile *kqf = (struct kqfile *)kn->kn_fp->f_data;
+ struct kqueue *kq = &kqf->kqf_kqueue;
+ struct kqueue *parentkq = knote_get_kq(kn);
+ uint16_t plevel = 0;
+
+ assert((kqf->kqf_state & KQ_WORKQ) == 0);
+
+ if (parentkq == kq || kn->kn_filter != EVFILT_READ) {
+ knote_set_error(kn, EINVAL);
+ return 0;
+ }
+
+ /*
+ * We have to avoid creating a cycle when nesting kqueues
+ * inside another. Rather than trying to walk the whole
+ * potential DAG of nested kqueues, we just use a simple
+ * ceiling protocol. When a kqueue is inserted into another,
+ * we check that the (future) parent is not already nested
+ * into another kqueue at a lower level than the potenial
+ * child (because it could indicate a cycle). If that test
+ * passes, we just mark the nesting levels accordingly.
+ *
+ * Only up to MAX_NESTED_KQ can be nested.
+ */
+
+ kqlock(parentkq);
+ if (parentkq->kq_level > 0 &&
+ parentkq->kq_level < kq->kq_level)
+ {
+ kqunlock(parentkq);
+ knote_set_error(kn, EINVAL);
+ return 0;
+ } else {
+ /* set parent level appropriately */
+ plevel = (parentkq->kq_level == 0)? 2: parentkq->kq_level;
+ if (plevel < kq->kq_level + 1) {
+ if (kq->kq_level + 1 > MAX_NESTED_KQ) {
+ kqunlock(parentkq);
+ knote_set_error(kn, EINVAL);
+ return 0;
+ }
+ plevel = kq->kq_level + 1;
+ }
+
+ parentkq->kq_level = plevel;
+ kqunlock(parentkq);
+
+ kn->kn_filtid = EVFILTID_KQREAD;
+ kqlock(kq);
+ KNOTE_ATTACH(&kqf->kqf_sel.si_note, kn);
+ /* indicate nesting in child, if needed */
+ if (kq->kq_level == 0)
+ kq->kq_level = 1;
+
+ int count = kq->kq_count;
+ kqunlock(kq);
+ return (count > 0);
+ }
+}
+
+/*
+ * kqueue_drain - called when kq is closed
+ */
+/*ARGSUSED*/
+static int
+kqueue_drain(struct fileproc *fp, __unused vfs_context_t ctx)
+{
+ struct kqueue *kq = (struct kqueue *)fp->f_fglob->fg_data;
+
+ assert((kq->kq_state & KQ_WORKQ) == 0);
+
+ kqlock(kq);
+ kq->kq_state |= KQ_DRAIN;
+ kqueue_interrupt(kq);
+ kqunlock(kq);
+ return (0);
+}
+
+/*ARGSUSED*/
+int
+kqueue_stat(struct kqueue *kq, void *ub, int isstat64, proc_t p)
+{
+ assert((kq->kq_state & KQ_WORKQ) == 0);
+
+ kqlock(kq);
+ if (isstat64 != 0) {
+ struct stat64 *sb64 = (struct stat64 *)ub;
+
+ bzero((void *)sb64, sizeof(*sb64));
+ sb64->st_size = kq->kq_count;
+ if (kq->kq_state & KQ_KEV_QOS)
+ sb64->st_blksize = sizeof(struct kevent_qos_s);
+ else if (kq->kq_state & KQ_KEV64)
+ sb64->st_blksize = sizeof(struct kevent64_s);
+ else if (IS_64BIT_PROCESS(p))
+ sb64->st_blksize = sizeof(struct user64_kevent);
+ else
+ sb64->st_blksize = sizeof(struct user32_kevent);
+ sb64->st_mode = S_IFIFO;
+ } else {
+ struct stat *sb = (struct stat *)ub;
+
+ bzero((void *)sb, sizeof(*sb));
+ sb->st_size = kq->kq_count;
+ if (kq->kq_state & KQ_KEV_QOS)
+ sb->st_blksize = sizeof(struct kevent_qos_s);
+ else if (kq->kq_state & KQ_KEV64)
+ sb->st_blksize = sizeof(struct kevent64_s);
+ else if (IS_64BIT_PROCESS(p))
+ sb->st_blksize = sizeof(struct user64_kevent);
+ else
+ sb->st_blksize = sizeof(struct user32_kevent);
+ sb->st_mode = S_IFIFO;
+ }
+ kqunlock(kq);
+ return (0);
+}
+
+/*
+ * Interact with the pthread kext to request a servicing there at a specific QoS
+ * level.
+ *
+ * - Caller holds the workq request lock
+ *
+ * - May be called with the kqueue's wait queue set locked,
+ * so cannot do anything that could recurse on that.
+ */
+static void
+kqueue_threadreq_initiate(struct kqueue *kq, struct kqrequest *kqr,
+ kq_index_t qos, int flags)
+{
+ assert(kqr->kqr_state & KQR_WAKEUP);
+ assert(kqr->kqr_thread == THREAD_NULL);
+ assert((kqr->kqr_state & KQR_THREQUESTED) == 0);
+ struct turnstile *ts = TURNSTILE_NULL;
+
+ if (workq_is_exiting(kq->kq_p)) {
+ return;
+ }
+
+ /* Add a thread request reference on the kqueue. */
+ kqueue_retain(kq);
+
+ kq_req_held(kq);
+
+ if (kq->kq_state & KQ_WORKLOOP) {
+ __assert_only struct kqworkloop *kqwl = (struct kqworkloop *)kq;
+
+ assert(kqwl->kqwl_owner == THREAD_NULL);
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQWL_THREQUEST),
+ kqwl->kqwl_dynamicid, 0, qos, kqr->kqr_state);
+ ts = kqwl->kqwl_turnstile;
+ } else {
+ assert(kq->kq_state & KQ_WORKQ);
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQWQ_THREQUEST),
+ -1, 0, qos, kqr->kqr_state);
+ }
+
+ kqr->kqr_state |= KQR_THREQUESTED;
+
+ /*
+ * New-style thread request supported.
+ * Provide the pthread kext a pointer to a workq_threadreq_s structure for
+ * its use until a corresponding kqueue_threadreq_bind callback.
+ */
+#if 0 // 45129862
+ if ((kq->kq_state & KQ_WORKLOOP) && current_proc() == kq->kq_p) {
+ flags |= WORKQ_THREADREQ_SET_AST_ON_FAILURE;
+ }
+#endif
+ if (qos == KQWQ_QOS_MANAGER) {
+ qos = WORKQ_THREAD_QOS_MANAGER;
+ }
+ if (!workq_kern_threadreq_initiate(kq->kq_p, kqr, ts, qos, flags)) {
+ /*
+ * Process is shutting down or exec'ing.
+ * All the kqueues are going to be cleaned up
+ * soon. Forget we even asked for a thread -
+ * and make sure we don't ask for more.
+ */
+ kqr->kqr_state &= ~(KQR_THREQUESTED | KQR_R2K_NOTIF_ARMED);
+ kqueue_release(kq, KQUEUE_CANT_BE_LAST_REF);
+ }
+}
+
+/*
+ * kqueue_threadreq_bind_prepost - prepost the bind to kevent
+ *
+ * This is used when kqueue_threadreq_bind may cause a lock inversion.
+ */
+void
+kqueue_threadreq_bind_prepost(struct proc *p __unused, workq_threadreq_t req,
+ thread_t thread)
+{
+ struct kqrequest *kqr = __container_of(req, struct kqrequest, kqr_req);
+ struct uthread *ut = get_bsdthread_info(thread);
+
+ req->tr_binding_thread = thread;
+ ut->uu_kqr_bound = kqr;
+ req->tr_state = TR_STATE_BINDING;
+
+ struct kqworkloop *kqwl = kqr_kqworkloop(kqr);
+ if (kqwl && kqwl->kqwl_turnstile) {
+ struct turnstile *ts = kqwl->kqwl_turnstile;
+ /*
+ * While a thread request is in flight, the workqueue
+ * is the interlock for the turnstile and can update the inheritor.
+ */
+ turnstile_update_inheritor(ts, thread, TURNSTILE_IMMEDIATE_UPDATE |
+ TURNSTILE_INHERITOR_THREAD);
+ turnstile_update_inheritor_complete(ts, TURNSTILE_INTERLOCK_HELD);
+ }
+}
+
+/*
+ * kqueue_threadreq_bind_commit - commit a bind prepost
+ *
+ * The workq code has to commit any binding prepost before the thread has
+ * a chance to come back to userspace (and do kevent syscalls) or be aborted.
+ */
+void
+kqueue_threadreq_bind_commit(struct proc *p, thread_t thread)
+{
+ struct uthread *ut = get_bsdthread_info(thread);
+ struct kqrequest *kqr = ut->uu_kqr_bound;
+ kqueue_t kqu = kqr_kqueue(p, kqr);
+
+ kq_req_lock(kqu);
+ if (kqr->kqr_req.tr_state == TR_STATE_BINDING) {
+ kqueue_threadreq_bind(p, &kqr->kqr_req, thread, 0);
+ }
+ kq_req_unlock(kqu);
+}
+
+static void
+kqueue_threadreq_modify(struct kqueue *kq, struct kqrequest *kqr, kq_index_t qos)
+{
+ assert(kqr->kqr_state & KQR_THREQUESTED);
+ assert(kqr->kqr_thread == THREAD_NULL);
+
+ kq_req_held(kq);
+
+ int flags = 0;
+#if 0 // 45129862
+ if ((kq->kq_state & KQ_WORKLOOP) && kq->kq_p == current_proc()) {
+ flags |= WORKQ_THREADREQ_SET_AST_ON_FAILURE;
+ }
+#endif
+ workq_kern_threadreq_modify(kq->kq_p, kqr, qos, flags);
+}
+
+/*
+ * kqueue_threadreq_bind - bind thread to processing kqrequest
+ *
+ * The provided thread will be responsible for delivering events
+ * associated with the given kqrequest. Bind it and get ready for
+ * the thread to eventually arrive.
+ */
+void
+kqueue_threadreq_bind(struct proc *p, workq_threadreq_t req, thread_t thread,
+ unsigned int flags)
+{
+ struct kqrequest *kqr = __container_of(req, struct kqrequest, kqr_req);
+ kqueue_t kqu = kqr_kqueue(p, kqr);
+ struct uthread *ut = get_bsdthread_info(thread);
+
+ kq_req_held(kqu);
+
+ assert(kqr->kqr_state & KQR_THREQUESTED);
+ assert(kqr->kqr_thread == THREAD_NULL);
+ assert(ut->uu_kqueue_override == 0);
+
+ if (kqr->kqr_req.tr_state == TR_STATE_BINDING) {
+ assert(ut->uu_kqr_bound == kqr);
+ assert(kqr->kqr_req.tr_binding_thread == thread);
+ kqr->kqr_req.tr_state = TR_STATE_IDLE;
+ kqr->kqr_req.tr_binding_thread = NULL;
+ } else {
+ assert(ut->uu_kqr_bound == NULL);
+ }
+
+ ut->uu_kqr_bound = kqr;
+ kqr->kqr_thread = thread;
+
+ if (kqu.kq->kq_state & KQ_WORKLOOP) {
+ struct turnstile *ts = kqu.kqwl->kqwl_turnstile;
+
+ if (__improbable(thread == kqu.kqwl->kqwl_owner)) {
+ /*
+ * <rdar://problem/38626999> shows that asserting here is not ok.
+ *
+ * This is not supposed to happen for correct use of the interface,
+ * but it is sadly possible for userspace (with the help of memory
+ * corruption, such as over-release of a dispatch queue) to make
+ * the creator thread the "owner" of a workloop.
+ *
+ * Once that happens, and that creator thread picks up the same
+ * workloop as a servicer, we trip this codepath. We need to fixup
+ * the state to forget about this thread being the owner, as the
+ * entire workloop state machine expects servicers to never be
+ * owners and everything would basically go downhill from here.
+ */
+ kqu.kqwl->kqwl_owner = THREAD_NULL;
+ if (kqworkloop_owner_override(kqu.kqwl)) {
+ thread_drop_ipc_override(thread);
+ }
+ thread_ends_owning_workloop(thread);
+ }
+
+ if (ts && (flags & KQUEUE_THREADERQ_BIND_NO_INHERITOR_UPDATE) == 0) {
+ /*
+ * Past this point, the interlock is the kq req lock again,
+ * so we can fix the inheritor for good.
+ */
+ filt_wlupdate_inheritor(kqu.kqwl, ts, TURNSTILE_IMMEDIATE_UPDATE);
+ turnstile_update_inheritor_complete(ts, TURNSTILE_INTERLOCK_HELD);
+ }
+
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQWL_BIND), kqu.kqwl->kqwl_dynamicid,
+ thread_tid(thread), kqr->kqr_qos_index,
+ (kqr->kqr_override_index << 16) | kqr->kqr_state);
+
+ ut->uu_kqueue_override = kqr->kqr_override_index;
+ if (kqr->kqr_override_index) {
+ thread_add_ipc_override(thread, kqr->kqr_override_index);
+ }
+ } else {
+ assert(kqr->kqr_override_index == 0);
+
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQWQ_BIND), -1,
+ thread_tid(thread), kqr->kqr_qos_index,
+ (kqr->kqr_override_index << 16) | kqr->kqr_state);
+ }
+}
+
+/*
+ * kqueue_threadreq_cancel - abort a pending thread request
+ *
+ * Called when exiting/exec'ing. Forget our pending request.
+ */
+void
+kqueue_threadreq_cancel(struct proc *p, workq_threadreq_t req)
+{
+ struct kqrequest *kqr = __container_of(req, struct kqrequest, kqr_req);
+ kqueue_t kqu = kqr_kqueue(p, kqr);
+
+ kq_req_lock(kqu);
+
+ assert(kqr->kqr_thread == THREAD_NULL);
+ assert(kqr->kqr_state & KQR_THREQUESTED);
+ kqr->kqr_state &= ~(KQR_THREQUESTED | KQR_R2K_NOTIF_ARMED);
+
+ kq_req_unlock(kqu);
+
+ kqueue_release_last(p, kqu); /* may dealloc kqu */
+}
+
+workq_threadreq_param_t
+kqueue_threadreq_workloop_param(workq_threadreq_t req)
+{
+ struct kqrequest *kqr = __container_of(req, struct kqrequest, kqr_req);
+ struct kqworkloop *kqwl;
+ workq_threadreq_param_t trp;
+
+ assert(kqr->kqr_state & KQR_WORKLOOP);
+ kqwl = __container_of(kqr, struct kqworkloop, kqwl_request);
+ trp.trp_value = kqwl->kqwl_params;
+ return trp;
+}
+
+/*
+ * kqueue_threadreq_unbind - unbind thread from processing kqueue
+ *
+ * End processing the per-QoS bucket of events and allow other threads
+ * to be requested for future servicing.
+ *
+ * caller holds a reference on the kqueue.
+ */
+void
+kqueue_threadreq_unbind(struct proc *p, struct kqrequest *kqr)
+{
+ if (kqr->kqr_state & KQR_WORKLOOP) {
+ kqworkloop_unbind(p, kqr_kqworkloop(kqr));
+ } else {
+ kqworkq_unbind(p, kqr);
+ }
+}
+
+/*
+ * If we aren't already busy processing events [for this QoS],
+ * request workq thread support as appropriate.
+ *
+ * TBD - for now, we don't segregate out processing by QoS.
+ *
+ * - May be called with the kqueue's wait queue set locked,
+ * so cannot do anything that could recurse on that.
+ */
+static void
+kqworkq_request_help(struct kqworkq *kqwq, kq_index_t qos_index)
+{
+ struct kqrequest *kqr;
+
+ /* convert to thread qos value */
+ assert(qos_index < KQWQ_NBUCKETS);
+
+ kq_req_lock(kqwq);
+ kqr = kqworkq_get_request(kqwq, qos_index);
+
+ if ((kqr->kqr_state & KQR_WAKEUP) == 0) {
+ kqr->kqr_state |= KQR_WAKEUP;
+ if ((kqr->kqr_state & KQR_THREQUESTED) == 0) {
+ kqueue_threadreq_initiate(&kqwq->kqwq_kqueue, kqr, qos_index, 0);
+ }
+ }
+ kq_req_unlock(kqwq);
+}
+
+static kq_index_t
+kqworkloop_owner_override(struct kqworkloop *kqwl)
+{
+ struct kqrequest *kqr = &kqwl->kqwl_request;
+ return MAX(kqr->kqr_qos_index, kqr->kqr_override_index);
+}
+
+static inline void
+kqworkloop_request_fire_r2k_notification(struct kqworkloop *kqwl)
+{
+ struct kqrequest *kqr = &kqwl->kqwl_request;
+
+ kq_req_held(kqwl);
+
+ if (kqr->kqr_state & KQR_R2K_NOTIF_ARMED) {
+ assert(kqr->kqr_thread);
+ kqr->kqr_state &= ~KQR_R2K_NOTIF_ARMED;
+ act_set_astkevent(kqr->kqr_thread, AST_KEVENT_RETURN_TO_KERNEL);
+ }
+}
+
+static void
+kqworkloop_update_threads_qos(struct kqworkloop *kqwl, int op, kq_index_t qos)
+{
+ struct kqrequest *kqr = &kqwl->kqwl_request;
+ struct kqueue *kq = &kqwl->kqwl_kqueue;
+ kq_index_t old_owner_override = kqworkloop_owner_override(kqwl);
+ kq_index_t i;
+
+ /* must hold the kqr lock */
+ kq_req_held(kqwl);
+
+ switch (op) {
+ case KQWL_UTQ_UPDATE_WAKEUP_QOS:
+ if (qos == KQWL_BUCKET_STAYACTIVE) {
+ /*
+ * the KQWL_BUCKET_STAYACTIVE is not a QoS bucket, we only remember
+ * a high watermark (kqr_stayactive_qos) of any stay active knote
+ * that was ever registered with this workloop.
+ *
+ * When waitq_set__CALLING_PREPOST_HOOK__() wakes up any stay active
+ * knote, we use this high-watermark as a wakeup-index, and also set
+ * the magic KQWL_BUCKET_STAYACTIVE bit to make sure we remember
+ * there is at least one stay active knote fired until the next full
+ * processing of this bucket.
+ */
+ kqr->kqr_wakeup_indexes |= KQWL_STAYACTIVE_FIRED_BIT;
+ qos = kqr->kqr_stayactive_qos;
+ assert(qos);
+ }
+ if (kqr->kqr_wakeup_indexes & (1 << qos)) {
+ assert(kqr->kqr_state & KQR_WAKEUP);
+ break;
+ }
+
+ kqr->kqr_wakeup_indexes |= (1 << qos);
+ kqr->kqr_state |= KQR_WAKEUP;
+ kqworkloop_request_fire_r2k_notification(kqwl);
+ goto recompute;
+
+ case KQWL_UTQ_UPDATE_STAYACTIVE_QOS:
+ assert(qos);
+ if (kqr->kqr_stayactive_qos < qos) {
+ kqr->kqr_stayactive_qos = qos;
+ if (kqr->kqr_wakeup_indexes & KQWL_STAYACTIVE_FIRED_BIT) {
+ assert(kqr->kqr_state & KQR_WAKEUP);
+ kqr->kqr_wakeup_indexes |= (1 << qos);
+ goto recompute;
+ }
+ }
+ break;
+
+ case KQWL_UTQ_PARKING:
+ case KQWL_UTQ_UNBINDING:
+ kqr->kqr_override_index = qos;
+ /* FALLTHROUGH */
+ case KQWL_UTQ_RECOMPUTE_WAKEUP_QOS:
+ if (op == KQWL_UTQ_RECOMPUTE_WAKEUP_QOS) {
+ assert(qos == THREAD_QOS_UNSPECIFIED);
+ }
+ kqlock_held(kqwl); // to look at kq_queues
+ i = KQWL_BUCKET_STAYACTIVE;
+ if (TAILQ_EMPTY(&kqr->kqr_suppressed)) {
+ kqr->kqr_override_index = THREAD_QOS_UNSPECIFIED;
+ }
+ if (!TAILQ_EMPTY(&kqwl->kqwl_queue[i]) &&
+ (kqr->kqr_wakeup_indexes & KQWL_STAYACTIVE_FIRED_BIT)) {
+ /*
+ * If the KQWL_STAYACTIVE_FIRED_BIT is set, it means a stay active
+ * knote may have fired, so we need to merge in kqr_stayactive_qos.
+ *
+ * Unlike other buckets, this one is never empty but could be idle.
+ */
+ kqr->kqr_wakeup_indexes &= KQWL_STAYACTIVE_FIRED_BIT;
+ kqr->kqr_wakeup_indexes |= (1 << kqr->kqr_stayactive_qos);
+ } else {
+ kqr->kqr_wakeup_indexes = 0;
+ }
+ for (i = THREAD_QOS_UNSPECIFIED + 1; i < KQWL_BUCKET_STAYACTIVE; i++) {
+ if (!TAILQ_EMPTY(&kqwl->kqwl_queue[i])) {
+ kqr->kqr_wakeup_indexes |= (1 << i);
+ }
+ }
+ if (kqr->kqr_wakeup_indexes) {
+ kqr->kqr_state |= KQR_WAKEUP;
+ kqworkloop_request_fire_r2k_notification(kqwl);
+ } else {
+ kqr->kqr_state &= ~KQR_WAKEUP;
+ }
+ goto recompute;
+
+ case KQWL_UTQ_RESET_WAKEUP_OVERRIDE:
+ kqr->kqr_override_index = qos;
+ goto recompute;
+
+ case KQWL_UTQ_UPDATE_WAKEUP_OVERRIDE:
+ recompute:
+ /*
+ * When modifying the wakeup QoS or the override QoS, we always need to
+ * maintain our invariant that kqr_override_index is at least as large
+ * as the highest QoS for which an event is fired.
+ *
+ * However this override index can be larger when there is an overriden
+ * suppressed knote pushing on the kqueue.
+ */
+ if (kqr->kqr_wakeup_indexes > (1 << qos)) {
+ qos = fls(kqr->kqr_wakeup_indexes) - 1; /* fls is 1-based */
+ }
+ if (kqr->kqr_override_index < qos) {
+ kqr->kqr_override_index = qos;
+ }
+ break;
+
+ case KQWL_UTQ_REDRIVE_EVENTS:
+ break;
+
+ case KQWL_UTQ_SET_QOS_INDEX:
+ kqr->kqr_qos_index = qos;
+ break;
+
+ default:
+ panic("unknown kqwl thread qos update operation: %d", op);
+ }
+
+ thread_t kqwl_owner = kqwl->kqwl_owner;
+ thread_t servicer = kqr->kqr_thread;
+ boolean_t qos_changed = FALSE;
+ kq_index_t new_owner_override = kqworkloop_owner_override(kqwl);
+
+ /*
+ * Apply the diffs to the owner if applicable
+ */
+ if (kqwl_owner) {
+#if 0
+ /* JMM - need new trace hooks for owner overrides */
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQWL_THADJUST),
+ kqwl->kqwl_dynamicid, thread_tid(kqwl_owner), kqr->kqr_qos_index,
+ (kqr->kqr_override_index << 16) | kqr->kqr_state);
+#endif
+ if (new_owner_override == old_owner_override) {
+ // nothing to do
+ } else if (old_owner_override == THREAD_QOS_UNSPECIFIED) {
+ thread_add_ipc_override(kqwl_owner, new_owner_override);
+ } else if (new_owner_override == THREAD_QOS_UNSPECIFIED) {
+ thread_drop_ipc_override(kqwl_owner);
+ } else /* old_owner_override != new_owner_override */ {
+ thread_update_ipc_override(kqwl_owner, new_owner_override);
+ }
+ }
+
+ /*
+ * apply the diffs to the servicer
+ */
+ if ((kqr->kqr_state & KQR_THREQUESTED) == 0) {
+ /*
+ * No servicer, nor thread-request
+ *
+ * Make a new thread request, unless there is an owner (or the workloop
+ * is suspended in userland) or if there is no asynchronous work in the
+ * first place.
+ */
+
+ if (kqwl_owner == NULL && (kqr->kqr_state & KQR_WAKEUP)) {
+ int initiate_flags = 0;
+ if (op == KQWL_UTQ_UNBINDING) {
+ initiate_flags = WORKQ_THREADREQ_ATTEMPT_REBIND;
+ }
+ kqueue_threadreq_initiate(kq, kqr, new_owner_override,
+ initiate_flags);
+ }
+ } else if (servicer) {
+ /*
+ * Servicer in flight
+ *
+ * Just apply the diff to the servicer
+ */
+ struct uthread *ut = get_bsdthread_info(servicer);
+ if (ut->uu_kqueue_override != kqr->kqr_override_index) {
+ if (ut->uu_kqueue_override == THREAD_QOS_UNSPECIFIED) {
+ thread_add_ipc_override(servicer, kqr->kqr_override_index);
+ } else if (kqr->kqr_override_index == THREAD_QOS_UNSPECIFIED) {
+ thread_drop_ipc_override(servicer);
+ } else /* ut->uu_kqueue_override != kqr->kqr_override_index */ {
+ thread_update_ipc_override(servicer, kqr->kqr_override_index);
+ }
+ ut->uu_kqueue_override = kqr->kqr_override_index;
+ qos_changed = TRUE;
+ }
+ } else if (new_owner_override == THREAD_QOS_UNSPECIFIED) {
+ /*
+ * No events to deliver anymore.
+ *
+ * However canceling with turnstiles is challenging, so the fact that
+ * the request isn't useful will be discovered by the servicer himself
+ * later on.
+ */
+ } else if (old_owner_override != new_owner_override) {
+ /*
+ * Request is in flight
+ *
+ * Apply the diff to the thread request
+ */
+ kqueue_threadreq_modify(kq, kqr, new_owner_override);
+ qos_changed = TRUE;
+ }
+
+ if (qos_changed) {
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQWL_THADJUST), kqwl->kqwl_dynamicid,
+ thread_tid(kqr->kqr_thread), kqr->kqr_qos_index,
+ (kqr->kqr_override_index << 16) | kqr->kqr_state);
+ }
+}
+
+static void
+kqworkloop_request_help(struct kqworkloop *kqwl, kq_index_t qos_index)
+{
+ /* convert to thread qos value */
+ assert(qos_index < KQWL_NBUCKETS);
+
+ kq_req_lock(kqwl);
+ kqworkloop_update_threads_qos(kqwl, KQWL_UTQ_UPDATE_WAKEUP_QOS, qos_index);
+ kq_req_unlock(kqwl);
+}
+
+static struct kqtailq *
+kqueue_get_queue(struct kqueue *kq, kq_index_t qos_index)
+{
+ if (kq->kq_state & KQ_WORKQ) {
+ assert(qos_index < KQWQ_NBUCKETS);
+ } else if (kq->kq_state & KQ_WORKLOOP) {
+ assert(qos_index < KQWL_NBUCKETS);
+ } else {
+ assert(qos_index == QOS_INDEX_KQFILE);
+ }
+ static_assert(offsetof(struct kqueue, kq_queue) == sizeof(struct kqueue),
+ "struct kqueue::kq_queue must be exactly at the end");
+ return &kq->kq_queue[qos_index];
+}
+
+static int
+kqueue_queue_empty(struct kqueue *kq, kq_index_t qos_index)
+{
+ return TAILQ_EMPTY(kqueue_get_queue(kq, qos_index));
+}
+
+static struct kqtailq *
+kqueue_get_suppressed_queue(kqueue_t kq, struct knote *kn)
+{
+ if (kq.kq->kq_state & KQ_WORKQ) {
+ return &kqworkq_get_request(kq.kqwq, kn->kn_qos_index)->kqr_suppressed;
+ } else if (kq.kq->kq_state & KQ_WORKLOOP) {
+ return &kq.kqwl->kqwl_request.kqr_suppressed;
+ } else {
+ return &kq.kqf->kqf_suppressed;
+ }
+}
+
+static struct turnstile *
+kqueue_get_turnstile(kqueue_t kqu, bool can_alloc)
+{
+ uint8_t kqr_state;
+
+ if ((kqu.kq->kq_state & KQ_WORKLOOP) == 0) {
+ return TURNSTILE_NULL;
+ }
+
+ kqr_state = os_atomic_load(&kqu.kqwl->kqwl_request.kqr_state, relaxed);
+ if (kqr_state & KQR_ALLOCATED_TURNSTILE) {
+ /* force a dependency to pair with the atomic or with release below */
+ return os_atomic_load_with_dependency_on(&kqu.kqwl->kqwl_turnstile,
+ kqr_state);
+ }
+
+ if (!can_alloc) {
+ return TURNSTILE_NULL;
+ }
+
+ struct turnstile *ts = turnstile_alloc(), *free_ts = TURNSTILE_NULL;
+
+ kq_req_lock(kqu);
+ if (filt_wlturnstile_interlock_is_workq(kqu.kqwl)) {
+ workq_kern_threadreq_lock(kqu.kqwl->kqwl_p);
+ }
+
+ if (kqu.kqwl->kqwl_request.kqr_state & KQR_ALLOCATED_TURNSTILE) {
+ free_ts = ts;
+ ts = kqu.kqwl->kqwl_turnstile;
+ } else {
+ ts = turnstile_prepare((uintptr_t)kqu.kqwl, &kqu.kqwl->kqwl_turnstile,
+ ts, TURNSTILE_WORKLOOPS);
+
+ /* release-barrier to pair with the unlocked load of kqwl_turnstile above */
+ os_atomic_or(&kqu.kqwl->kqwl_request.kqr_state,
+ KQR_ALLOCATED_TURNSTILE, release);
+ }
+
+ if (filt_wlturnstile_interlock_is_workq(kqu.kqwl)) {
+ workq_kern_threadreq_unlock(kqu.kqwl->kqwl_p);
+ }
+ kq_req_unlock(kqu.kqwl);
+
+ if (free_ts) {
+ turnstile_deallocate(free_ts);
+ }
+ return ts;
+}
+
+struct turnstile *
+kqueue_turnstile(struct kqueue *kq)
+{
+ return kqueue_get_turnstile(kq, false);
+}
+
+struct turnstile *
+kqueue_alloc_turnstile(struct kqueue *kq)
+{
+ return kqueue_get_turnstile(kq, true);
+}
+
+static struct kqtailq *
+knote_get_queue(struct knote *kn)
+{
+ return kqueue_get_queue(knote_get_kq(kn), kn->kn_qos_index);
+}
+
+static void
+knote_reset_priority(struct knote *kn, pthread_priority_t pp)
+{
+ struct kqueue *kq = knote_get_kq(kn);
+ kq_index_t qos = _pthread_priority_thread_qos(pp);
+
+ assert((kn->kn_status & KN_QUEUED) == 0);
+
+ if (kq->kq_state & KQ_WORKQ) {
+ if (qos == THREAD_QOS_UNSPECIFIED) {
+ /* On workqueues, outside of QoS means MANAGER */
+ qos = KQWQ_QOS_MANAGER;
+ pp = _PTHREAD_PRIORITY_EVENT_MANAGER_FLAG;
+ } else {
+ pp = _pthread_priority_normalize(pp);
+ }
+ } else if (kq->kq_state & KQ_WORKLOOP) {
+ assert((pp & _PTHREAD_PRIORITY_EVENT_MANAGER_FLAG) == 0);
+ pp = _pthread_priority_normalize(pp);
+ } else {
+ pp = _pthread_unspecified_priority();
+ qos = THREAD_QOS_UNSPECIFIED;
+ }
+
+ kn->kn_qos = pp;
+ kn->kn_req_index = qos;
+
+ if ((kn->kn_status & KN_MERGE_QOS) == 0 || qos > kn->kn_qos_override) {
+ /* Never lower QoS when in "Merge" mode */
+ kn->kn_qos_override = qos;
+ }
+
+ /* only adjust in-use qos index when not suppressed */
+ if ((kn->kn_status & KN_SUPPRESSED) == 0) {
+ kn->kn_qos_index = qos;
+ } else if (kq->kq_state & KQ_WORKQ) {
+ kqworkq_update_override((struct kqworkq *)kq, kn, qos);
+ } else if (kq->kq_state & KQ_WORKLOOP) {
+ kqworkloop_update_override((struct kqworkloop *)kq, qos);
+ }
+}
+
+static void
+knote_set_qos_overcommit(struct knote *kn)
+{
+ struct kqueue *kq = knote_get_kq(kn);
+
+ /* turn overcommit on for the appropriate thread request? */
+ if ((kn->kn_qos & _PTHREAD_PRIORITY_OVERCOMMIT_FLAG) &&
+ (kq->kq_state & KQ_WORKLOOP)) {
+ struct kqworkloop *kqwl = (struct kqworkloop *)kq;
+ struct kqrequest *kqr = &kqwl->kqwl_request;
+
+ /*
+ * This test is racy, but since we never remove this bit,
+ * it allows us to avoid taking a lock.
+ */
+ if (kqr->kqr_state & KQR_THOVERCOMMIT) {
+ return;
+ }
+
+ kq_req_lock(kqwl);
+ kqr->kqr_state |= KQR_THOVERCOMMIT;
+ if (!kqr->kqr_thread && (kqr->kqr_state & KQR_THREQUESTED)) {
+ kqueue_threadreq_modify(kq, kqr, kqr->kqr_req.tr_qos);
+ }
+ kq_req_unlock(kqwl);
+ }
+}
+
+static kq_index_t
+knote_get_qos_override_index(struct knote *kn)
+{
+ return kn->kn_qos_override;
+}
+
+static void
+kqworkq_update_override(struct kqworkq *kqwq, struct knote *kn,
+ kq_index_t override_index)
+{
+ struct kqrequest *kqr;
+ kq_index_t old_override_index;
+ kq_index_t queue_index = kn->kn_qos_index;
+
+ if (override_index <= queue_index) {
+ return;
+ }
+
+ kqr = kqworkq_get_request(kqwq, queue_index);
+
+ kq_req_lock(kqwq);
+ old_override_index = kqr->kqr_override_index;
+ if (override_index > MAX(kqr->kqr_qos_index, old_override_index)) {
+ kqr->kqr_override_index = override_index;
+
+ /* apply the override to [incoming?] servicing thread */
+ if (kqr->kqr_thread) {
+ if (old_override_index)
+ thread_update_ipc_override(kqr->kqr_thread, override_index);
+ else
+ thread_add_ipc_override(kqr->kqr_thread, override_index);
+ }
+ }
+ kq_req_unlock(kqwq);
+}
+
+static void
+kqworkloop_update_override(struct kqworkloop *kqwl, kq_index_t override_index)
+{
+ kq_req_lock(kqwl);
+ kqworkloop_update_threads_qos(kqwl, KQWL_UTQ_UPDATE_WAKEUP_OVERRIDE,
+ override_index);
+ kq_req_unlock(kqwl);
+}
+
+static thread_qos_t
+kqworkloop_unbind_locked(struct kqworkloop *kqwl, thread_t thread)
+{
+ struct uthread *ut = get_bsdthread_info(thread);
+ struct kqrequest *kqr = &kqwl->kqwl_request;
+ kq_index_t ipc_override = ut->uu_kqueue_override;
+
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQWL_UNBIND), kqwl->kqwl_dynamicid,
+ thread_tid(thread), 0, 0);
+
+ kq_req_held(kqwl);
+ assert(ut->uu_kqr_bound == kqr);
+ ut->uu_kqr_bound = NULL;
+ ut->uu_kqueue_override = THREAD_QOS_UNSPECIFIED;
+
+ if (kqwl->kqwl_owner == NULL && kqwl->kqwl_turnstile) {
+ turnstile_update_inheritor(kqwl->kqwl_turnstile,
+ TURNSTILE_INHERITOR_NULL, TURNSTILE_IMMEDIATE_UPDATE);
+ turnstile_update_inheritor_complete(kqwl->kqwl_turnstile,
+ TURNSTILE_INTERLOCK_HELD);
+ }
+
+ kqr->kqr_thread = NULL;
+ kqr->kqr_state &= ~(KQR_THREQUESTED | KQR_R2K_NOTIF_ARMED);
+ return ipc_override;
+}
+
+/*
+ * kqworkloop_unbind - Unbind the servicer thread of a workloop kqueue
+ *
+ * It will acknowledge events, and possibly request a new thread if:
+ * - there were active events left
+ * - we pended waitq hook callouts during processing
+ * - we pended wakeups while processing (or unsuppressing)
+ *
+ * Called with kqueue lock held.
+ */
+static void
+kqworkloop_unbind(proc_t p, struct kqworkloop *kqwl)
+{
+ struct kqueue *kq = &kqwl->kqwl_kqueue;
+ struct kqrequest *kqr = &kqwl->kqwl_request;
+ thread_t thread = kqr->kqr_thread;
+ int op = KQWL_UTQ_PARKING;
+ kq_index_t ipc_override, qos_override = THREAD_QOS_UNSPECIFIED;
+
+ assert(thread == current_thread());
+
+ kqlock(kqwl);
+
+ /*
+ * Forcing the KQ_PROCESSING flag allows for QoS updates because of
+ * unsuppressing knotes not to be applied until the eventual call to
+ * kqworkloop_update_threads_qos() below.
+ */
+ assert((kq->kq_state & KQ_PROCESSING) == 0);
+ if (!TAILQ_EMPTY(&kqr->kqr_suppressed)) {
+ kq->kq_state |= KQ_PROCESSING;
+ qos_override = kqworkloop_acknowledge_events(kqwl);
+ kq->kq_state &= ~KQ_PROCESSING;
+ }
+
+ kq_req_lock(kqwl);
+
+ ipc_override = kqworkloop_unbind_locked(kqwl, thread);
+ kqworkloop_update_threads_qos(kqwl, op, qos_override);
+
+ kq_req_unlock(kqwl);
+
+ kqunlock(kqwl);
+
+ /*
+ * Drop the override on the current thread last, after the call to
+ * kqworkloop_update_threads_qos above.
+ */
+ if (ipc_override) {
+ thread_drop_ipc_override(thread);
+ }
+
+ /* If last reference, dealloc the workloop kq */
+ kqueue_release_last(p, kqwl);
+}
+
+static thread_qos_t
+kqworkq_unbind_locked(__assert_only struct kqworkq *kqwq,
+ struct kqrequest *kqr, thread_t thread)
+{
+ struct uthread *ut = get_bsdthread_info(thread);
+ kq_index_t old_override = kqr->kqr_override_index;
+
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KQWQ_UNBIND), -1,
+ thread_tid(kqr->kqr_thread), kqr->kqr_qos_index, 0);
+
+ kq_req_held(kqwq);
+ assert(ut->uu_kqr_bound == kqr);
+ ut->uu_kqr_bound = NULL;
+ kqr->kqr_thread = NULL;
+ kqr->kqr_state &= ~(KQR_THREQUESTED | KQR_R2K_NOTIF_ARMED);
+ kqr->kqr_override_index = THREAD_QOS_UNSPECIFIED;
+
+ return old_override;
+}
+
+/*
+ * kqworkq_unbind - unbind of a workq kqueue from a thread
+ *
+ * We may have to request new threads.
+ * This can happen there are no waiting processing threads and:
+ * - there were active events we never got to (count > 0)
+ * - we pended waitq hook callouts during processing
+ * - we pended wakeups while processing (or unsuppressing)
+ */
+static void
+kqworkq_unbind(proc_t p, struct kqrequest *kqr)
+{
+ struct kqworkq *kqwq = (struct kqworkq *)p->p_fd->fd_wqkqueue;
+ __assert_only int rc;
+
+ kqlock(kqwq);
+ rc = kqworkq_acknowledge_events(kqwq, kqr, 0, KQWQAE_UNBIND);
+ assert(rc == -1);
+ kqunlock(kqwq);
+}
+
+struct kqrequest *
+kqworkq_get_request(struct kqworkq *kqwq, kq_index_t qos_index)
+{
+ assert(qos_index < KQWQ_NBUCKETS);
+ return &kqwq->kqwq_request[qos_index];
+}
+
+static void
+knote_apply_qos_override(struct knote *kn, kq_index_t qos_index)
+{
+ assert((kn->kn_status & KN_QUEUED) == 0);
+
+ kn->kn_qos_override = qos_index;
+
+ if (kn->kn_status & KN_SUPPRESSED) {
+ struct kqueue *kq = knote_get_kq(kn);
+ /*
+ * For suppressed events, the kn_qos_index field cannot be touched as it
+ * allows us to know on which supress queue the knote is for a kqworkq.
+ *
+ * Also, there's no natural push applied on the kqueues when this field
+ * changes anyway. We hence need to apply manual overrides in this case,
+ * which will be cleared when the events are later acknowledged.
+ */
+ if (kq->kq_state & KQ_WORKQ) {
+ kqworkq_update_override((struct kqworkq *)kq, kn, qos_index);
+ } else {
+ kqworkloop_update_override((struct kqworkloop *)kq, qos_index);
+ }
+ } else {
+ kn->kn_qos_index = qos_index;
+ }
+}
+
+static bool
+knote_should_apply_qos_override(struct kqueue *kq, struct knote *kn, int result,
+ thread_qos_t *qos_out)
+{
+ thread_qos_t qos_index = (result >> FILTER_ADJUST_EVENT_QOS_SHIFT) & 7;
+
+ kqlock_held(kq);
+
+ assert(result & FILTER_ADJUST_EVENT_QOS_BIT);
+ assert(qos_index < THREAD_QOS_LAST);
+
+ /*
+ * Early exit for knotes that should not change QoS
+ *
+ * It is safe to test kn_req_index against MANAGER / STAYACTIVE because
+ * knotes with such kn_req_index values never change for their entire
+ * lifetime.
+ */
+ if (__improbable(!knote_fops(kn)->f_adjusts_qos)) {
+ panic("filter %d cannot change QoS", kn->kn_filtid);
+ } else if (kq->kq_state & KQ_WORKLOOP) {
+ if (kn->kn_req_index == KQWL_BUCKET_STAYACTIVE) {
+ return false;
+ }
+ } else if (kq->kq_state & KQ_WORKQ) {
+ if (kn->kn_req_index == KQWQ_QOS_MANAGER) {
+ return false;
+ }
+ } else {
+ return false;
+ }
+
+ /*
+ * knotes with the FALLBACK flag will only use their registration QoS if the
+ * incoming event has no QoS, else, the registration QoS acts as a floor.
+ */
+ if (kn->kn_qos & _PTHREAD_PRIORITY_FALLBACK_FLAG) {
+ if (qos_index == THREAD_QOS_UNSPECIFIED)
+ qos_index = kn->kn_req_index;
+ } else {
+ if (qos_index < kn->kn_req_index)
+ qos_index = kn->kn_req_index;
+ }
+ if ((kn->kn_status & KN_MERGE_QOS) && (qos_index < kn->kn_qos_override)) {
+ /* Never lower QoS when in "Merge" mode */
+ return false;
+ }
+
+ if ((kn->kn_status & KN_LOCKED) && kn->kn_inuse) {
+ /*
+ * When we're trying to update the QoS override and that both an
+ * f_event() and other f_* calls are running concurrently, any of these
+ * in flight calls may want to perform overrides that aren't properly
+ * serialized with each other.
+ *
+ * The first update that observes this racy situation enters a "Merge"
+ * mode which causes subsequent override requests to saturate the
+ * override instead of replacing its value.
+ *
+ * This mode is left when knote_unlock() or knote_call_filter_event()
+ * observe that no other f_* routine is in flight.
+ */
+ kn->kn_status |= KN_MERGE_QOS;
+ }
+
+ if (kn->kn_qos_override == qos_index) {
+ return false;
+ }
+
+ *qos_out = qos_index;
+ return true;
+}
+
+static void
+knote_adjust_qos(struct kqueue *kq, struct knote *kn, int result)
+{
+ thread_qos_t qos;
+ if (knote_should_apply_qos_override(kq, kn, result, &qos)) {
+ knote_dequeue(kn);
+ knote_apply_qos_override(kn, qos);
+ if (knote_enqueue(kn) && (kn->kn_status & KN_ACTIVE)) {
+ knote_wakeup(kn);
+ }
+ }
+}
+
+static void
+knote_wakeup(struct knote *kn)
+{
+ struct kqueue *kq = knote_get_kq(kn);
+
+ kqlock_held(kq);
+
+ if (kq->kq_state & KQ_WORKQ) {
+ struct kqworkq *kqwq = (struct kqworkq *)kq;
+
+ kqworkq_request_help(kqwq, kn->kn_qos_index);
+ } else if (kq->kq_state & KQ_WORKLOOP) {
+ struct kqworkloop *kqwl = (struct kqworkloop *)kq;
+
+ /*
+ * kqworkloop_end_processing() will perform the required QoS
+ * computations when it unsets the processing mode.
+ */
+ if (!kqworkloop_is_processing_on_current_thread(kqwl)) {
+ kqworkloop_request_help(kqwl, kn->kn_qos_index);
+ }
+ } else {
+ struct kqfile *kqf = (struct kqfile *)kq;
+
+ /* flag wakeups during processing */
+ if (kq->kq_state & KQ_PROCESSING)
+ kq->kq_state |= KQ_WAKEUP;
+
+ /* wakeup a thread waiting on this queue */
+ if (kq->kq_state & (KQ_SLEEP | KQ_SEL)) {
+ kq->kq_state &= ~(KQ_SLEEP | KQ_SEL);
+ waitq_wakeup64_all((struct waitq *)&kq->kq_wqs, KQ_EVENT,
+ THREAD_AWAKENED, WAITQ_ALL_PRIORITIES);
+ }
+
+ /* wakeup other kqueues/select sets we're inside */
+ KNOTE(&kqf->kqf_sel.si_note, 0);
+ }
+}
+
+/*
+ * Called with the kqueue locked
+ */
+static void
+kqueue_interrupt(struct kqueue *kq)
+{
+ assert((kq->kq_state & KQ_WORKQ) == 0);
+
+ /* wakeup sleeping threads */
+ if ((kq->kq_state & (KQ_SLEEP | KQ_SEL)) != 0) {
+ kq->kq_state &= ~(KQ_SLEEP | KQ_SEL);
+ (void)waitq_wakeup64_all((struct waitq *)&kq->kq_wqs,
+ KQ_EVENT,
+ THREAD_RESTART,
+ WAITQ_ALL_PRIORITIES);
+ }
+
+ /* wakeup threads waiting their turn to process */
+ if (kq->kq_state & KQ_PROCWAIT) {
+ struct kqtailq *suppressq;
+
+ assert(kq->kq_state & KQ_PROCESSING);
+
+ kq->kq_state &= ~KQ_PROCWAIT;
+ suppressq = kqueue_get_suppressed_queue(kq, NULL);
+ (void)waitq_wakeup64_all((struct waitq *)&kq->kq_wqs,
+ CAST_EVENT64_T(suppressq),
+ THREAD_RESTART,
+ WAITQ_ALL_PRIORITIES);
+ }
+}
+
+/*
+ * Called back from waitq code when no threads waiting and the hook was set.
+ *
+ * Interrupts are likely disabled and spin locks are held - minimal work
+ * can be done in this context!!!
+ *
+ * JMM - in the future, this will try to determine which knotes match the
+ * wait queue wakeup and apply these wakeups against those knotes themselves.
+ * For now, all the events dispatched this way are dispatch-manager handled,
+ * so hard-code that for now.
+ */
+void
+waitq_set__CALLING_PREPOST_HOOK__(void *kq_hook, void *knote_hook, int qos)
+{
+#pragma unused(knote_hook, qos)
+
+ struct kqueue *kq = (struct kqueue *)kq_hook;
+
+ if (kq->kq_state & KQ_WORKQ) {
+ struct kqworkq *kqwq = (struct kqworkq *)kq;
+
+ kqworkq_request_help(kqwq, KQWQ_QOS_MANAGER);
+ } else if (kq->kq_state & KQ_WORKLOOP) {
+ struct kqworkloop *kqwl = (struct kqworkloop *)kq;
+
+ kqworkloop_request_help(kqwl, KQWL_BUCKET_STAYACTIVE);
+ }
+}
+
+void
+klist_init(struct klist *list)
+{
+ SLIST_INIT(list);
+}
+
+
+/*
+ * Query/Post each knote in the object's list
+ *
+ * The object lock protects the list. It is assumed
+ * that the filter/event routine for the object can
+ * determine that the object is already locked (via
+ * the hint) and not deadlock itself.
+ *
+ * The object lock should also hold off pending
+ * detach/drop operations.
+ */
+void
+knote(struct klist *list, long hint)
+{
+ struct knote *kn;
+
+ SLIST_FOREACH(kn, list, kn_selnext) {
+ struct kqueue *kq = knote_get_kq(kn);
+ kqlock(kq);
+ knote_call_filter_event(kq, kn, hint);
+ kqunlock(kq);
+ }
+}
+
+/*
+ * attach a knote to the specified list. Return true if this is the first entry.
+ * The list is protected by whatever lock the object it is associated with uses.
+ */
+int
+knote_attach(struct klist *list, struct knote *kn)
+{
+ int ret = SLIST_EMPTY(list);
+ SLIST_INSERT_HEAD(list, kn, kn_selnext);
+ return (ret);
+}
+
+/*
+ * detach a knote from the specified list. Return true if that was the last entry.
+ * The list is protected by whatever lock the object it is associated with uses.
+ */
+int
+knote_detach(struct klist *list, struct knote *kn)
+{
+ SLIST_REMOVE(list, kn, knote, kn_selnext);
+ return (SLIST_EMPTY(list));
+}
+
+/*
+ * knote_vanish - Indicate that the source has vanished
+ *
+ * If the knote has requested EV_VANISHED delivery,
+ * arrange for that. Otherwise, deliver a NOTE_REVOKE
+ * event for backward compatibility.
+ *
+ * The knote is marked as having vanished, but is not
+ * actually detached from the source in this instance.
+ * The actual detach is deferred until the knote drop.
+ *
+ * Our caller already has the object lock held. Calling
+ * the detach routine would try to take that lock
+ * recursively - which likely is not supported.
+ */
+void
+knote_vanish(struct klist *list)
+{
+ struct knote *kn;
+ struct knote *kn_next;
+
+ SLIST_FOREACH_SAFE(kn, list, kn_selnext, kn_next) {
+ struct kqueue *kq = knote_get_kq(kn);
+
+ kqlock(kq);
+ if (kn->kn_status & KN_REQVANISH) {
+ /* If EV_VANISH supported - prepare to deliver one */
+ kn->kn_status |= KN_VANISHED;
+ knote_activate(kn);
+ } else {
+ knote_call_filter_event(kq, kn, NOTE_REVOKE);
+ }
+ kqunlock(kq);
+ }
+}
+
+/*
+ * Force a lazy allocation of the waitqset link
+ * of the kq_wqs associated with the kn
+ * if it wasn't already allocated.
+ *
+ * This allows knote_link_waitq to never block
+ * if reserved_link is not NULL.
+ */
+void
+knote_link_waitqset_lazy_alloc(struct knote *kn)
+{
+ struct kqueue *kq = knote_get_kq(kn);
+ waitq_set_lazy_init_link(&kq->kq_wqs);
+}
+
+/*
+ * Check if a lazy allocation for the waitqset link
+ * of the kq_wqs is needed.
+ */
+boolean_t
+knote_link_waitqset_should_lazy_alloc(struct knote *kn)
+{
+ struct kqueue *kq = knote_get_kq(kn);
+ return waitq_set_should_lazy_init_link(&kq->kq_wqs);
+}
+
+/*
+ * 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
+ * the knote to the active list at wakeup (nothing calls knote()). Instead,
+ * we permanently enqueue them here.
+ *
+ * kqueue and knote references are held by caller.
+ * waitq locked by caller.
+ *
+ * caller provides the wait queue link structure and insures that the kq->kq_wqs
+ * is linked by previously calling knote_link_waitqset_lazy_alloc.
+ */
+int
+knote_link_waitq(struct knote *kn, struct waitq *wq, uint64_t *reserved_link)
+{
+ struct kqueue *kq = knote_get_kq(kn);
+ kern_return_t kr;
+
+ kr = waitq_link(wq, &kq->kq_wqs, WAITQ_ALREADY_LOCKED, reserved_link);
+ if (kr == KERN_SUCCESS) {
+ knote_markstayactive(kn);
+ return (0);
+ } else {
+ return (EINVAL);
+ }
+}
+
+/*
+ * Unlink the provided wait queue from the kqueue associated with a knote.
+ * Also remove it from the magic list of directly attached knotes.
+ *
+ * Note that the unlink may have already happened from the other side, so
+ * ignore any failures to unlink and just remove it from the kqueue list.
+ *
+ * On success, caller is responsible for the link structure
+ */
+int
+knote_unlink_waitq(struct knote *kn, struct waitq *wq)
+{
+ struct kqueue *kq = knote_get_kq(kn);
+ kern_return_t kr;
+
+ kr = waitq_unlink(wq, &kq->kq_wqs);
+ knote_clearstayactive(kn);
+ return ((kr != KERN_SUCCESS) ? EINVAL : 0);
+}
+
+/*
+ * remove all knotes referencing a specified fd
+ *
+ * Entered with the proc_fd lock already held.
+ * It returns the same way, but may drop it temporarily.
+ */
+void
+knote_fdclose(struct proc *p, int fd)
+{
+ struct klist *list;
+ struct knote *kn;
+ KNOTE_LOCK_CTX(knlc);
+
+restart:
+ list = &p->p_fd->fd_knlist[fd];
+ SLIST_FOREACH(kn, list, kn_link) {
+ struct kqueue *kq = knote_get_kq(kn);
+
+ kqlock(kq);
+
+ if (kq->kq_p != p)
+ panic("%s: proc mismatch (kq->kq_p=%p != p=%p)",
+ __func__, kq->kq_p, p);
+
+ /*
+ * If the knote supports EV_VANISHED delivery,
+ * transition it to vanished mode (or skip over
+ * it if already vanished).
+ */
+ if (kn->kn_status & KN_VANISHED) {
+ kqunlock(kq);
+ continue;
+ }
+
+ proc_fdunlock(p);
+ if (!knote_lock(kq, kn, &knlc, KNOTE_KQ_LOCK_ON_SUCCESS)) {
+ /* the knote was dropped by someone, nothing to do */
+ } else if (kn->kn_status & KN_REQVANISH) {
+ kn->kn_status |= KN_VANISHED;
+ kn->kn_status &= ~KN_ATTACHED;
+
+ kqunlock(kq);
+ knote_fops(kn)->f_detach(kn);
+ if (knote_fops(kn)->f_isfd)
+ fp_drop(p, kn->kn_id, kn->kn_fp, 0);
+ kqlock(kq);
+
+ knote_activate(kn);
+ knote_unlock(kq, kn, &knlc, KNOTE_KQ_UNLOCK);
+ } else {
+ knote_drop(kq, kn, &knlc);
+ }
+
+ proc_fdlock(p);
+ goto restart;
+ }
+}
+
+/*
+ * knote_fdfind - lookup a knote in the fd table for process
+ *
+ * If the filter is file-based, lookup based on fd index.
+ * Otherwise use a hash based on the ident.
+ *
+ * Matching is based on kq, filter, and ident. Optionally,
+ * it may also be based on the udata field in the kevent -
+ * allowing multiple event registration for the file object
+ * per kqueue.
+ *
+ * fd_knhashlock or fdlock held on entry (and exit)
+ */
+static struct knote *
+knote_fdfind(struct kqueue *kq,
+ struct kevent_internal_s *kev,
+ bool is_fd,
+ struct proc *p)
+{
+ struct filedesc *fdp = p->p_fd;
+ struct klist *list = NULL;
+ struct knote *kn = NULL;
+
+ /*
+ * determine where to look for the knote
+ */
+ if (is_fd) {
+ /* fd-based knotes are linked off the fd table */
+ if (kev->ident < (u_int)fdp->fd_knlistsize) {
+ list = &fdp->fd_knlist[kev->ident];
+ }
+ } else if (fdp->fd_knhashmask != 0) {
+ /* hash non-fd knotes here too */
+ list = &fdp->fd_knhash[KN_HASH((u_long)kev->ident, fdp->fd_knhashmask)];
+ }
+
+ /*
+ * scan the selected list looking for a match
+ */
+ if (list != NULL) {
+ SLIST_FOREACH(kn, list, kn_link) {
+ if (kq == knote_get_kq(kn) &&
+ kev->ident == kn->kn_id &&
+ kev->filter == kn->kn_filter) {
+ if (kev->flags & EV_UDATA_SPECIFIC) {
+ if ((kn->kn_status & KN_UDATA_SPECIFIC) &&
+ kev->udata == kn->kn_udata) {
+ break; /* matching udata-specific knote */
+ }
+ } else if ((kn->kn_status & KN_UDATA_SPECIFIC) == 0) {
+ break; /* matching non-udata-specific knote */
+ }
+ }
+ }
+ }
+ return kn;
+}
+
+/*
+ * kq_add_knote- Add knote to the fd table for process
+ * while checking for duplicates.
+ *
+ * All file-based filters associate a list of knotes by file
+ * descriptor index. All other filters hash the knote by ident.
+ *
+ * May have to grow the table of knote lists to cover the
+ * file descriptor index presented.
+ *
+ * fd_knhashlock and fdlock unheld on entry (and exit).
+ *
+ * Takes a rwlock boost if inserting the knote is successful.
+ */
+static int
+kq_add_knote(struct kqueue *kq, struct knote *kn, struct knote_lock_ctx *knlc,
+ struct proc *p)
+{
+ struct filedesc *fdp = p->p_fd;
+ struct klist *list = NULL;
+ int ret = 0;
+ bool is_fd = knote_fops(kn)->f_isfd;
+
+ if (is_fd)
+ proc_fdlock(p);
+ else
+ knhash_lock(p);
+
+ if (knote_fdfind(kq, &kn->kn_kevent, is_fd, p) != NULL) {
+ /* found an existing knote: we can't add this one */
+ ret = ERESTART;
+ goto out_locked;
+ }
+
+ /* knote was not found: add it now */
+ if (!is_fd) {
+ if (fdp->fd_knhashmask == 0) {
+ u_long size = 0;
+
+ list = hashinit(CONFIG_KN_HASHSIZE, M_KQUEUE, &size);
+ if (list == NULL) {
+ ret = ENOMEM;
+ goto out_locked;
+ }
+
+ fdp->fd_knhash = list;
+ fdp->fd_knhashmask = size;
+ }
+
+ list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
+ SLIST_INSERT_HEAD(list, kn, kn_link);
+ ret = 0;
+ goto out_locked;
+
+ } else {
+ /* knote is fd based */
+
+ 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
+ || kn->kn_id >= (uint64_t)maxfiles) {
+ ret = EINVAL;
+ goto out_locked;
+ }
+ /* have to grow the fd_knlist */
+ size = fdp->fd_knlistsize;
+ while (size <= kn->kn_id)
+ size += KQEXTENT;
+
+ if (size >= (UINT_MAX/sizeof(struct klist *))) {
+ ret = EINVAL;
+ goto out_locked;
+ }
+
+ MALLOC(list, struct klist *,
+ size * sizeof(struct klist *), M_KQUEUE, M_WAITOK);
+ if (list == NULL) {
+ ret = ENOMEM;
+ goto out_locked;
+ }
+
+ bcopy((caddr_t)fdp->fd_knlist, (caddr_t)list,
+ fdp->fd_knlistsize * sizeof(struct klist *));
+ bzero((caddr_t)list +
+ 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;
+ }
+
+ list = &fdp->fd_knlist[kn->kn_id];
+ SLIST_INSERT_HEAD(list, kn, kn_link);
+ ret = 0;
+ goto out_locked;
+
+ }
+
+out_locked:
+ if (ret == 0) {
+ kqlock(kq);
+ assert((kn->kn_status & KN_LOCKED) == 0);
+ (void)knote_lock(kq, kn, knlc, KNOTE_KQ_UNLOCK);
+ }
+ if (is_fd)
+ proc_fdunlock(p);
+ else
+ knhash_unlock(p);
+
+ return ret;
+}
+
+/*
+ * kq_remove_knote - remove a knote from the fd table for process
+ *
+ * If the filter is file-based, remove based on fd index.
+ * Otherwise remove from the hash based on the ident.
+ *
+ * fd_knhashlock and fdlock unheld on entry (and exit).
+ */
+static void
+kq_remove_knote(struct kqueue *kq, struct knote *kn, struct proc *p,
+ struct knote_lock_ctx *knlc)
+{
+ struct filedesc *fdp = p->p_fd;
+ struct klist *list = NULL;
+ uint16_t kq_state;
+ bool is_fd;
+
+ is_fd = knote_fops(kn)->f_isfd;
+
+ if (is_fd)
+ proc_fdlock(p);
+ else
+ knhash_lock(p);
+
+ if (is_fd) {
+ assert ((u_int)fdp->fd_knlistsize > kn->kn_id);
+ list = &fdp->fd_knlist[kn->kn_id];
+ } else {
+ list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
+ }
+ SLIST_REMOVE(list, kn, knote, kn_link);
+
+ kqlock(kq);
+ kq_state = kq->kq_state;
+ if (knlc) {
+ knote_unlock_cancel(kq, kn, knlc, KNOTE_KQ_UNLOCK);
+ } else {
+ kqunlock(kq);
+ }
+ if (is_fd)
+ proc_fdunlock(p);
+ else
+ knhash_unlock(p);
+
+ if (kq_state & KQ_DYNAMIC)
+ kqueue_release_last(p, kq);
+}
+
+/*
+ * kq_find_knote_and_kq_lock - lookup a knote in the fd table for process
+ * and, if the knote is found, acquires the kqlock while holding the fd table lock/spinlock.
+ *
+ * fd_knhashlock or fdlock unheld on entry (and exit)
+ */
+
+static struct knote *
+kq_find_knote_and_kq_lock(struct kqueue *kq, struct kevent_internal_s *kev,
+ bool is_fd, struct proc *p)
+{
+ struct knote * ret;
+
+ if (is_fd)
+ proc_fdlock(p);
+ else
+ knhash_lock(p);
+
+ ret = knote_fdfind(kq, kev, is_fd, p);
+
+ if (ret) {
+ kqlock(kq);
+ }
+
+ if (is_fd)
+ proc_fdunlock(p);
+ else
+ knhash_unlock(p);
+
+ return ret;
+}
+/*
+ * knote_drop - disconnect and drop the knote
+ *
+ * Called with the kqueue locked, returns with the kqueue unlocked.
+ *
+ * If a knote locking context is passed, it is canceled.
+ *
+ * The knote may have already been detached from
+ * (or not yet attached to) its source object.
+ */
+static void
+knote_drop(struct kqueue *kq, struct knote *kn, struct knote_lock_ctx *knlc)
+{
+ struct proc *p = kq->kq_p;
+
+ kqlock_held(kq);
+
+ assert((kn->kn_status & KN_DROPPING) == 0);
+ if (knlc == NULL) {
+ assert((kn->kn_status & KN_LOCKED) == 0);
+ }
+ kn->kn_status |= KN_DROPPING;
+
+ knote_unsuppress(kn);
+ knote_dequeue(kn);
+ knote_wait_for_filter_events(kq, kn);
+
+ /* If we are attached, disconnect from the source first */
+ if (kn->kn_status & KN_ATTACHED) {
+ knote_fops(kn)->f_detach(kn);
+ }
+
+ /* kq may be freed when kq_remove_knote() returns */
+ kq_remove_knote(kq, kn, p, knlc);
+ if (knote_fops(kn)->f_isfd && ((kn->kn_status & KN_VANISHED) == 0))
+ fp_drop(p, kn->kn_id, kn->kn_fp, 0);
+
+ knote_free(kn);
+}
+
+/* called with kqueue lock held */
+static void
+knote_activate(struct knote *kn)
+{
+ if (kn->kn_status & KN_ACTIVE)
+ return;
+
+ KDBG_FILTERED(KEV_EVTID(BSD_KEVENT_KNOTE_ACTIVATE),
+ kn->kn_udata, kn->kn_status | (kn->kn_id << 32),
+ kn->kn_filtid);
+
+ kn->kn_status |= KN_ACTIVE;
+ if (knote_enqueue(kn))
+ knote_wakeup(kn);
+}
+
+/* called with kqueue lock held */
+static void
+knote_deactivate(struct knote *kn)
+{
+ kn->kn_status &= ~KN_ACTIVE;
+ if ((kn->kn_status & KN_STAYACTIVE) == 0)
+ knote_dequeue(kn);
+}
+
+/* called with kqueue lock held */
+static void
+knote_enable(struct knote *kn)
+{
+ if ((kn->kn_status & KN_DISABLED) == 0)
+ return;
+
+ kn->kn_status &= ~KN_DISABLED;
+
+ if (kn->kn_status & KN_SUPPRESSED) {
+ /*
+ * it is possible for userland to have knotes registered for a given
+ * workloop `wl_orig` but really handled on another workloop `wl_new`.
+ *
+ * In that case, rearming will happen from the servicer thread of
+ * `wl_new` which if `wl_orig` is no longer being serviced, would cause
+ * this knote to stay suppressed forever if we only relied on
+ * kqworkloop_acknowledge_events to be called by `wl_orig`.
+ *
+ * However if we see the KQ_PROCESSING bit on `wl_orig` set, we can't
+ * unsuppress because that would mess with the processing phase of
+ * `wl_orig`, however it also means kqworkloop_acknowledge_events()
+ * will be called.
+ */
+ struct kqueue *kq = knote_get_kq(kn);
+ if ((kq->kq_state & KQ_PROCESSING) == 0) {
+ knote_unsuppress(kn);
+ }
+ } else if (knote_enqueue(kn)) {
+ knote_wakeup(kn);
+ }
+}
+
+/* called with kqueue lock held */
+static void
+knote_disable(struct knote *kn)
+{
+ if (kn->kn_status & KN_DISABLED)
+ return;
+
+ kn->kn_status |= KN_DISABLED;
+ knote_dequeue(kn);
+}
+
+/* called with kqueue lock held */
+static void
+knote_suppress(struct knote *kn)
+{
+ struct kqtailq *suppressq;
+ struct kqueue *kq = knote_get_kq(kn);
+
+ kqlock_held(kq);
+
+ if (kn->kn_status & KN_SUPPRESSED)
+ return;
+
+ knote_dequeue(kn);
+ kn->kn_status |= KN_SUPPRESSED;
+ suppressq = kqueue_get_suppressed_queue(kq, kn);
+ TAILQ_INSERT_TAIL(suppressq, kn, kn_tqe);
+}
+
+/* called with kqueue lock held */
+static void
+knote_unsuppress(struct knote *kn)
+{
+ struct kqtailq *suppressq;
+ struct kqueue *kq = knote_get_kq(kn);
+
+ kqlock_held(kq);
+
+ if ((kn->kn_status & KN_SUPPRESSED) == 0)
+ return;
+
+ kn->kn_status &= ~KN_SUPPRESSED;
+ suppressq = kqueue_get_suppressed_queue(kq, kn);
+ TAILQ_REMOVE(suppressq, kn, kn_tqe);
+
+ /*
+ * If the knote is no longer active, reset its push,
+ * and resynchronize kn_qos_index with kn_qos_override
+ */
+ if ((kn->kn_status & KN_ACTIVE) == 0) {
+ kn->kn_qos_override = kn->kn_req_index;
+ }
+ kn->kn_qos_index = kn->kn_qos_override;
+
+ /* don't wakeup if unsuppressing just a stay-active knote */
+ if (knote_enqueue(kn) && (kn->kn_status & KN_ACTIVE)) {
+ knote_wakeup(kn);
+ }
+
+ if ((kq->kq_state & KQ_WORKLOOP) && TAILQ_EMPTY(suppressq)) {
+ struct kqworkloop *kqwl = (struct kqworkloop *)kq;
+
+ if (kqworkloop_is_processing_on_current_thread(kqwl)) {
+ /*
+ * kqworkloop_end_processing() or kqworkloop_begin_processing()
+ * will perform the required QoS computations when it unsets the
+ * processing mode.
+ */
+ } else {
+ kq_req_lock(kqwl);
+ kqworkloop_update_threads_qos(kqwl, KQWL_UTQ_RESET_WAKEUP_OVERRIDE, 0);
+ kq_req_unlock(kqwl);
+ }
+ }
+}
+
+/* called with kqueue lock held */
+static int
+knote_enqueue(struct knote *kn)
+{
+ if ((kn->kn_status & (KN_ACTIVE | KN_STAYACTIVE)) == 0 ||
+ (kn->kn_status & (KN_DISABLED | KN_SUPPRESSED | KN_DROPPING)))
+ return 0;
+
+ if ((kn->kn_status & KN_QUEUED) == 0) {
+ struct kqtailq *queue = knote_get_queue(kn);
+ struct kqueue *kq = knote_get_kq(kn);
+
+ kqlock_held(kq);
+ TAILQ_INSERT_TAIL(queue, kn, kn_tqe);
+ kn->kn_status |= KN_QUEUED;
+ kq->kq_count++;
+ return 1;
+ }
+ return ((kn->kn_status & KN_STAYACTIVE) != 0);
+}
+
+
+/* called with kqueue lock held */
+static void
+knote_dequeue(struct knote *kn)
+{
+ struct kqueue *kq = knote_get_kq(kn);
+ struct kqtailq *queue;
+
+ kqlock_held(kq);
+
+ if ((kn->kn_status & KN_QUEUED) == 0)
+ return;
+
+ queue = knote_get_queue(kn);
+ TAILQ_REMOVE(queue, kn, kn_tqe);
+ kn->kn_status &= ~KN_QUEUED;
+ kq->kq_count--;
+}
+
+void
+knote_init(void)
+{
+ knote_zone = zinit(sizeof(struct knote), 8192*sizeof(struct knote),
+ 8192, "knote zone");
+
+ kqfile_zone = zinit(sizeof(struct kqfile), 8192*sizeof(struct kqfile),
+ 8192, "kqueue file zone");
+
+ kqworkq_zone = zinit(sizeof(struct kqworkq), 8192*sizeof(struct kqworkq),
+ 8192, "kqueue workq zone");
+
+ kqworkloop_zone = zinit(sizeof(struct kqworkloop), 8192*sizeof(struct kqworkloop),
+ 8192, "kqueue workloop zone");
+
+ /* allocate kq lock group attribute and group */
+ kq_lck_grp_attr = lck_grp_attr_alloc_init();
+
+ kq_lck_grp = lck_grp_alloc_init("kqueue", kq_lck_grp_attr);
+
+ /* Allocate kq lock attribute */
+ kq_lck_attr = lck_attr_alloc_init();
+
+#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)
+
+const struct filterops *
+knote_fops(struct knote *kn)
+{
+ return sysfilt_ops[kn->kn_filtid];
+}
+
+static struct knote *
+knote_alloc(void)
+{
+ struct knote *kn = ((struct knote *)zalloc(knote_zone));
+ bzero(kn, sizeof(struct knote));
+ return kn;
+}
+
+static void
+knote_free(struct knote *kn)
+{
+ assert(kn->kn_inuse == 0);
+ assert((kn->kn_status & KN_LOCKED) == 0);
+ zfree(knote_zone, kn);
+}
+
+#if SOCKETS
+#include <sys/param.h>
+#include <sys/socket.h>
+#include <sys/protosw.h>
+#include <sys/domain.h>
+#include <sys/mbuf.h>
+#include <sys/kern_event.h>
+#include <sys/malloc.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_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,
+};
+
+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 flags)
+{
+#pragma unused(flags)
+ 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);