]> git.saurik.com Git - apple/xnu.git/blobdiff - osfmk/kern/sync_sema.c
xnu-3789.51.2.tar.gz
[apple/xnu.git] / osfmk / kern / sync_sema.c
index dc22aaa4e5fab698e1087fb08af48344a3fed46b..7f0fca49394dc3234c440afd9ae3c2b7828c0328 100644 (file)
@@ -1,23 +1,29 @@
 /*
- * Copyright (c) 2000-2004 Apple Computer, Inc. All rights reserved.
+ * Copyright (c) 2000-2009 Apple Inc. All rights reserved.
  *
- * @APPLE_LICENSE_HEADER_START@
+ * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
  * 
- * The contents of this file constitute Original Code as defined in and
- * are subject to the Apple Public Source License Version 1.1 (the
- * "License").  You may not use this file except in compliance with the
- * License.  Please obtain a copy of the License at
- * http://www.apple.com/publicsource and read it before using this file.
+ * This file contains Original Code and/or Modifications of Original Code
+ * as defined in and that are subject to the Apple Public Source License
+ * Version 2.0 (the 'License'). You may not use this file except in
+ * compliance with the License. The rights granted to you under the License
+ * may not be used to create, or enable the creation or redistribution of,
+ * unlawful or unlicensed copies of an Apple operating system, or to
+ * circumvent, violate, or enable the circumvention or violation of, any
+ * terms of an Apple operating system software license agreement.
  * 
- * This Original Code and all software distributed under the License are
- * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
+ * Please obtain a copy of the License at
+ * http://www.opensource.apple.com/apsl/ and read it before using this file.
+ * 
+ * The Original Code and all software distributed under the License are
+ * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT.  Please see the
- * License for the specific language governing rights and limitations
- * under the License.
+ * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
+ * Please see the License for the specific language governing rights and
+ * limitations under the License.
  * 
- * @APPLE_LICENSE_HEADER_END@
+ * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
  */
 /*
  * @OSF_COPYRIGHT@
 #include <ipc/ipc_port.h>
 #include <ipc/ipc_space.h>
 #include <kern/host.h>
-#include <kern/wait_queue.h>
+#include <kern/waitq.h>
 #include <kern/zalloc.h>
 #include <kern/mach_param.h>
 
+#include <libkern/OSAtomic.h>
+
 static unsigned int semaphore_event;
-#define SEMAPHORE_EVENT ((event64_t)&semaphore_event)
+#define SEMAPHORE_EVENT CAST_EVENT64_T(&semaphore_event)
 
 zone_t semaphore_zone;
-unsigned int semaphore_max = SEMAPHORE_MAX;
+unsigned int semaphore_max;
 
 /* Forward declarations */
 
@@ -87,6 +95,8 @@ semaphore_timedwait_signal_trap_internal(
                                clock_res_t nsec,
                                void (*caller_cont)(kern_return_t));
 
+kern_return_t
+semaphore_signal_internal_trap(mach_port_name_t sema_name);
 
 kern_return_t
 semaphore_signal_internal(
@@ -101,13 +111,33 @@ semaphore_convert_wait_result(
 void
 semaphore_wait_continue(void);
 
-kern_return_t
+static kern_return_t
 semaphore_wait_internal(
                        semaphore_t             wait_semaphore,
                        semaphore_t             signal_semaphore,
-                       mach_timespec_t *wait_timep,
+                       uint64_t                deadline,
+                       int                             option,
                        void (*caller_cont)(kern_return_t));
 
+void
+kdp_sema_find_owner(
+                       struct waitq *          waitq,
+                       event64_t               event,
+                       thread_waitinfo_t *     waitinfo);
+
+static __inline__ uint64_t
+semaphore_deadline(
+       unsigned int            sec,
+       clock_res_t                     nsec)
+{
+       uint64_t        abstime;
+
+       nanoseconds_to_absolutetime((uint64_t)sec *     NSEC_PER_SEC + nsec, &abstime);
+       clock_absolutetime_interval_to_deadline(abstime, &abstime);
+
+       return (abstime);
+}
+
 /*
  *     ROUTINE:        semaphore_init          [private]
  *
@@ -121,6 +151,7 @@ semaphore_init(void)
                        semaphore_max * sizeof(struct semaphore),
                        sizeof(struct semaphore),
                        "semaphores");
+  zone_change(semaphore_zone, Z_NOENCRYPT, TRUE);
 }
 
 /*
@@ -137,50 +168,40 @@ semaphore_create(
        int                             value)
 {
        semaphore_t              s = SEMAPHORE_NULL;
+       kern_return_t           kret;
 
 
-
-       if (task == TASK_NULL || value < 0 || policy > SYNC_POLICY_MAX) {
-               *new_semaphore = SEMAPHORE_NULL;
+       *new_semaphore = SEMAPHORE_NULL;
+       if (task == TASK_NULL || value < 0 || policy > SYNC_POLICY_MAX)
                return KERN_INVALID_ARGUMENT;
-       }
 
        s = (semaphore_t) zalloc (semaphore_zone);
 
-       if (s == SEMAPHORE_NULL) {
-               *new_semaphore = SEMAPHORE_NULL;
+       if (s == SEMAPHORE_NULL)
                return KERN_RESOURCE_SHORTAGE; 
-       }
 
-       wait_queue_init(&s->wait_queue, policy); /* also inits lock */
-       s->count = value;
-       s->ref_count = 1;
+       kret = waitq_init(&s->waitq, policy | SYNC_POLICY_DISABLE_IRQ); /* also inits lock */
+       if (kret != KERN_SUCCESS) {
+               zfree(semaphore_zone, s);
+               return kret;
+       }
 
        /*
-        *  Create and initialize the semaphore port
+        * Initialize the semaphore values.
         */
-       s->port = ipc_port_alloc_kernel();
-       if (s->port == IP_NULL) {       
-               /* This will deallocate the semaphore */        
-               semaphore_dereference(s);
-               *new_semaphore = SEMAPHORE_NULL;
-               return KERN_RESOURCE_SHORTAGE; 
-       }
-
-       ipc_kobject_set (s->port, (ipc_kobject_t) s, IKOT_SEMAPHORE);
+       s->port = IP_NULL;
+       s->ref_count = 1;
+       s->count = value;
+       s->active = TRUE;
+       s->owner = task;
 
        /*
         *  Associate the new semaphore with the task by adding
         *  the new semaphore to the task's semaphore list.
-        *
-        *  Associate the task with the new semaphore by having the
-        *  semaphores task pointer point to the owning task's structure.
         */
        task_lock(task);
        enqueue_head(&task->semaphore_list, (queue_entry_t) s);
        task->semaphores_owned++;
-       s->owner = task;
-       s->active = TRUE;
        task_unlock(task);
 
        *new_semaphore = s;
@@ -189,42 +210,30 @@ semaphore_create(
 }                
 
 /*
- *     Routine:        semaphore_destroy
+ *     Routine:        semaphore_destroy_internal
  *
- *     Destroys a semaphore.  This call will only succeed if the
- *     specified task is the SAME task name specified at the semaphore's
- *     creation.
+ *     Disassociate a semaphore from its owning task, mark it inactive,
+ *     and set any waiting threads running with THREAD_RESTART.
  *
- *     All threads currently blocked on the semaphore are awoken.  These
- *     threads will return with the KERN_TERMINATED error.
+ *     Conditions:
+ *                     task is locked
+ *                     semaphore is locked
+ *                     semaphore is owned by the specified task
+ *     Returns:
+ *                     with semaphore unlocked
  */
-kern_return_t
-semaphore_destroy(
+static void
+semaphore_destroy_internal(
        task_t                  task,
        semaphore_t             semaphore)
 {
-       int                             old_count;
-       spl_t                   spl_level;
-
+       int                     old_count;
 
-       if (task == TASK_NULL || semaphore == SEMAPHORE_NULL)
-               return KERN_INVALID_ARGUMENT;
-
-       /*
-        *  Disown semaphore
-        */
-       task_lock(task);
-       if (semaphore->owner != task) {
-               task_unlock(task);
-               return KERN_INVALID_ARGUMENT;
-       }
-       remqueue(&task->semaphore_list, (queue_entry_t) semaphore);
+       /* unlink semaphore from owning task */
+       assert(semaphore->owner == task);
+       remqueue((queue_entry_t) semaphore);
        semaphore->owner = TASK_NULL;
        task->semaphores_owned--;
-       task_unlock(task);
-
-       spl_level = splsched();
-       semaphore_lock(semaphore);
 
        /*
         *  Deactivate semaphore
@@ -239,26 +248,99 @@ semaphore_destroy(
        semaphore->count = 0;
 
        if (old_count < 0) {
-               wait_queue_wakeup64_all_locked(&semaphore->wait_queue,
-                                            SEMAPHORE_EVENT,
-                                            THREAD_RESTART,
-                                            TRUE);             /* unlock? */
+               waitq_wakeup64_all_locked(&semaphore->waitq,
+                                         SEMAPHORE_EVENT,
+                                         THREAD_RESTART, NULL,
+                                         WAITQ_ALL_PRIORITIES,
+                                         WAITQ_UNLOCK);
+               /* waitq/semaphore is unlocked */
        } else {
                semaphore_unlock(semaphore);
        }
+}
+
+/*
+ *     Routine:        semaphore_destroy
+ *
+ *     Destroys a semaphore and consume the caller's reference on the
+ *     semaphore.
+ */
+kern_return_t
+semaphore_destroy(
+       task_t                  task,
+       semaphore_t             semaphore)
+{
+       spl_t spl_level;
+
+       if (semaphore == SEMAPHORE_NULL)
+               return KERN_INVALID_ARGUMENT;
+
+       if (task == TASK_NULL) {
+               semaphore_dereference(semaphore);
+               return KERN_INVALID_ARGUMENT;
+       }
+
+       task_lock(task);
+       spl_level = splsched();
+       semaphore_lock(semaphore);
+
+       if (semaphore->owner != task) {
+               semaphore_unlock(semaphore);
+               splx(spl_level);
+               task_unlock(task);
+               return KERN_INVALID_ARGUMENT;
+       }
+                       
+       semaphore_destroy_internal(task, semaphore);
+       /* semaphore unlocked */
+
        splx(spl_level);
+       task_unlock(task);
 
-       /*
-        *  Deallocate
-        *
-        *  Drop the semaphore reference, which in turn deallocates the
-        *  semaphore structure if the reference count goes to zero.
-        */
-       ipc_port_dealloc_kernel(semaphore->port);
        semaphore_dereference(semaphore);
        return KERN_SUCCESS;
 }
 
+/*
+ *     Routine:        semaphore_destroy_all
+ *
+ *     Destroy all the semaphores associated with a given task.
+ */
+#define SEMASPERSPL 20  /* max number of semaphores to destroy per spl hold */
+
+void
+semaphore_destroy_all(
+       task_t                  task)
+{
+       uint32_t count;
+       spl_t spl_level;
+
+       count = 0;
+       task_lock(task);
+       while (!queue_empty(&task->semaphore_list)) {
+               semaphore_t semaphore;
+
+               semaphore = (semaphore_t) queue_first(&task->semaphore_list);
+
+               if (count == 0) 
+                       spl_level = splsched();
+               semaphore_lock(semaphore);
+
+               semaphore_destroy_internal(task, semaphore);
+               /* semaphore unlocked */
+
+               /* throttle number of semaphores per interrupt disablement */
+               if (++count == SEMASPERSPL) {
+                       count = 0;
+                       splx(spl_level);
+               }
+       }
+       if (count != 0)
+               splx(spl_level);
+
+       task_unlock(task);
+}
+
 /*
  *     Routine:        semaphore_signal_internal
  *
@@ -286,15 +368,16 @@ semaphore_signal_internal(
 
        if (thread != THREAD_NULL) {
                if (semaphore->count < 0) {
-                       kr = wait_queue_wakeup64_thread_locked(
-                                       &semaphore->wait_queue,
+                       kr = waitq_wakeup64_thread_locked(
+                                       &semaphore->waitq,
                                        SEMAPHORE_EVENT,
                                        thread,
                                        THREAD_AWAKENED,
-                                       TRUE);  /* unlock? */
+                                       WAITQ_UNLOCK);
+                       /* waitq/semaphore is unlocked */
                } else {
-                       semaphore_unlock(semaphore);
                        kr = KERN_NOT_WAITING;
+                       semaphore_unlock(semaphore);
                }
                splx(spl_level);
                return kr;
@@ -303,34 +386,40 @@ semaphore_signal_internal(
        if (options & SEMAPHORE_SIGNAL_ALL) {
                int old_count = semaphore->count;
 
+               kr = KERN_NOT_WAITING;
                if (old_count < 0) {
                        semaphore->count = 0;  /* always reset */
-                       kr = wait_queue_wakeup64_all_locked(
-                                       &semaphore->wait_queue,
+                       kr = waitq_wakeup64_all_locked(
+                                       &semaphore->waitq,
                                        SEMAPHORE_EVENT,
-                                       THREAD_AWAKENED,
-                                       TRUE);          /* unlock? */
+                                       THREAD_AWAKENED, NULL,
+                                       WAITQ_ALL_PRIORITIES,
+                                       WAITQ_UNLOCK);
+                       /* waitq / semaphore is unlocked */
                } else {
                        if (options & SEMAPHORE_SIGNAL_PREPOST)
                                semaphore->count++;
-                       semaphore_unlock(semaphore);
                        kr = KERN_SUCCESS;
+                       semaphore_unlock(semaphore);
                }
                splx(spl_level);
                return kr;
        }
        
        if (semaphore->count < 0) {
-               if (wait_queue_wakeup64_one_locked(
-                                       &semaphore->wait_queue,
+               kr = waitq_wakeup64_one_locked(
+                                       &semaphore->waitq,
                                        SEMAPHORE_EVENT,
-                                       THREAD_AWAKENED,
-                                       FALSE) == KERN_SUCCESS) {
+                                       THREAD_AWAKENED, NULL,
+                                       WAITQ_ALL_PRIORITIES,
+                                       WAITQ_KEEP_LOCKED);
+               if (kr == KERN_SUCCESS) {
                        semaphore_unlock(semaphore);
                        splx(spl_level);
                        return KERN_SUCCESS;
-               } else
+               } else {
                        semaphore->count = 0;  /* all waiters gone */
+               }
        }
 
        if (options & SEMAPHORE_SIGNAL_PREPOST) {
@@ -446,6 +535,13 @@ semaphore_signal_trap(
        struct semaphore_signal_trap_args *args)
 {
        mach_port_name_t sema_name = args->signal_name;
+
+       return (semaphore_signal_internal_trap(sema_name));
+}
+
+kern_return_t
+semaphore_signal_internal_trap(mach_port_name_t sema_name)
+{
        semaphore_t     semaphore;
        kern_return_t kr;
 
@@ -571,14 +667,14 @@ semaphore_wait_continue(void)
  *             The reference
  *             A reference is held on the signal semaphore.
  */
-kern_return_t
+static kern_return_t
 semaphore_wait_internal(
        semaphore_t             wait_semaphore,
        semaphore_t             signal_semaphore,
-       mach_timespec_t         *wait_timep,
+       uint64_t                deadline,
+       int                             option,
        void                    (*caller_cont)(kern_return_t))
 {
-       boolean_t                       nonblocking;
        int                                     wait_result;
        spl_t                           spl_level;
        kern_return_t           kr = KERN_ALREADY_WAITING;
@@ -586,44 +682,26 @@ semaphore_wait_internal(
        spl_level = splsched();
        semaphore_lock(wait_semaphore);
 
-       /*
-        * Decide if we really have to wait.
-        */
-       nonblocking = (wait_timep != (mach_timespec_t *)0) ?
-                     (wait_timep->tv_sec == 0 && wait_timep->tv_nsec == 0) :
-                     FALSE;
-
        if (!wait_semaphore->active) {
                kr = KERN_TERMINATED;
        } else if (wait_semaphore->count > 0) {
                wait_semaphore->count--;
                kr = KERN_SUCCESS;
-       } else if (nonblocking) {
+       } else if (option & SEMAPHORE_TIMEOUT_NOBLOCK) {
                kr = KERN_OPERATION_TIMED_OUT;
        } else {
-               uint64_t        abstime;
                thread_t        self = current_thread();
 
                wait_semaphore->count = -1;  /* we don't keep an actual count */
-               thread_lock(self);
-               
-               /*
-                * If it is a timed wait, calculate the wake up deadline.
-                */
-               if (wait_timep != (mach_timespec_t *)0) {
-                       nanoseconds_to_absolutetime((uint64_t)wait_timep->tv_sec *
-                                                                                       NSEC_PER_SEC + wait_timep->tv_nsec, &abstime);
-                       clock_absolutetime_interval_to_deadline(abstime, &abstime);
-               }
-               else
-                       abstime = 0;
 
-               (void)wait_queue_assert_wait64_locked(
-                                       &wait_semaphore->wait_queue,
+               thread_set_pending_block_hint(self, kThreadWaitSemaphore);
+               (void)waitq_assert_wait64_locked(
+                                       &wait_semaphore->waitq,
                                        SEMAPHORE_EVENT,
-                                       THREAD_ABORTSAFE, abstime,
+                                       THREAD_ABORTSAFE,
+                                       TIMEOUT_URGENCY_USER_NORMAL,
+                                       deadline, TIMEOUT_NO_LEEWAY,
                                        self);
-               thread_unlock(self);
        }
        semaphore_unlock(wait_semaphore);
        splx(spl_level);
@@ -714,8 +792,37 @@ semaphore_wait(
                return KERN_INVALID_ARGUMENT;
 
        return(semaphore_wait_internal(semaphore,
-                                      SEMAPHORE_NULL,
-                                      (mach_timespec_t *)0,
+                                          SEMAPHORE_NULL,
+                                          0ULL, SEMAPHORE_OPTION_NONE,
+                                      (void (*)(kern_return_t))0));
+}
+
+kern_return_t
+semaphore_wait_noblock(
+       semaphore_t             semaphore)
+{      
+
+       if (semaphore == SEMAPHORE_NULL)
+               return KERN_INVALID_ARGUMENT;
+
+       return(semaphore_wait_internal(semaphore,
+                                          SEMAPHORE_NULL,
+                                          0ULL, SEMAPHORE_TIMEOUT_NOBLOCK,
+                                      (void (*)(kern_return_t))0));
+}
+
+kern_return_t
+semaphore_wait_deadline(
+       semaphore_t             semaphore,
+       uint64_t                deadline)
+{      
+
+       if (semaphore == SEMAPHORE_NULL)
+               return KERN_INVALID_ARGUMENT;
+
+       return(semaphore_wait_internal(semaphore,
+                                          SEMAPHORE_NULL,
+                                          deadline, SEMAPHORE_OPTION_NONE,
                                       (void (*)(kern_return_t))0));
 }
 
@@ -747,7 +854,7 @@ semaphore_wait_trap_internal(
        if (kr == KERN_SUCCESS) {
                kr = semaphore_wait_internal(semaphore,
                                SEMAPHORE_NULL,
-                               (mach_timespec_t *)0,
+                               0ULL, SEMAPHORE_OPTION_NONE,
                                caller_cont);
                semaphore_dereference(semaphore);
        }
@@ -766,16 +873,24 @@ kern_return_t
 semaphore_timedwait(
        semaphore_t             semaphore,
        mach_timespec_t         wait_time)
-{      
+{
+       int                             option = SEMAPHORE_OPTION_NONE;
+       uint64_t                deadline = 0;
+
        if (semaphore == SEMAPHORE_NULL)
                return KERN_INVALID_ARGUMENT;
        
        if(BAD_MACH_TIMESPEC(&wait_time))
                return KERN_INVALID_VALUE;
+
+       if (wait_time.tv_sec == 0 && wait_time.tv_nsec == 0)
+               option = SEMAPHORE_TIMEOUT_NOBLOCK;
+       else
+               deadline = semaphore_deadline(wait_time.tv_sec, wait_time.tv_nsec);
        
        return (semaphore_wait_internal(semaphore,
                                        SEMAPHORE_NULL,
-                                       &wait_time,
+                                       deadline, option,
                                        (void(*)(kern_return_t))0));
        
 }
@@ -807,7 +922,6 @@ semaphore_timedwait_trap_internal(
        clock_res_t             nsec,
        void (*caller_cont)(kern_return_t))
 {
-
        semaphore_t semaphore;
        mach_timespec_t wait_time;
        kern_return_t kr;
@@ -819,9 +933,17 @@ semaphore_timedwait_trap_internal(
        
        kr = port_name_to_semaphore(name, &semaphore);
        if (kr == KERN_SUCCESS) {
+               int                             option = SEMAPHORE_OPTION_NONE;
+               uint64_t                deadline = 0;
+
+               if (sec == 0 && nsec == 0)
+                       option = SEMAPHORE_TIMEOUT_NOBLOCK;
+               else
+                       deadline = semaphore_deadline(sec, nsec);
+
                kr = semaphore_wait_internal(semaphore,
                                SEMAPHORE_NULL,
-                               &wait_time,
+                               deadline, option,
                                caller_cont);
                semaphore_dereference(semaphore);
        }
@@ -846,7 +968,7 @@ semaphore_wait_signal(
        
        return(semaphore_wait_internal(wait_semaphore,
                                       signal_semaphore,
-                                      (mach_timespec_t *)0,
+                                          0ULL, SEMAPHORE_OPTION_NONE,
                                       (void(*)(kern_return_t))0));
 }
 
@@ -879,7 +1001,7 @@ semaphore_wait_signal_trap_internal(
                if (kr == KERN_SUCCESS) {
                        kr = semaphore_wait_internal(wait_semaphore,
                                        signal_semaphore,
-                                       (mach_timespec_t *)0,
+                                       0ULL, SEMAPHORE_OPTION_NONE,
                                        caller_cont);
                        semaphore_dereference(wait_semaphore);
                }
@@ -904,15 +1026,23 @@ semaphore_timedwait_signal(
        semaphore_t             signal_semaphore,
        mach_timespec_t         wait_time)
 {
+       int                             option = SEMAPHORE_OPTION_NONE;
+       uint64_t                deadline = 0;
+
        if (wait_semaphore == SEMAPHORE_NULL)
                return KERN_INVALID_ARGUMENT;
        
        if(BAD_MACH_TIMESPEC(&wait_time))
                return KERN_INVALID_VALUE;
+
+       if (wait_time.tv_sec == 0 && wait_time.tv_nsec == 0)
+               option = SEMAPHORE_TIMEOUT_NOBLOCK;
+       else
+               deadline = semaphore_deadline(wait_time.tv_sec, wait_time.tv_nsec);
        
        return(semaphore_wait_internal(wait_semaphore,
                                       signal_semaphore,
-                                      &wait_time,
+                                          deadline, option,
                                       (void(*)(kern_return_t))0));
 }
 
@@ -951,9 +1081,17 @@ semaphore_timedwait_signal_trap_internal(
        if (kr == KERN_SUCCESS) {
                kr = port_name_to_semaphore(wait_name, &wait_semaphore);
                if (kr == KERN_SUCCESS) {
+                       int                             option = SEMAPHORE_OPTION_NONE;
+                       uint64_t                deadline = 0;
+
+                       if (sec == 0 && nsec == 0)
+                               option = SEMAPHORE_TIMEOUT_NOBLOCK;
+                       else
+                               deadline = semaphore_deadline(sec, nsec);
+
                        kr = semaphore_wait_internal(wait_semaphore,
                                        signal_semaphore,
-                                       &wait_time,
+                                       deadline, option,
                                        caller_cont);
                        semaphore_dereference(wait_semaphore);
                }
@@ -973,15 +1111,7 @@ void
 semaphore_reference(
        semaphore_t             semaphore)
 {
-       spl_t                   spl_level;
-
-       spl_level = splsched();
-       semaphore_lock(semaphore);
-
-       semaphore->ref_count++;
-
-       semaphore_unlock(semaphore);
-       splx(spl_level);
+       (void)hw_atomic_add(&semaphore->ref_count, 1);
 }
 
 /*
@@ -994,21 +1124,70 @@ void
 semaphore_dereference(
        semaphore_t             semaphore)
 {
-       int                     ref_count;
-       spl_t                   spl_level;
+       uint32_t collisions;
+       spl_t spl_level;
 
-       if (semaphore != NULL) {
-           spl_level = splsched();
-           semaphore_lock(semaphore);
+       if (semaphore == NULL)
+               return;
 
-           ref_count = --(semaphore->ref_count);
+       if (hw_atomic_sub(&semaphore->ref_count, 1) != 0)
+               return;
 
-           semaphore_unlock(semaphore);
-           splx(spl_level);
+       /*
+        * Last ref, clean up the port [if any]
+        * associated with the semaphore, destroy
+        * it (if still active) and then free
+        * the semaphore.
+        */
+       ipc_port_t port = semaphore->port;
+
+       if (IP_VALID(port)) {
+               assert(!port->ip_srights);
+               ipc_port_dealloc_kernel(port);
+       }
 
-           if (ref_count == 0) {
-                       assert(wait_queue_empty(&semaphore->wait_queue));
-                       zfree(semaphore_zone, semaphore);
-           }
+       /*
+        * Lock the semaphore to lock in the owner task reference.
+        * Then continue to try to lock the task (inverse order).
+        */
+       spl_level = splsched();
+       semaphore_lock(semaphore);
+       for (collisions = 0; semaphore->active; collisions++) {
+               task_t task = semaphore->owner;
+
+               assert(task != TASK_NULL);
+               
+               if (task_lock_try(task)) {
+                       semaphore_destroy_internal(task, semaphore);
+                       /* semaphore unlocked */
+                       splx(spl_level);
+                       task_unlock(task);
+                       goto out;
+               }
+               
+               /* failed to get out-of-order locks */
+               semaphore_unlock(semaphore);
+               splx(spl_level);
+               mutex_pause(collisions);
+               spl_level = splsched();
+               semaphore_lock(semaphore);
        }
+       semaphore_unlock(semaphore);
+       splx(spl_level);
+
+ out:
+       zfree(semaphore_zone, semaphore);
+}
+
+#define WAITQ_TO_SEMA(wq) ((semaphore_t) ((uintptr_t)(wq) - offsetof(struct semaphore, waitq)))
+void
+kdp_sema_find_owner(struct waitq * waitq, __assert_only event64_t event, thread_waitinfo_t * waitinfo)
+{
+       semaphore_t sem = WAITQ_TO_SEMA(waitq);
+       assert(event == SEMAPHORE_EVENT);
+       assert(kdp_is_in_zone(sem, "semaphores"));
+
+       waitinfo->context = VM_KERNEL_UNSLIDE_OR_PERM(sem->port);
+       if (sem->owner)
+               waitinfo->owner = pid_from_task(sem->owner);
 }