+/* Returns a +1 thread reference */
+thread_t
+port_name_to_thread_for_ulock(mach_port_name_t thread_name)
+{
+ thread_t thread = THREAD_NULL;
+ thread_t self = current_thread();
+
+ /*
+ * Translate the port name if supplied.
+ */
+ if (thread_name != MACH_PORT_NULL) {
+ ipc_port_t port;
+
+ if (ipc_port_translate_send(self->task->itk_space,
+ thread_name, &port) == KERN_SUCCESS) {
+ ip_reference(port);
+ ip_unlock(port);
+
+ thread = convert_port_to_thread(port);
+ ip_release(port);
+
+ if (thread == THREAD_NULL) {
+ return thread;
+ }
+
+ if ((thread == self) || (thread->task != self->task)) {
+ thread_deallocate(thread);
+ thread = THREAD_NULL;
+ }
+ }
+ }
+
+ return thread;
+}
+
+/* This function is called after an assert_wait(), therefore it must not
+ * cause another wait until after the thread_run() or thread_block()
+ *
+ * Consumes a ref on thread
+ */
+wait_result_t
+thread_handoff(thread_t thread)
+{
+ thread_t deallocate_thread = THREAD_NULL;
+ thread_t self = current_thread();
+
+ /*
+ * Try to handoff if supplied.
+ */
+ if (thread != THREAD_NULL) {
+ spl_t s = splsched();
+
+ thread_t pulled_thread = thread_run_queue_remove_for_handoff(thread);
+
+ KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED,MACH_SCHED_THREAD_SWITCH)|DBG_FUNC_NONE,
+ thread_tid(thread), thread->state,
+ pulled_thread ? TRUE : FALSE, 0, 0);
+
+ if (pulled_thread != THREAD_NULL) {
+ /* We can't be dropping the last ref here */
+ thread_deallocate_safe(thread);
+
+ int result = thread_run(self, THREAD_CONTINUE_NULL, NULL, pulled_thread);
+
+ splx(s);
+ return result;
+ }
+
+ splx(s);
+
+ deallocate_thread = thread;
+ thread = THREAD_NULL;
+ }
+
+ int result = thread_block(THREAD_CONTINUE_NULL);
+ if (deallocate_thread != THREAD_NULL) {
+ thread_deallocate(deallocate_thread);
+ }
+
+ return result;
+}
+