+#if defined(CONFIG_SCHED_TIMESHARE_CORE)
+ new_thread->sched_stamp = sched_tick;
+ new_thread->pri_shift = sched_pri_shifts[new_thread->th_sched_bucket];
+#endif /* defined(CONFIG_SCHED_TIMESHARE_CORE) */
+
+#if CONFIG_EMBEDDED
+ if (parent_task->max_priority <= MAXPRI_THROTTLE)
+ sched_thread_mode_demote(new_thread, TH_SFLAG_THROTTLED);
+#endif /* CONFIG_EMBEDDED */
+
+ thread_policy_create(new_thread);
+
+ /* Chain the thread onto the task's list */
+ queue_enter(&parent_task->threads, new_thread, thread_t, task_threads);
+ parent_task->thread_count++;
+
+ /* So terminating threads don't need to take the task lock to decrement */
+ hw_atomic_add(&parent_task->active_thread_count, 1);
+
+ /* Protected by the tasks_threads_lock */
+ new_thread->thread_id = ++thread_unique_id;
+
+
+ queue_enter(&threads, new_thread, thread_t, threads);
+ threads_count++;
+
+ new_thread->active = TRUE;
+ if (task_is_a_corpse_fork(parent_task)) {
+ /* Set the inspection bit if the task is a corpse fork */
+ new_thread->inspection = TRUE;
+ } else {
+ new_thread->inspection = FALSE;
+ }
+ new_thread->corpse_dup = FALSE;
+ *out_thread = new_thread;
+
+ {
+ long dbg_arg1, dbg_arg2, dbg_arg3, dbg_arg4;
+
+ kdbg_trace_data(parent_task->bsd_info, &dbg_arg2, &dbg_arg4);
+
+ /*
+ * Starting with 26604425, exec'ing creates a new task/thread.
+ *
+ * NEWTHREAD in the current process has two possible meanings:
+ *
+ * 1) Create a new thread for this process.
+ * 2) Create a new thread for the future process this will become in an exec.
+ *
+ * To disambiguate these, arg3 will be set to TRUE for case #2.
+ *
+ * The value we need to find (TPF_EXEC_COPY) is stable in the case of a
+ * task exec'ing. The read of t_procflags does not take the proc_lock.
+ */
+ dbg_arg3 = (task_is_exec_copy(parent_task)) ? TRUE : 0;
+
+
+ KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
+ TRACE_DATA_NEWTHREAD | DBG_FUNC_NONE,
+ (vm_address_t)(uintptr_t)thread_tid(new_thread), dbg_arg2, dbg_arg3, dbg_arg4, 0);
+
+ kdbg_trace_string(parent_task->bsd_info,
+ &dbg_arg1, &dbg_arg2, &dbg_arg3, &dbg_arg4);
+
+ KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
+ TRACE_STRING_NEWTHREAD | DBG_FUNC_NONE,
+ dbg_arg1, dbg_arg2, dbg_arg3, dbg_arg4, 0);
+ }
+
+ DTRACE_PROC1(lwp__create, thread_t, *out_thread);
+
+ return (KERN_SUCCESS);
+}
+
+static kern_return_t
+thread_create_internal2(
+ task_t task,
+ thread_t *new_thread,
+ boolean_t from_user,
+ thread_continue_t continuation)
+{
+ kern_return_t result;
+ thread_t thread;
+
+ if (task == TASK_NULL || task == kernel_task)
+ return (KERN_INVALID_ARGUMENT);
+
+ result = thread_create_internal(task, -1, continuation, TH_OPTION_NONE, &thread);
+ if (result != KERN_SUCCESS)
+ return (result);
+
+ thread->user_stop_count = 1;
+ thread_hold(thread);
+ if (task->suspend_count > 0)
+ thread_hold(thread);
+
+ if (from_user)
+ extmod_statistics_incr_thread_create(task);
+
+ task_unlock(task);
+ lck_mtx_unlock(&tasks_threads_lock);
+
+ *new_thread = thread;
+
+ return (KERN_SUCCESS);
+}
+
+/* No prototype, since task_server.h has the _from_user version if KERNEL_SERVER */
+kern_return_t
+thread_create(
+ task_t task,
+ thread_t *new_thread);
+
+kern_return_t
+thread_create(
+ task_t task,
+ thread_t *new_thread)
+{
+ return thread_create_internal2(task, new_thread, FALSE, (thread_continue_t)thread_bootstrap_return);
+}
+
+kern_return_t
+thread_create_from_user(
+ task_t task,
+ thread_t *new_thread)
+{
+ return thread_create_internal2(task, new_thread, TRUE, (thread_continue_t)thread_bootstrap_return);
+}
+
+kern_return_t
+thread_create_with_continuation(
+ task_t task,
+ thread_t *new_thread,
+ thread_continue_t continuation)
+{
+ return thread_create_internal2(task, new_thread, FALSE, continuation);
+}
+
+/*
+ * Create a thread that is already started, but is waiting on an event
+ */
+static kern_return_t
+thread_create_waiting_internal(
+ task_t task,
+ thread_continue_t continuation,
+ event_t event,
+ int options,
+ thread_t *new_thread)
+{
+ kern_return_t result;
+ thread_t thread;
+
+ if (task == TASK_NULL || task == kernel_task)
+ return (KERN_INVALID_ARGUMENT);
+
+ result = thread_create_internal(task, -1, continuation, options, &thread);
+ if (result != KERN_SUCCESS)
+ return (result);
+
+ /* note no user_stop_count or thread_hold here */
+
+ if (task->suspend_count > 0)
+ thread_hold(thread);
+
+ thread_mtx_lock(thread);
+ thread_start_in_assert_wait(thread, event, THREAD_INTERRUPTIBLE);
+ thread_mtx_unlock(thread);
+
+ task_unlock(task);
+ lck_mtx_unlock(&tasks_threads_lock);
+
+ *new_thread = thread;
+
+ return (KERN_SUCCESS);
+}
+
+kern_return_t
+thread_create_waiting(
+ task_t task,
+ thread_continue_t continuation,
+ event_t event,
+ thread_t *new_thread)
+{
+ return thread_create_waiting_internal(task, continuation, event,
+ TH_OPTION_NONE, new_thread);
+}
+
+
+static kern_return_t
+thread_create_running_internal2(
+ task_t task,
+ int flavor,
+ thread_state_t new_state,
+ mach_msg_type_number_t new_state_count,
+ thread_t *new_thread,
+ boolean_t from_user)
+{
+ kern_return_t result;
+ thread_t thread;
+
+ if (task == TASK_NULL || task == kernel_task)
+ return (KERN_INVALID_ARGUMENT);
+
+ result = thread_create_internal(task, -1, (thread_continue_t)thread_bootstrap_return, TH_OPTION_NONE, &thread);
+ if (result != KERN_SUCCESS)
+ return (result);
+
+ if (task->suspend_count > 0)
+ thread_hold(thread);
+
+ result = machine_thread_set_state(thread, flavor, new_state, new_state_count);
+ if (result != KERN_SUCCESS) {
+ task_unlock(task);
+ lck_mtx_unlock(&tasks_threads_lock);
+
+ thread_terminate(thread);
+ thread_deallocate(thread);
+ return (result);
+ }
+
+ thread_mtx_lock(thread);
+ thread_start(thread);
+ thread_mtx_unlock(thread);
+
+ if (from_user)
+ extmod_statistics_incr_thread_create(task);
+
+ task_unlock(task);
+ lck_mtx_unlock(&tasks_threads_lock);
+
+ *new_thread = thread;
+
+ return (result);
+}
+
+/* Prototype, see justification above */
+kern_return_t
+thread_create_running(
+ task_t task,
+ int flavor,
+ thread_state_t new_state,
+ mach_msg_type_number_t new_state_count,
+ thread_t *new_thread);
+
+kern_return_t
+thread_create_running(
+ task_t task,
+ int flavor,
+ thread_state_t new_state,
+ mach_msg_type_number_t new_state_count,
+ thread_t *new_thread)
+{
+ return thread_create_running_internal2(
+ task, flavor, new_state, new_state_count,
+ new_thread, FALSE);
+}
+
+kern_return_t
+thread_create_running_from_user(
+ task_t task,
+ int flavor,
+ thread_state_t new_state,
+ mach_msg_type_number_t new_state_count,
+ thread_t *new_thread)
+{
+ return thread_create_running_internal2(
+ task, flavor, new_state, new_state_count,
+ new_thread, TRUE);
+}
+
+kern_return_t
+thread_create_workq(
+ task_t task,
+ thread_continue_t thread_return,
+ thread_t *new_thread)
+{
+ kern_return_t result;
+ thread_t thread;
+
+ if (task == TASK_NULL || task == kernel_task)
+ return (KERN_INVALID_ARGUMENT);
+
+ result = thread_create_internal(task, -1, thread_return, TH_OPTION_NOCRED | TH_OPTION_NOSUSP, &thread);
+ if (result != KERN_SUCCESS)
+ return (result);
+
+ thread->user_stop_count = 1;
+ thread_hold(thread);
+ if (task->suspend_count > 0)
+ thread_hold(thread);
+
+ task_unlock(task);
+ lck_mtx_unlock(&tasks_threads_lock);
+
+ *new_thread = thread;
+
+ return (KERN_SUCCESS);
+}
+
+kern_return_t
+thread_create_workq_waiting(
+ task_t task,
+ thread_continue_t continuation,
+ event_t event,
+ thread_t *new_thread)
+{
+
+ return thread_create_waiting_internal(task, continuation, event,
+ TH_OPTION_NOCRED | TH_OPTION_NOSUSP,
+ new_thread);
+}
+
+/*
+ * kernel_thread_create:
+ *
+ * Create a thread in the kernel task
+ * to execute in kernel context.
+ */
+kern_return_t
+kernel_thread_create(
+ thread_continue_t continuation,
+ void *parameter,
+ integer_t priority,
+ thread_t *new_thread)
+{
+ kern_return_t result;
+ thread_t thread;
+ task_t task = kernel_task;
+
+ result = thread_create_internal(task, priority, continuation, TH_OPTION_NOCRED | TH_OPTION_NONE, &thread);
+ if (result != KERN_SUCCESS)
+ return (result);
+
+ task_unlock(task);
+ lck_mtx_unlock(&tasks_threads_lock);
+
+ stack_alloc(thread);
+ assert(thread->kernel_stack != 0);
+#if CONFIG_EMBEDDED
+ if (priority > BASEPRI_KERNEL)
+#endif
+ thread->reserved_stack = thread->kernel_stack;
+
+ thread->parameter = parameter;
+
+if(debug_task & 1)
+ kprintf("kernel_thread_create: thread = %p continuation = %p\n", thread, continuation);
+ *new_thread = thread;
+
+ return (result);
+}
+
+kern_return_t
+kernel_thread_start_priority(
+ thread_continue_t continuation,
+ void *parameter,
+ integer_t priority,
+ thread_t *new_thread)
+{
+ kern_return_t result;
+ thread_t thread;
+
+ result = kernel_thread_create(continuation, parameter, priority, &thread);
+ if (result != KERN_SUCCESS)
+ return (result);
+
+ *new_thread = thread;
+
+ thread_mtx_lock(thread);
+ thread_start(thread);
+ thread_mtx_unlock(thread);
+
+ return (result);
+}
+
+kern_return_t
+kernel_thread_start(
+ thread_continue_t continuation,
+ void *parameter,
+ thread_t *new_thread)
+{
+ return kernel_thread_start_priority(continuation, parameter, -1, new_thread);
+}
+
+/* Separated into helper function so it can be used by THREAD_BASIC_INFO and THREAD_EXTENDED_INFO */
+/* it is assumed that the thread is locked by the caller */
+static void
+retrieve_thread_basic_info(thread_t thread, thread_basic_info_t basic_info)
+{
+ int state, flags;
+
+ /* fill in info */
+
+ thread_read_times(thread, &basic_info->user_time,
+ &basic_info->system_time);
+
+ /*
+ * Update lazy-evaluated scheduler info because someone wants it.
+ */
+ if (SCHED(can_update_priority)(thread))
+ SCHED(update_priority)(thread);
+
+ basic_info->sleep_time = 0;
+
+ /*
+ * To calculate cpu_usage, first correct for timer rate,
+ * then for 5/8 ageing. The correction factor [3/5] is
+ * (1/(5/8) - 1).
+ */
+ basic_info->cpu_usage = 0;
+#if defined(CONFIG_SCHED_TIMESHARE_CORE)
+ if (sched_tick_interval) {
+ basic_info->cpu_usage = (integer_t)(((uint64_t)thread->cpu_usage
+ * TH_USAGE_SCALE) / sched_tick_interval);
+ basic_info->cpu_usage = (basic_info->cpu_usage * 3) / 5;
+ }
+#endif
+
+ if (basic_info->cpu_usage > TH_USAGE_SCALE)
+ basic_info->cpu_usage = TH_USAGE_SCALE;
+
+ basic_info->policy = ((thread->sched_mode == TH_MODE_TIMESHARE)?
+ POLICY_TIMESHARE: POLICY_RR);
+
+ flags = 0;
+ if (thread->options & TH_OPT_IDLE_THREAD)
+ flags |= TH_FLAGS_IDLE;
+
+ if (thread->options & TH_OPT_GLOBAL_FORCED_IDLE) {
+ flags |= TH_FLAGS_GLOBAL_FORCED_IDLE;
+ }
+
+ if (!thread->kernel_stack)
+ flags |= TH_FLAGS_SWAPPED;
+
+ state = 0;
+ if (thread->state & TH_TERMINATE)
+ state = TH_STATE_HALTED;
+ else
+ if (thread->state & TH_RUN)
+ state = TH_STATE_RUNNING;
+ else
+ if (thread->state & TH_UNINT)
+ state = TH_STATE_UNINTERRUPTIBLE;
+ else
+ if (thread->state & TH_SUSP)
+ state = TH_STATE_STOPPED;
+ else
+ if (thread->state & TH_WAIT)
+ state = TH_STATE_WAITING;
+
+ basic_info->run_state = state;
+ basic_info->flags = flags;
+
+ basic_info->suspend_count = thread->user_stop_count;
+
+ return;
+}
+
+kern_return_t
+thread_info_internal(
+ thread_t thread,
+ thread_flavor_t flavor,
+ thread_info_t thread_info_out, /* ptr to OUT array */
+ mach_msg_type_number_t *thread_info_count) /*IN/OUT*/
+{
+ spl_t s;
+
+ if (thread == THREAD_NULL)
+ return (KERN_INVALID_ARGUMENT);
+
+ if (flavor == THREAD_BASIC_INFO) {
+
+ if (*thread_info_count < THREAD_BASIC_INFO_COUNT)
+ return (KERN_INVALID_ARGUMENT);
+
+ s = splsched();
+ thread_lock(thread);
+
+ retrieve_thread_basic_info(thread, (thread_basic_info_t) thread_info_out);
+
+ thread_unlock(thread);
+ splx(s);
+
+ *thread_info_count = THREAD_BASIC_INFO_COUNT;
+
+ return (KERN_SUCCESS);
+ }
+ else
+ if (flavor == THREAD_IDENTIFIER_INFO) {
+ thread_identifier_info_t identifier_info;
+
+ if (*thread_info_count < THREAD_IDENTIFIER_INFO_COUNT)
+ return (KERN_INVALID_ARGUMENT);
+
+ identifier_info = (thread_identifier_info_t) thread_info_out;
+
+ s = splsched();
+ thread_lock(thread);
+
+ identifier_info->thread_id = thread->thread_id;
+ identifier_info->thread_handle = thread->machine.cthread_self;
+ identifier_info->dispatch_qaddr = thread_dispatchqaddr(thread);
+
+ thread_unlock(thread);
+ splx(s);
+ return KERN_SUCCESS;
+ }
+ else
+ if (flavor == THREAD_SCHED_TIMESHARE_INFO) {
+ policy_timeshare_info_t ts_info;
+
+ if (*thread_info_count < POLICY_TIMESHARE_INFO_COUNT)
+ return (KERN_INVALID_ARGUMENT);
+
+ ts_info = (policy_timeshare_info_t)thread_info_out;
+
+ s = splsched();
+ thread_lock(thread);
+
+ if (thread->sched_mode != TH_MODE_TIMESHARE) {
+ thread_unlock(thread);
+ splx(s);
+ return (KERN_INVALID_POLICY);
+ }
+
+ ts_info->depressed = (thread->sched_flags & TH_SFLAG_DEPRESSED_MASK) != 0;
+ if (ts_info->depressed) {
+ ts_info->base_priority = DEPRESSPRI;
+ ts_info->depress_priority = thread->base_pri;
+ }
+ else {
+ ts_info->base_priority = thread->base_pri;
+ ts_info->depress_priority = -1;
+ }
+
+ ts_info->cur_priority = thread->sched_pri;
+ ts_info->max_priority = thread->max_priority;
+
+ thread_unlock(thread);
+ splx(s);
+
+ *thread_info_count = POLICY_TIMESHARE_INFO_COUNT;
+
+ return (KERN_SUCCESS);
+ }
+ else
+ if (flavor == THREAD_SCHED_FIFO_INFO) {
+ if (*thread_info_count < POLICY_FIFO_INFO_COUNT)
+ return (KERN_INVALID_ARGUMENT);
+
+ return (KERN_INVALID_POLICY);
+ }
+ else
+ if (flavor == THREAD_SCHED_RR_INFO) {
+ policy_rr_info_t rr_info;
+ uint32_t quantum_time;
+ uint64_t quantum_ns;
+
+ if (*thread_info_count < POLICY_RR_INFO_COUNT)
+ return (KERN_INVALID_ARGUMENT);
+
+ rr_info = (policy_rr_info_t) thread_info_out;
+
+ s = splsched();
+ thread_lock(thread);
+
+ if (thread->sched_mode == TH_MODE_TIMESHARE) {
+ thread_unlock(thread);
+ splx(s);
+
+ return (KERN_INVALID_POLICY);
+ }
+
+ rr_info->depressed = (thread->sched_flags & TH_SFLAG_DEPRESSED_MASK) != 0;
+ if (rr_info->depressed) {
+ rr_info->base_priority = DEPRESSPRI;
+ rr_info->depress_priority = thread->base_pri;
+ }
+ else {
+ rr_info->base_priority = thread->base_pri;
+ rr_info->depress_priority = -1;
+ }
+
+ quantum_time = SCHED(initial_quantum_size)(THREAD_NULL);
+ absolutetime_to_nanoseconds(quantum_time, &quantum_ns);
+
+ rr_info->max_priority = thread->max_priority;
+ rr_info->quantum = (uint32_t)(quantum_ns / 1000 / 1000);
+
+ thread_unlock(thread);
+ splx(s);
+
+ *thread_info_count = POLICY_RR_INFO_COUNT;
+
+ return (KERN_SUCCESS);
+ }
+ else
+ if (flavor == THREAD_EXTENDED_INFO) {
+ thread_basic_info_data_t basic_info;
+ thread_extended_info_t extended_info = (thread_extended_info_t) thread_info_out;
+
+ if (*thread_info_count < THREAD_EXTENDED_INFO_COUNT) {
+ return (KERN_INVALID_ARGUMENT);
+ }
+
+ s = splsched();
+ thread_lock(thread);
+
+ /* NOTE: This mimics fill_taskthreadinfo(), which is the function used by proc_pidinfo() for
+ * the PROC_PIDTHREADINFO flavor (which can't be used on corpses)
+ */
+ retrieve_thread_basic_info(thread, &basic_info);
+ extended_info->pth_user_time = ((basic_info.user_time.seconds * (integer_t)NSEC_PER_SEC) + (basic_info.user_time.microseconds * (integer_t)NSEC_PER_USEC));
+ extended_info->pth_system_time = ((basic_info.system_time.seconds * (integer_t)NSEC_PER_SEC) + (basic_info.system_time.microseconds * (integer_t)NSEC_PER_USEC));
+
+ extended_info->pth_cpu_usage = basic_info.cpu_usage;
+ extended_info->pth_policy = basic_info.policy;
+ extended_info->pth_run_state = basic_info.run_state;
+ extended_info->pth_flags = basic_info.flags;
+ extended_info->pth_sleep_time = basic_info.sleep_time;
+ extended_info->pth_curpri = thread->sched_pri;
+ extended_info->pth_priority = thread->base_pri;
+ extended_info->pth_maxpriority = thread->max_priority;
+
+ bsd_getthreadname(thread->uthread,extended_info->pth_name);
+
+ thread_unlock(thread);
+ splx(s);
+
+ *thread_info_count = THREAD_EXTENDED_INFO_COUNT;
+
+ return (KERN_SUCCESS);
+ }
+ else
+ if (flavor == THREAD_DEBUG_INFO_INTERNAL) {
+#if DEVELOPMENT || DEBUG
+ thread_debug_info_internal_t dbg_info;
+ if (*thread_info_count < THREAD_DEBUG_INFO_INTERNAL_COUNT)
+ return (KERN_NOT_SUPPORTED);
+
+ if (thread_info_out == NULL)
+ return (KERN_INVALID_ARGUMENT);
+
+ dbg_info = (thread_debug_info_internal_t) thread_info_out;
+ dbg_info->page_creation_count = thread->t_page_creation_count;
+
+ *thread_info_count = THREAD_DEBUG_INFO_INTERNAL_COUNT;
+ return (KERN_SUCCESS);
+#endif /* DEVELOPMENT || DEBUG */
+ return (KERN_NOT_SUPPORTED);
+ }
+
+ return (KERN_INVALID_ARGUMENT);
+}
+
+void
+thread_read_times(
+ thread_t thread,
+ time_value_t *user_time,
+ time_value_t *system_time)
+{
+ clock_sec_t secs;
+ clock_usec_t usecs;
+ uint64_t tval_user, tval_system;
+
+ tval_user = timer_grab(&thread->user_timer);
+ tval_system = timer_grab(&thread->system_timer);
+
+ if (thread->precise_user_kernel_time) {
+ absolutetime_to_microtime(tval_user, &secs, &usecs);
+ user_time->seconds = (typeof(user_time->seconds))secs;
+ user_time->microseconds = usecs;
+
+ absolutetime_to_microtime(tval_system, &secs, &usecs);
+ system_time->seconds = (typeof(system_time->seconds))secs;
+ system_time->microseconds = usecs;
+ } else {
+ /* system_timer may represent either sys or user */
+ tval_user += tval_system;
+ absolutetime_to_microtime(tval_user, &secs, &usecs);
+ user_time->seconds = (typeof(user_time->seconds))secs;
+ user_time->microseconds = usecs;
+
+ system_time->seconds = 0;
+ system_time->microseconds = 0;
+ }
+}
+
+uint64_t thread_get_runtime_self(void)
+{
+ boolean_t interrupt_state;
+ uint64_t runtime;
+ thread_t thread = NULL;
+ processor_t processor = NULL;
+
+ thread = current_thread();
+
+ /* Not interrupt safe, as the scheduler may otherwise update timer values underneath us */
+ interrupt_state = ml_set_interrupts_enabled(FALSE);
+ processor = current_processor();
+ timer_switch(PROCESSOR_DATA(processor, thread_timer), mach_absolute_time(), PROCESSOR_DATA(processor, thread_timer));
+ runtime = (timer_grab(&thread->user_timer) + timer_grab(&thread->system_timer));
+ ml_set_interrupts_enabled(interrupt_state);
+
+ return runtime;
+}
+
+kern_return_t
+thread_assign(
+ __unused thread_t thread,
+ __unused processor_set_t new_pset)
+{
+ return (KERN_FAILURE);
+}
+
+/*
+ * thread_assign_default:
+ *
+ * Special version of thread_assign for assigning threads to default
+ * processor set.
+ */
+kern_return_t
+thread_assign_default(
+ thread_t thread)
+{
+ return (thread_assign(thread, &pset0));
+}
+
+/*
+ * thread_get_assignment
+ *
+ * Return current assignment for this thread.
+ */
+kern_return_t
+thread_get_assignment(
+ thread_t thread,
+ processor_set_t *pset)
+{
+ if (thread == NULL)
+ return (KERN_INVALID_ARGUMENT);
+
+ *pset = &pset0;
+
+ return (KERN_SUCCESS);
+}
+
+/*
+ * thread_wire_internal:
+ *
+ * Specify that the target thread must always be able
+ * to run and to allocate memory.
+ */
+kern_return_t
+thread_wire_internal(
+ host_priv_t host_priv,
+ thread_t thread,
+ boolean_t wired,
+ boolean_t *prev_state)
+{
+ if (host_priv == NULL || thread != current_thread())
+ return (KERN_INVALID_ARGUMENT);
+
+ assert(host_priv == &realhost);
+
+ if (prev_state)
+ *prev_state = (thread->options & TH_OPT_VMPRIV) != 0;
+
+ if (wired) {
+ if (!(thread->options & TH_OPT_VMPRIV))
+ vm_page_free_reserve(1); /* XXX */
+ thread->options |= TH_OPT_VMPRIV;
+ }
+ else {
+ if (thread->options & TH_OPT_VMPRIV)
+ vm_page_free_reserve(-1); /* XXX */
+ thread->options &= ~TH_OPT_VMPRIV;
+ }
+
+ return (KERN_SUCCESS);
+}
+
+
+/*
+ * thread_wire:
+ *
+ * User-api wrapper for thread_wire_internal()
+ */
+kern_return_t
+thread_wire(
+ host_priv_t host_priv,
+ thread_t thread,
+ boolean_t wired)
+{
+ return (thread_wire_internal(host_priv, thread, wired, NULL));
+}
+
+
+boolean_t
+is_vm_privileged(void)
+{
+ return current_thread()->options & TH_OPT_VMPRIV ? TRUE : FALSE;
+}
+
+boolean_t
+set_vm_privilege(boolean_t privileged)
+{
+ boolean_t was_vmpriv;
+
+ if (current_thread()->options & TH_OPT_VMPRIV)
+ was_vmpriv = TRUE;
+ else
+ was_vmpriv = FALSE;
+
+ if (privileged != FALSE)
+ current_thread()->options |= TH_OPT_VMPRIV;
+ else
+ current_thread()->options &= ~TH_OPT_VMPRIV;
+
+ return (was_vmpriv);
+}
+
+void
+set_thread_rwlock_boost(void)
+{
+ current_thread()->rwlock_count++;
+}
+
+void
+clear_thread_rwlock_boost(void)
+{
+ thread_t thread = current_thread();
+
+ if ((thread->rwlock_count-- == 1) && (thread->sched_flags & TH_SFLAG_RW_PROMOTED)) {
+
+ lck_rw_clear_promotion(thread);
+ }
+}
+
+
+/*
+ * XXX assuming current thread only, for now...
+ */
+void
+thread_guard_violation(thread_t thread,
+ mach_exception_data_type_t code, mach_exception_data_type_t subcode)
+{
+ assert(thread == current_thread());
+ assert(thread->task != kernel_task);
+
+ spl_t s = splsched();
+ /*
+ * Use the saved state area of the thread structure
+ * to store all info required to handle the AST when
+ * returning to userspace
+ */
+ assert(EXC_GUARD_DECODE_GUARD_TYPE(code));
+ thread->guard_exc_info.code = code;
+ thread->guard_exc_info.subcode = subcode;
+ thread_ast_set(thread, AST_GUARD);
+ ast_propagate(thread);
+
+ splx(s);
+}
+
+/*
+ * guard_ast:
+ *
+ * Handle AST_GUARD for a thread. This routine looks at the
+ * state saved in the thread structure to determine the cause
+ * of this exception. Based on this value, it invokes the
+ * appropriate routine which determines other exception related
+ * info and raises the exception.
+ */
+void
+guard_ast(thread_t t)
+{
+ const mach_exception_data_type_t
+ code = t->guard_exc_info.code,
+ subcode = t->guard_exc_info.subcode;
+
+ switch (EXC_GUARD_DECODE_GUARD_TYPE(code)) {
+ case GUARD_TYPE_MACH_PORT:
+ mach_port_guard_ast(t, code, subcode);
+ break;
+ case GUARD_TYPE_FD:
+ fd_guard_ast(t, code, subcode);
+ break;
+#if CONFIG_VNGUARD
+ case GUARD_TYPE_VN:
+ vn_guard_ast(t, code, subcode);
+ break;
+#endif
+ default:
+ panic("guard_exc_info %llx %llx", code, subcode);
+ }
+}
+
+static void
+thread_cputime_callback(int warning, __unused const void *arg0, __unused const void *arg1)
+{
+ if (warning == LEDGER_WARNING_ROSE_ABOVE) {
+#if CONFIG_TELEMETRY
+ /*
+ * This thread is in danger of violating the CPU usage monitor. Enable telemetry
+ * on the entire task so there are micro-stackshots available if and when
+ * EXC_RESOURCE is triggered. We could have chosen to enable micro-stackshots
+ * for this thread only; but now that this task is suspect, knowing what all of
+ * its threads are up to will be useful.
+ */
+ telemetry_task_ctl(current_task(), TF_CPUMON_WARNING, 1);
+#endif
+ return;
+ }
+
+#if CONFIG_TELEMETRY
+ /*
+ * If the balance has dipped below the warning level (LEDGER_WARNING_DIPPED_BELOW) or
+ * exceeded the limit, turn telemetry off for the task.
+ */
+ telemetry_task_ctl(current_task(), TF_CPUMON_WARNING, 0);
+#endif
+
+ if (warning == 0) {
+ SENDING_NOTIFICATION__THIS_THREAD_IS_CONSUMING_TOO_MUCH_CPU();
+ }
+}
+
+void __attribute__((noinline))
+SENDING_NOTIFICATION__THIS_THREAD_IS_CONSUMING_TOO_MUCH_CPU(void)
+{
+ int pid = 0;
+ task_t task = current_task();
+ thread_t thread = current_thread();
+ uint64_t tid = thread->thread_id;
+ const char *procname = "unknown";
+ time_value_t thread_total_time = {0, 0};
+ time_value_t thread_system_time;
+ time_value_t thread_user_time;
+ int action;
+ uint8_t percentage;
+ uint32_t usage_percent = 0;
+ uint32_t interval_sec;
+ uint64_t interval_ns;
+ uint64_t balance_ns;
+ boolean_t fatal = FALSE;
+ boolean_t send_exc_resource = TRUE; /* in addition to RESOURCE_NOTIFY */
+ kern_return_t kr;
+
+#ifdef EXC_RESOURCE_MONITORS
+ mach_exception_data_type_t code[EXCEPTION_CODE_MAX];
+#endif /* EXC_RESOURCE_MONITORS */
+ struct ledger_entry_info lei;
+
+ assert(thread->t_threadledger != LEDGER_NULL);
+
+ /*
+ * Extract the fatal bit and suspend the monitor (which clears the bit).
+ */
+ task_lock(task);
+ if (task->rusage_cpu_flags & TASK_RUSECPU_FLAGS_FATAL_CPUMON) {
+ fatal = TRUE;
+ send_exc_resource = TRUE;
+ }
+ /* Only one thread can be here at a time. Whichever makes it through
+ first will successfully suspend the monitor and proceed to send the
+ notification. Other threads will get an error trying to suspend the
+ monitor and give up on sending the notification. In the first release,
+ the monitor won't be resumed for a number of seconds, but we may
+ eventually need to handle low-latency resume.
+ */
+ kr = task_suspend_cpumon(task);
+ task_unlock(task);
+ if (kr == KERN_INVALID_ARGUMENT) return;
+
+#ifdef MACH_BSD
+ pid = proc_selfpid();
+ if (task->bsd_info != NULL) {
+ procname = proc_name_address(task->bsd_info);
+ }
+#endif
+
+ thread_get_cpulimit(&action, &percentage, &interval_ns);
+
+ interval_sec = (uint32_t)(interval_ns / NSEC_PER_SEC);
+
+ thread_read_times(thread, &thread_user_time, &thread_system_time);
+ time_value_add(&thread_total_time, &thread_user_time);
+ time_value_add(&thread_total_time, &thread_system_time);
+ ledger_get_entry_info(thread->t_threadledger, thread_ledgers.cpu_time, &lei);
+
+ /* credit/debit/balance/limit are in absolute time units;
+ the refill info is in nanoseconds. */
+ absolutetime_to_nanoseconds(lei.lei_balance, &balance_ns);
+ if (lei.lei_last_refill > 0) {
+ usage_percent = (uint32_t)((balance_ns*100ULL) / lei.lei_last_refill);
+ }
+
+ /* TODO: show task total runtime (via TASK_ABSOLUTETIME_INFO)? */
+ printf("process %s[%d] thread %llu caught burning CPU! "
+ "It used more than %d%% CPU over %u seconds "
+ "(actual recent usage: %d%% over ~%llu seconds). "
+ "Thread lifetime cpu usage %d.%06ds, (%d.%06d user, %d.%06d sys) "
+ "ledger balance: %lld mabs credit: %lld mabs debit: %lld mabs "
+ "limit: %llu mabs period: %llu ns last refill: %llu ns%s.\n",
+ procname, pid, tid,
+ percentage, interval_sec,
+ usage_percent,
+ (lei.lei_last_refill + NSEC_PER_SEC/2) / NSEC_PER_SEC,
+ thread_total_time.seconds, thread_total_time.microseconds,
+ thread_user_time.seconds, thread_user_time.microseconds,
+ thread_system_time.seconds,thread_system_time.microseconds,
+ lei.lei_balance, lei.lei_credit, lei.lei_debit,
+ lei.lei_limit, lei.lei_refill_period, lei.lei_last_refill,
+ (fatal ? " [fatal violation]" : ""));
+
+ /*
+ For now, send RESOURCE_NOTIFY in parallel with EXC_RESOURCE. Once
+ we have logging parity, we will stop sending EXC_RESOURCE (24508922).
+ */
+
+ /* RESOURCE_NOTIFY MIG specifies nanoseconds of CPU time */
+ lei.lei_balance = balance_ns;
+ absolutetime_to_nanoseconds(lei.lei_limit, &lei.lei_limit);
+ trace_resource_violation(RMON_CPUUSAGE_VIOLATED, &lei);
+ kr = send_resource_violation(send_cpu_usage_violation, task, &lei,
+ fatal ? kRNFatalLimitFlag : 0);
+ if (kr) {
+ printf("send_resource_violation(CPU usage, ...): error %#x\n", kr);
+ }
+
+#ifdef EXC_RESOURCE_MONITORS
+ if (send_exc_resource) {
+ if (disable_exc_resource) {
+ printf("process %s[%d] thread %llu caught burning CPU! "
+ "EXC_RESOURCE%s supressed by a boot-arg\n",
+ procname, pid, tid, fatal ? " (and termination)" : "");
+ return;
+ }
+
+ if (audio_active) {
+ printf("process %s[%d] thread %llu caught burning CPU! "
+ "EXC_RESOURCE & termination supressed due to audio playback\n",
+ procname, pid, tid);
+ return;
+ }
+ }
+
+
+ if (send_exc_resource) {
+ code[0] = code[1] = 0;
+ EXC_RESOURCE_ENCODE_TYPE(code[0], RESOURCE_TYPE_CPU);
+ if (fatal) {
+ EXC_RESOURCE_ENCODE_FLAVOR(code[0], FLAVOR_CPU_MONITOR_FATAL);
+ }else {
+ EXC_RESOURCE_ENCODE_FLAVOR(code[0], FLAVOR_CPU_MONITOR);
+ }
+ EXC_RESOURCE_CPUMONITOR_ENCODE_INTERVAL(code[0], interval_sec);
+ EXC_RESOURCE_CPUMONITOR_ENCODE_PERCENTAGE(code[0], percentage);
+ EXC_RESOURCE_CPUMONITOR_ENCODE_PERCENTAGE(code[1], usage_percent);
+ exception_triage(EXC_RESOURCE, code, EXCEPTION_CODE_MAX);
+ }
+#endif /* EXC_RESOURCE_MONITORS */
+
+ if (fatal) {
+#if CONFIG_JETSAM
+ jetsam_on_ledger_cpulimit_exceeded();
+#else
+ task_terminate_internal(task);
+#endif
+ }
+}
+
+void thread_update_io_stats(thread_t thread, int size, int io_flags)
+{
+ int io_tier;
+
+ if (thread->thread_io_stats == NULL || thread->task->task_io_stats == NULL)
+ return;
+
+ if (io_flags & DKIO_READ) {
+ UPDATE_IO_STATS(thread->thread_io_stats->disk_reads, size);
+ UPDATE_IO_STATS_ATOMIC(thread->task->task_io_stats->disk_reads, size);
+ }
+
+ if (io_flags & DKIO_META) {
+ UPDATE_IO_STATS(thread->thread_io_stats->metadata, size);
+ UPDATE_IO_STATS_ATOMIC(thread->task->task_io_stats->metadata, size);
+ }
+
+ if (io_flags & DKIO_PAGING) {
+ UPDATE_IO_STATS(thread->thread_io_stats->paging, size);
+ UPDATE_IO_STATS_ATOMIC(thread->task->task_io_stats->paging, size);
+ }
+
+ io_tier = ((io_flags & DKIO_TIER_MASK) >> DKIO_TIER_SHIFT);
+ assert (io_tier < IO_NUM_PRIORITIES);
+
+ UPDATE_IO_STATS(thread->thread_io_stats->io_priority[io_tier], size);
+ UPDATE_IO_STATS_ATOMIC(thread->task->task_io_stats->io_priority[io_tier], size);
+
+ /* Update Total I/O Counts */
+ UPDATE_IO_STATS(thread->thread_io_stats->total_io, size);
+ UPDATE_IO_STATS_ATOMIC(thread->task->task_io_stats->total_io, size);
+
+ if (!(io_flags & DKIO_READ)) {
+ DTRACE_IO3(physical_writes, struct task *, thread->task, uint32_t, size, int, io_flags);
+ ledger_credit(thread->task->ledger, task_ledgers.physical_writes, size);
+ }
+}
+
+static void
+init_thread_ledgers(void) {
+ ledger_template_t t;
+ int idx;
+
+ assert(thread_ledger_template == NULL);
+
+ if ((t = ledger_template_create("Per-thread ledger")) == NULL)
+ panic("couldn't create thread ledger template");
+
+ if ((idx = ledger_entry_add(t, "cpu_time", "sched", "ns")) < 0) {
+ panic("couldn't create cpu_time entry for thread ledger template");
+ }
+
+ if (ledger_set_callback(t, idx, thread_cputime_callback, NULL, NULL) < 0) {
+ panic("couldn't set thread ledger callback for cpu_time entry");
+ }
+
+ thread_ledgers.cpu_time = idx;
+
+ ledger_template_complete(t);
+ thread_ledger_template = t;
+}
+
+/*
+ * Returns currently applied CPU usage limit, or 0/0 if none is applied.
+ */
+int
+thread_get_cpulimit(int *action, uint8_t *percentage, uint64_t *interval_ns)
+{
+ int64_t abstime = 0;
+ uint64_t limittime = 0;
+ thread_t thread = current_thread();
+
+ *percentage = 0;
+ *interval_ns = 0;
+ *action = 0;
+
+ if (thread->t_threadledger == LEDGER_NULL) {
+ /*
+ * This thread has no per-thread ledger, so it can't possibly
+ * have a CPU limit applied.
+ */
+ return (KERN_SUCCESS);
+ }
+
+ ledger_get_period(thread->t_threadledger, thread_ledgers.cpu_time, interval_ns);
+ ledger_get_limit(thread->t_threadledger, thread_ledgers.cpu_time, &abstime);
+
+ if ((abstime == LEDGER_LIMIT_INFINITY) || (*interval_ns == 0)) {
+ /*
+ * This thread's CPU time ledger has no period or limit; so it
+ * doesn't have a CPU limit applied.
+ */
+ return (KERN_SUCCESS);
+ }
+
+ /*
+ * This calculation is the converse to the one in thread_set_cpulimit().
+ */
+ absolutetime_to_nanoseconds(abstime, &limittime);
+ *percentage = (limittime * 100ULL) / *interval_ns;
+ assert(*percentage <= 100);
+
+ if (thread->options & TH_OPT_PROC_CPULIMIT) {
+ assert((thread->options & TH_OPT_PRVT_CPULIMIT) == 0);
+
+ *action = THREAD_CPULIMIT_BLOCK;
+ } else if (thread->options & TH_OPT_PRVT_CPULIMIT) {
+ assert((thread->options & TH_OPT_PROC_CPULIMIT) == 0);
+
+ *action = THREAD_CPULIMIT_EXCEPTION;
+ } else {
+ *action = THREAD_CPULIMIT_DISABLE;
+ }
+
+ return (KERN_SUCCESS);
+}
+
+/*
+ * Set CPU usage limit on a thread.
+ *
+ * Calling with percentage of 0 will unset the limit for this thread.
+ */
+int
+thread_set_cpulimit(int action, uint8_t percentage, uint64_t interval_ns)
+{
+ thread_t thread = current_thread();
+ ledger_t l;
+ uint64_t limittime = 0;
+ uint64_t abstime = 0;
+
+ assert(percentage <= 100);
+
+ if (action == THREAD_CPULIMIT_DISABLE) {
+ /*
+ * Remove CPU limit, if any exists.
+ */
+ if (thread->t_threadledger != LEDGER_NULL) {
+ l = thread->t_threadledger;
+ ledger_set_limit(l, thread_ledgers.cpu_time, LEDGER_LIMIT_INFINITY, 0);
+ ledger_set_action(l, thread_ledgers.cpu_time, LEDGER_ACTION_IGNORE);
+ thread->options &= ~(TH_OPT_PROC_CPULIMIT | TH_OPT_PRVT_CPULIMIT);
+ }
+
+ return (0);
+ }
+
+ if (interval_ns < MINIMUM_CPULIMIT_INTERVAL_MS * NSEC_PER_MSEC) {
+ return (KERN_INVALID_ARGUMENT);
+ }
+
+ l = thread->t_threadledger;
+ if (l == LEDGER_NULL) {
+ /*
+ * This thread doesn't yet have a per-thread ledger; so create one with the CPU time entry active.
+ */
+ if ((l = ledger_instantiate(thread_ledger_template, LEDGER_CREATE_INACTIVE_ENTRIES)) == LEDGER_NULL)
+ return (KERN_RESOURCE_SHORTAGE);
+
+ /*
+ * We are the first to create this thread's ledger, so only activate our entry.
+ */
+ ledger_entry_setactive(l, thread_ledgers.cpu_time);
+ thread->t_threadledger = l;
+ }
+
+ /*
+ * The limit is specified as a percentage of CPU over an interval in nanoseconds.
+ * Calculate the amount of CPU time that the thread needs to consume in order to hit the limit.
+ */
+ limittime = (interval_ns * percentage) / 100;
+ nanoseconds_to_absolutetime(limittime, &abstime);
+ ledger_set_limit(l, thread_ledgers.cpu_time, abstime, cpumon_ustackshots_trigger_pct);
+ /*
+ * Refill the thread's allotted CPU time every interval_ns nanoseconds.
+ */
+ ledger_set_period(l, thread_ledgers.cpu_time, interval_ns);
+
+ if (action == THREAD_CPULIMIT_EXCEPTION) {
+ /*
+ * We don't support programming the CPU usage monitor on a task if any of its
+ * threads have a per-thread blocking CPU limit configured.
+ */
+ if (thread->options & TH_OPT_PRVT_CPULIMIT) {
+ panic("CPU usage monitor activated, but blocking thread limit exists");
+ }
+
+ /*
+ * Make a note that this thread's CPU limit is being used for the task-wide CPU
+ * usage monitor. We don't have to arm the callback which will trigger the
+ * exception, because that was done for us in ledger_instantiate (because the
+ * ledger template used has a default callback).
+ */
+ thread->options |= TH_OPT_PROC_CPULIMIT;
+ } else {
+ /*
+ * We deliberately override any CPU limit imposed by a task-wide limit (eg
+ * CPU usage monitor).
+ */
+ thread->options &= ~TH_OPT_PROC_CPULIMIT;