2 * Copyright (c) 2000-2016 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
29 * @OSF_FREE_COPYRIGHT@
32 * Mach Operating System
33 * Copyright (c) 1991,1990,1989,1988 Carnegie Mellon University
34 * All Rights Reserved.
36 * Permission to use, copy, modify and distribute this software and its
37 * documentation is hereby granted, provided that both the copyright
38 * notice and this permission notice appear in all copies of the
39 * software, derivative works or modified versions, and any portions
40 * thereof, and that both notices appear in supporting documentation.
42 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
43 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
44 * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
46 * Carnegie Mellon requests users of this software to return to
48 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
49 * School of Computer Science
50 * Carnegie Mellon University
51 * Pittsburgh PA 15213-3890
53 * any improvements or extensions that they make and grant Carnegie Mellon
54 * the rights to redistribute these changes.
58 * Author: Avadis Tevanian, Jr., Michael Wayne Young, David Golub,
61 * Task management primitives implementation.
64 * Copyright (c) 1993 The University of Utah and
65 * the Computer Systems Laboratory (CSL). All rights reserved.
67 * Permission to use, copy, modify and distribute this software and its
68 * documentation is hereby granted, provided that both the copyright
69 * notice and this permission notice appear in all copies of the
70 * software, derivative works or modified versions, and any portions
71 * thereof, and that both notices appear in supporting documentation.
73 * THE UNIVERSITY OF UTAH AND CSL ALLOW FREE USE OF THIS SOFTWARE IN ITS "AS
74 * IS" CONDITION. THE UNIVERSITY OF UTAH AND CSL DISCLAIM ANY LIABILITY OF
75 * ANY KIND FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
77 * CSL requests users of this software to return to csl-dist@cs.utah.edu any
78 * improvements that they make and grant CSL redistribution rights.
82 * NOTICE: This file was modified by McAfee Research in 2004 to introduce
83 * support for mandatory and extensible security protections. This notice
84 * is included in support of clause 2.2 (b) of the Apple Public License,
86 * Copyright (c) 2005 SPARTA, Inc.
89 #include <mach/mach_types.h>
90 #include <mach/boolean.h>
91 #include <mach/host_priv.h>
92 #include <mach/machine/vm_types.h>
93 #include <mach/vm_param.h>
94 #include <mach/mach_vm.h>
95 #include <mach/semaphore.h>
96 #include <mach/task_info.h>
97 #include <mach/task_inspect.h>
98 #include <mach/task_special_ports.h>
101 #include <ipc/ipc_importance.h>
102 #include <ipc/ipc_types.h>
103 #include <ipc/ipc_space.h>
104 #include <ipc/ipc_entry.h>
105 #include <ipc/ipc_hash.h>
107 #include <kern/kern_types.h>
108 #include <kern/mach_param.h>
109 #include <kern/misc_protos.h>
110 #include <kern/task.h>
111 #include <kern/thread.h>
112 #include <kern/coalition.h>
113 #include <kern/zalloc.h>
114 #include <kern/kalloc.h>
115 #include <kern/kern_cdata.h>
116 #include <kern/processor.h>
117 #include <kern/sched_prim.h> /* for thread_wakeup */
118 #include <kern/ipc_tt.h>
119 #include <kern/host.h>
120 #include <kern/clock.h>
121 #include <kern/timer.h>
122 #include <kern/assert.h>
123 #include <kern/sync_lock.h>
124 #include <kern/affinity.h>
125 #include <kern/exc_resource.h>
126 #include <kern/machine.h>
127 #include <kern/policy_internal.h>
129 #include <corpses/task_corpse.h>
131 #include <kern/telemetry.h>
135 #include <kern/monotonic.h>
136 #include <machine/monotonic.h>
137 #endif /* MONOTONIC */
142 #include <vm/vm_map.h>
143 #include <vm/vm_kern.h> /* for kernel_map, ipc_kernel_map */
144 #include <vm/vm_pageout.h>
145 #include <vm/vm_protos.h>
146 #include <vm/vm_purgeable_internal.h>
148 #include <sys/resource.h>
149 #include <sys/signalvar.h> /* for coredump */
152 * Exported interfaces
155 #include <mach/task_server.h>
156 #include <mach/mach_host_server.h>
157 #include <mach/host_security_server.h>
158 #include <mach/mach_port_server.h>
160 #include <vm/vm_shared_region.h>
162 #include <libkern/OSDebug.h>
163 #include <libkern/OSAtomic.h>
164 #include <libkern/section_keywords.h>
167 #include <atm/atm_internal.h>
170 #include <kern/sfi.h> /* picks up ledger.h */
173 #include <security/mac_mach_internal.h>
177 extern int kpc_force_all_ctrs(task_t
, int);
182 lck_attr_t task_lck_attr
;
183 lck_grp_t task_lck_grp
;
184 lck_grp_attr_t task_lck_grp_attr
;
186 extern int exc_via_corpse_forking
;
187 extern int corpse_for_fatal_memkill
;
188 extern boolean_t
proc_send_synchronous_EXC_RESOURCE(void *p
);
190 /* Flag set by core audio when audio is playing. Used to stifle EXC_RESOURCE generation when active. */
191 int audio_active
= 0;
193 zinfo_usage_store_t tasks_tkm_private
;
194 zinfo_usage_store_t tasks_tkm_shared
;
196 /* A container to accumulate statistics for expired tasks */
197 expired_task_statistics_t dead_task_statistics
;
198 lck_spin_t dead_task_statistics_lock
;
200 ledger_template_t task_ledger_template
= NULL
;
202 SECURITY_READ_ONLY_LATE(struct _task_ledger_indices
) task_ledgers
__attribute__((used
)) =
210 .alternate_accounting
= -1,
211 .alternate_accounting_compressed
= -1,
213 .phys_footprint
= -1,
214 .internal_compressed
= -1,
215 .purgeable_volatile
= -1,
216 .purgeable_nonvolatile
= -1,
217 .purgeable_volatile_compressed
= -1,
218 .purgeable_nonvolatile_compressed
= -1,
219 .network_volatile
= -1,
220 .network_nonvolatile
= -1,
221 .network_volatile_compressed
= -1,
222 .network_nonvolatile_compressed
= -1,
223 .platform_idle_wakeups
= -1,
224 .interrupt_wakeups
= -1,
226 .sfi_wait_times
= { 0 /* initialized at runtime */},
227 #endif /* !CONFIG_EMBEDDED */
228 .cpu_time_billed_to_me
= -1,
229 .cpu_time_billed_to_others
= -1,
230 .physical_writes
= -1,
231 .logical_writes
= -1,
232 .energy_billed_to_me
= -1,
233 .energy_billed_to_others
= -1
236 /* System sleep state */
237 boolean_t tasks_suspend_state
;
240 void init_task_ledgers(void);
241 void task_footprint_exceeded(int warning
, __unused
const void *param0
, __unused
const void *param1
);
242 void task_wakeups_rate_exceeded(int warning
, __unused
const void *param0
, __unused
const void *param1
);
243 void task_io_rate_exceeded(int warning
, const void *param0
, __unused
const void *param1
);
244 void __attribute__((noinline
)) SENDING_NOTIFICATION__THIS_PROCESS_IS_CAUSING_TOO_MANY_WAKEUPS(void);
245 void __attribute__((noinline
)) PROC_CROSSED_HIGH_WATERMARK__SEND_EXC_RESOURCE_AND_SUSPEND(int max_footprint_mb
, boolean_t is_fatal
);
246 void __attribute__((noinline
)) SENDING_NOTIFICATION__THIS_PROCESS_IS_CAUSING_TOO_MUCH_IO(int flavor
);
248 kern_return_t
task_suspend_internal(task_t
);
249 kern_return_t
task_resume_internal(task_t
);
250 static kern_return_t
task_start_halt_locked(task_t task
, boolean_t should_mark_corpse
);
252 extern kern_return_t
iokit_task_terminate(task_t task
);
254 extern kern_return_t
exception_deliver(thread_t
, exception_type_t
, mach_exception_data_t
, mach_msg_type_number_t
, struct exception_action
*, lck_mtx_t
*);
255 extern void bsd_copythreadname(void *dst_uth
, void *src_uth
);
256 extern kern_return_t
thread_resume(thread_t thread
);
258 // Warn tasks when they hit 80% of their memory limit.
259 #define PHYS_FOOTPRINT_WARNING_LEVEL 80
261 #define TASK_WAKEUPS_MONITOR_DEFAULT_LIMIT 150 /* wakeups per second */
262 #define TASK_WAKEUPS_MONITOR_DEFAULT_INTERVAL 300 /* in seconds. */
265 * Level (in terms of percentage of the limit) at which the wakeups monitor triggers telemetry.
267 * (ie when the task's wakeups rate exceeds 70% of the limit, start taking user
268 * stacktraces, aka micro-stackshots)
270 #define TASK_WAKEUPS_MONITOR_DEFAULT_USTACKSHOTS_TRIGGER 70
272 int task_wakeups_monitor_interval
; /* In seconds. Time period over which wakeups rate is observed */
273 int task_wakeups_monitor_rate
; /* In hz. Maximum allowable wakeups per task before EXC_RESOURCE is sent */
275 int task_wakeups_monitor_ustackshots_trigger_pct
; /* Percentage. Level at which we start gathering telemetry. */
277 int disable_exc_resource
; /* Global override to supress EXC_RESOURCE for resource monitor violations. */
279 ledger_amount_t max_task_footprint
= 0; /* Per-task limit on physical memory consumption in bytes */
280 int max_task_footprint_warning_level
= 0; /* Per-task limit warning percentage */
281 int max_task_footprint_mb
= 0; /* Per-task limit on physical memory consumption in megabytes */
283 /* I/O Monitor Limits */
284 #define IOMON_DEFAULT_LIMIT (20480ull) /* MB of logical/physical I/O */
285 #define IOMON_DEFAULT_INTERVAL (86400ull) /* in seconds */
287 uint64_t task_iomon_limit_mb
; /* Per-task I/O monitor limit in MBs */
288 uint64_t task_iomon_interval_secs
; /* Per-task I/O monitor interval in secs */
290 #define IO_TELEMETRY_DEFAULT_LIMIT (10ll * 1024ll * 1024ll)
291 int64_t io_telemetry_limit
; /* Threshold to take a microstackshot (0 indicated I/O telemetry is turned off) */
292 int64_t global_logical_writes_count
= 0; /* Global count for logical writes */
293 static boolean_t
global_update_logical_writes(int64_t);
295 #define TASK_MAX_THREAD_LIMIT 256
298 int pmap_ledgers_panic
= 1;
299 int pmap_ledgers_panic_leeway
= 3;
300 #endif /* MACH_ASSERT */
302 int task_max
= CONFIG_TASK_MAX
; /* Max number of tasks */
305 int hwm_user_cores
= 0; /* high watermark violations generate user core files */
309 extern void proc_getexecutableuuid(void *, unsigned char *, unsigned long);
310 extern int proc_pid(struct proc
*p
);
311 extern int proc_selfpid(void);
312 extern struct proc
*current_proc(void);
313 extern char *proc_name_address(struct proc
*p
);
314 extern uint64_t get_dispatchqueue_offset_from_proc(void *);
315 extern int kevent_proc_copy_uptrs(void *proc
, uint64_t *buf
, int bufsize
);
316 extern void workq_proc_suspended(struct proc
*p
);
317 extern void workq_proc_resumed(struct proc
*p
);
319 #if CONFIG_MEMORYSTATUS
320 extern void proc_memstat_terminated(struct proc
* p
, boolean_t set
);
321 extern void memorystatus_on_ledger_footprint_exceeded(int warning
, boolean_t memlimit_is_active
, boolean_t memlimit_is_fatal
);
322 extern void memorystatus_log_exception(const int max_footprint_mb
, boolean_t memlimit_is_active
, boolean_t memlimit_is_fatal
);
323 extern boolean_t
memorystatus_allowed_vm_map_fork(task_t task
);
325 #if DEVELOPMENT || DEBUG
326 extern void memorystatus_abort_vm_map_fork(task_t
);
329 #endif /* CONFIG_MEMORYSTATUS */
331 #endif /* MACH_BSD */
333 #if DEVELOPMENT || DEBUG
334 int exc_resource_threads_enabled
;
335 #endif /* DEVELOPMENT || DEBUG */
337 #if (DEVELOPMENT || DEBUG) && TASK_EXC_GUARD_DELIVER_CORPSE
338 uint32_t task_exc_guard_default
= TASK_EXC_GUARD_MP_DELIVER
| TASK_EXC_GUARD_MP_CORPSE
|
339 TASK_EXC_GUARD_VM_DELIVER
| TASK_EXC_GUARD_VM_CORPSE
;
341 uint32_t task_exc_guard_default
= 0;
346 static void task_hold_locked(task_t task
);
347 static void task_wait_locked(task_t task
, boolean_t until_not_runnable
);
348 static void task_release_locked(task_t task
);
350 static void task_synchronizer_destroy_all(task_t task
);
357 boolean_t is_64bit_data
)
359 #if defined(__i386__) || defined(__x86_64__) || defined(__arm64__)
361 #endif /* defined(__i386__) || defined(__x86_64__) || defined(__arm64__) */
366 * Switching to/from 64-bit address spaces
369 if (!task_has_64Bit_addr(task
)) {
370 task_set_64Bit_addr(task
);
373 if (task_has_64Bit_addr(task
)) {
374 task_clear_64Bit_addr(task
);
379 * Switching to/from 64-bit register state.
382 if (task_has_64Bit_data(task
))
385 task_set_64Bit_data(task
);
387 if ( !task_has_64Bit_data(task
))
390 task_clear_64Bit_data(task
);
393 /* FIXME: On x86, the thread save state flavor can diverge from the
394 * task's 64-bit feature flag due to the 32-bit/64-bit register save
395 * state dichotomy. Since we can be pre-empted in this interval,
396 * certain routines may observe the thread as being in an inconsistent
397 * state with respect to its task's 64-bitness.
400 #if defined(__x86_64__) || defined(__arm64__)
401 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
402 thread_mtx_lock(thread
);
403 machine_thread_switch_addrmode(thread
);
404 thread_mtx_unlock(thread
);
406 #if defined(__arm64__)
407 /* specifically, if running on H9 */
408 if (thread
== current_thread()) {
411 spl_t spl
= splsched();
413 * This call tell that the current thread changed it's 32bitness.
414 * Other thread were no more on core when 32bitness was changed,
415 * but current_thread() is on core and the previous call to
416 * machine_thread_going_on_core() gave 32bitness which is now wrong.
418 * This is needed for bring-up, a different callback should be used
421 * TODO: Remove this callout when we no longer support 32-bit code on H9
424 urgency
= thread_get_urgency(thread
, &arg1
, &arg2
);
425 machine_thread_going_on_core(thread
, urgency
, 0, 0, mach_approximate_time());
426 thread_unlock(thread
);
429 #endif /* defined(__arm64__) */
431 #endif /* defined(__x86_64__) || defined(__arm64__) */
438 task_get_64bit_data(task_t task
)
440 return task_has_64Bit_data(task
);
444 task_set_platform_binary(
446 boolean_t is_platform
)
450 task
->t_flags
|= TF_PLATFORM
;
452 task
->t_flags
&= ~(TF_PLATFORM
);
458 * Set or clear per-task TF_CA_CLIENT_WI flag according to specified argument.
459 * Returns "false" if flag is already set, and "true" in other cases.
462 task_set_ca_client_wi(
464 boolean_t set_or_clear
)
469 /* Tasks can have only one CA_CLIENT work interval */
470 if (task
->t_flags
& TF_CA_CLIENT_WI
)
473 task
->t_flags
|= TF_CA_CLIENT_WI
;
475 task
->t_flags
&= ~TF_CA_CLIENT_WI
;
484 mach_vm_address_t addr
,
488 task
->all_image_info_addr
= addr
;
489 task
->all_image_info_size
= size
;
494 task_atm_reset(__unused task_t task
) {
497 if (task
->atm_context
!= NULL
) {
498 atm_task_descriptor_destroy(task
->atm_context
);
499 task
->atm_context
= NULL
;
506 task_bank_reset(__unused task_t task
) {
508 if (task
->bank_context
!= NULL
) {
509 bank_task_destroy(task
);
514 * NOTE: This should only be called when the P_LINTRANSIT
515 * flag is set (the proc_trans lock is held) on the
516 * proc associated with the task.
519 task_bank_init(__unused task_t task
) {
521 if (task
->bank_context
!= NULL
) {
522 panic("Task bank init called with non null bank context for task: %p and bank_context: %p", task
, task
->bank_context
);
524 bank_task_initialize(task
);
528 task_set_did_exec_flag(task_t task
)
530 task
->t_procflags
|= TPF_DID_EXEC
;
534 task_clear_exec_copy_flag(task_t task
)
536 task
->t_procflags
&= ~TPF_EXEC_COPY
;
540 * This wait event is t_procflags instead of t_flags because t_flags is volatile
542 * TODO: store the flags in the same place as the event
543 * rdar://problem/28501994
546 task_get_return_wait_event(task_t task
)
548 return (event_t
)&task
->t_procflags
;
552 task_clear_return_wait(task_t task
)
556 task
->t_flags
&= ~TF_LRETURNWAIT
;
558 if (task
->t_flags
& TF_LRETURNWAITER
) {
559 thread_wakeup(task_get_return_wait_event(task
));
560 task
->t_flags
&= ~TF_LRETURNWAITER
;
566 void __attribute__((noreturn
))
567 task_wait_to_return(void)
571 task
= current_task();
574 if (task
->t_flags
& TF_LRETURNWAIT
) {
576 task
->t_flags
|= TF_LRETURNWAITER
;
577 assert_wait(task_get_return_wait_event(task
), THREAD_UNINT
);
580 thread_block(THREAD_CONTINUE_NULL
);
583 } while (task
->t_flags
& TF_LRETURNWAIT
);
590 * Before jumping to userspace and allowing this process to execute any code,
591 * notify any interested parties.
593 mac_proc_notify_exec_complete(current_proc());
596 thread_bootstrap_return();
599 #ifdef CONFIG_32BIT_TELEMETRY
601 task_consume_32bit_log_flag(task_t task
)
603 if ((task
->t_procflags
& TPF_LOG_32BIT_TELEMETRY
) != 0) {
604 task
->t_procflags
&= ~TPF_LOG_32BIT_TELEMETRY
;
612 task_set_32bit_log_flag(task_t task
)
614 task
->t_procflags
|= TPF_LOG_32BIT_TELEMETRY
;
616 #endif /* CONFIG_32BIT_TELEMETRY */
619 task_is_exec_copy(task_t task
)
621 return task_is_exec_copy_internal(task
);
625 task_did_exec(task_t task
)
627 return task_did_exec_internal(task
);
631 task_is_active(task_t task
)
637 task_is_halting(task_t task
)
639 return task
->halting
;
642 #if TASK_REFERENCE_LEAK_DEBUG
643 #include <kern/btlog.h>
645 static btlog_t
*task_ref_btlog
;
646 #define TASK_REF_OP_INCR 0x1
647 #define TASK_REF_OP_DECR 0x2
649 #define TASK_REF_NUM_RECORDS 100000
650 #define TASK_REF_BTDEPTH 7
653 task_reference_internal(task_t task
)
655 void * bt
[TASK_REF_BTDEPTH
];
658 os_ref_retain(&task
->ref_count
);
660 numsaved
= OSBacktrace(bt
, TASK_REF_BTDEPTH
);
661 btlog_add_entry(task_ref_btlog
, task
, TASK_REF_OP_INCR
,
666 task_deallocate_internal(task_t task
)
668 void * bt
[TASK_REF_BTDEPTH
];
671 numsaved
= OSBacktrace(bt
, TASK_REF_BTDEPTH
);
672 btlog_add_entry(task_ref_btlog
, task
, TASK_REF_OP_DECR
,
675 return os_ref_release(&task
->ref_count
);
678 #endif /* TASK_REFERENCE_LEAK_DEBUG */
684 lck_grp_attr_setdefault(&task_lck_grp_attr
);
685 lck_grp_init(&task_lck_grp
, "task", &task_lck_grp_attr
);
686 lck_attr_setdefault(&task_lck_attr
);
687 lck_mtx_init(&tasks_threads_lock
, &task_lck_grp
, &task_lck_attr
);
688 lck_mtx_init(&tasks_corpse_lock
, &task_lck_grp
, &task_lck_attr
);
692 task_max
* sizeof(struct task
),
693 TASK_CHUNK
* sizeof(struct task
),
696 zone_change(task_zone
, Z_NOENCRYPT
, TRUE
);
700 #endif /* CONFIG_EMBEDDED */
703 * Configure per-task memory limit.
704 * The boot-arg is interpreted as Megabytes,
705 * and takes precedence over the device tree.
706 * Setting the boot-arg to 0 disables task limits.
708 if (!PE_parse_boot_argn("max_task_pmem", &max_task_footprint_mb
,
709 sizeof (max_task_footprint_mb
))) {
711 * No limit was found in boot-args, so go look in the device tree.
713 if (!PE_get_default("kern.max_task_pmem", &max_task_footprint_mb
,
714 sizeof(max_task_footprint_mb
))) {
716 * No limit was found in device tree.
718 max_task_footprint_mb
= 0;
722 if (max_task_footprint_mb
!= 0) {
723 #if CONFIG_MEMORYSTATUS
724 if (max_task_footprint_mb
< 50) {
725 printf("Warning: max_task_pmem %d below minimum.\n",
726 max_task_footprint_mb
);
727 max_task_footprint_mb
= 50;
729 printf("Limiting task physical memory footprint to %d MB\n",
730 max_task_footprint_mb
);
732 max_task_footprint
= (ledger_amount_t
)max_task_footprint_mb
* 1024 * 1024; // Convert MB to bytes
735 * Configure the per-task memory limit warning level.
736 * This is computed as a percentage.
738 max_task_footprint_warning_level
= 0;
740 if (max_mem
< 0x40000000) {
742 * On devices with < 1GB of memory:
743 * -- set warnings to 50MB below the per-task limit.
745 if (max_task_footprint_mb
> 50) {
746 max_task_footprint_warning_level
= ((max_task_footprint_mb
- 50) * 100) / max_task_footprint_mb
;
750 * On devices with >= 1GB of memory:
751 * -- set warnings to 100MB below the per-task limit.
753 if (max_task_footprint_mb
> 100) {
754 max_task_footprint_warning_level
= ((max_task_footprint_mb
- 100) * 100) / max_task_footprint_mb
;
759 * Never allow warning level to land below the default.
761 if (max_task_footprint_warning_level
< PHYS_FOOTPRINT_WARNING_LEVEL
) {
762 max_task_footprint_warning_level
= PHYS_FOOTPRINT_WARNING_LEVEL
;
765 printf("Limiting task physical memory warning to %d%%\n", max_task_footprint_warning_level
);
768 printf("Warning: max_task_pmem specified, but jetsam not configured; ignoring.\n");
769 #endif /* CONFIG_MEMORYSTATUS */
772 #if DEVELOPMENT || DEBUG
773 if (!PE_parse_boot_argn("exc_resource_threads",
774 &exc_resource_threads_enabled
,
775 sizeof(exc_resource_threads_enabled
))) {
776 exc_resource_threads_enabled
= 1;
778 PE_parse_boot_argn("task_exc_guard_default",
779 &task_exc_guard_default
,
780 sizeof(task_exc_guard_default
));
781 #endif /* DEVELOPMENT || DEBUG */
784 if (!PE_parse_boot_argn("hwm_user_cores", &hwm_user_cores
,
785 sizeof (hwm_user_cores
))) {
790 proc_init_cpumon_params();
792 if (!PE_parse_boot_argn("task_wakeups_monitor_rate", &task_wakeups_monitor_rate
, sizeof (task_wakeups_monitor_rate
))) {
793 task_wakeups_monitor_rate
= TASK_WAKEUPS_MONITOR_DEFAULT_LIMIT
;
796 if (!PE_parse_boot_argn("task_wakeups_monitor_interval", &task_wakeups_monitor_interval
, sizeof (task_wakeups_monitor_interval
))) {
797 task_wakeups_monitor_interval
= TASK_WAKEUPS_MONITOR_DEFAULT_INTERVAL
;
800 if (!PE_parse_boot_argn("task_wakeups_monitor_ustackshots_trigger_pct", &task_wakeups_monitor_ustackshots_trigger_pct
,
801 sizeof (task_wakeups_monitor_ustackshots_trigger_pct
))) {
802 task_wakeups_monitor_ustackshots_trigger_pct
= TASK_WAKEUPS_MONITOR_DEFAULT_USTACKSHOTS_TRIGGER
;
805 if (!PE_parse_boot_argn("disable_exc_resource", &disable_exc_resource
,
806 sizeof (disable_exc_resource
))) {
807 disable_exc_resource
= 0;
810 if (!PE_parse_boot_argn("task_iomon_limit_mb", &task_iomon_limit_mb
, sizeof (task_iomon_limit_mb
))) {
811 task_iomon_limit_mb
= IOMON_DEFAULT_LIMIT
;
814 if (!PE_parse_boot_argn("task_iomon_interval_secs", &task_iomon_interval_secs
, sizeof (task_iomon_interval_secs
))) {
815 task_iomon_interval_secs
= IOMON_DEFAULT_INTERVAL
;
818 if (!PE_parse_boot_argn("io_telemetry_limit", &io_telemetry_limit
, sizeof (io_telemetry_limit
))) {
819 io_telemetry_limit
= IO_TELEMETRY_DEFAULT_LIMIT
;
823 * If we have coalitions, coalition_init() will call init_task_ledgers() as it
824 * sets up the ledgers for the default coalition. If we don't have coalitions,
825 * then we have to call it now.
827 #if CONFIG_COALITIONS
828 assert(task_ledger_template
);
829 #else /* CONFIG_COALITIONS */
831 #endif /* CONFIG_COALITIONS */
833 #if TASK_REFERENCE_LEAK_DEBUG
834 task_ref_btlog
= btlog_create(TASK_REF_NUM_RECORDS
, TASK_REF_BTDEPTH
, TRUE
/* caller_will_remove_entries_for_element? */);
835 assert(task_ref_btlog
);
839 * Create the kernel task as the first task.
842 if (task_create_internal(TASK_NULL
, NULL
, FALSE
, TRUE
, TRUE
, TF_NONE
, TPF_NONE
, &kernel_task
) != KERN_SUCCESS
)
844 if (task_create_internal(TASK_NULL
, NULL
, FALSE
, FALSE
, FALSE
, TF_NONE
, TPF_NONE
, &kernel_task
) != KERN_SUCCESS
)
846 panic("task_init\n");
849 vm_map_deallocate(kernel_task
->map
);
850 kernel_task
->map
= kernel_map
;
851 lck_spin_init(&dead_task_statistics_lock
, &task_lck_grp
, &task_lck_attr
);
855 * Create a task running in the kernel address space. It may
856 * have its own map of size mem_size and may have ipc privileges.
860 __unused task_t parent_task
,
861 __unused vm_offset_t map_base
,
862 __unused vm_size_t map_size
,
863 __unused task_t
*child_task
)
865 return (KERN_INVALID_ARGUMENT
);
871 __unused ledger_port_array_t ledger_ports
,
872 __unused mach_msg_type_number_t num_ledger_ports
,
873 __unused boolean_t inherit_memory
,
874 __unused task_t
*child_task
) /* OUT */
876 if (parent_task
== TASK_NULL
)
877 return(KERN_INVALID_ARGUMENT
);
880 * No longer supported: too many calls assume that a task has a valid
883 return(KERN_FAILURE
);
887 host_security_create_task_token(
888 host_security_t host_security
,
890 __unused security_token_t sec_token
,
891 __unused audit_token_t audit_token
,
892 __unused host_priv_t host_priv
,
893 __unused ledger_port_array_t ledger_ports
,
894 __unused mach_msg_type_number_t num_ledger_ports
,
895 __unused boolean_t inherit_memory
,
896 __unused task_t
*child_task
) /* OUT */
898 if (parent_task
== TASK_NULL
)
899 return(KERN_INVALID_ARGUMENT
);
901 if (host_security
== HOST_NULL
)
902 return(KERN_INVALID_SECURITY
);
905 * No longer supported.
907 return(KERN_FAILURE
);
915 * Physical footprint: This is the sum of:
916 * + (internal - alternate_accounting)
917 * + (internal_compressed - alternate_accounting_compressed)
919 * + purgeable_nonvolatile
920 * + purgeable_nonvolatile_compressed
924 * The task's anonymous memory, which on iOS is always resident.
926 * internal_compressed
927 * Amount of this task's internal memory which is held by the compressor.
928 * Such memory is no longer actually resident for the task [i.e., resident in its pmap],
929 * and could be either decompressed back into memory, or paged out to storage, depending
930 * on our implementation.
933 * IOKit mappings: The total size of all IOKit mappings in this task, regardless of
934 clean/dirty or internal/external state].
936 * alternate_accounting
937 * The number of internal dirty pages which are part of IOKit mappings. By definition, these pages
938 * are counted in both internal *and* iokit_mapped, so we must subtract them from the total to avoid
942 init_task_ledgers(void)
946 assert(task_ledger_template
== NULL
);
947 assert(kernel_task
== TASK_NULL
);
950 PE_parse_boot_argn("pmap_ledgers_panic",
952 sizeof (pmap_ledgers_panic
));
953 PE_parse_boot_argn("pmap_ledgers_panic_leeway",
954 &pmap_ledgers_panic_leeway
,
955 sizeof (pmap_ledgers_panic_leeway
));
956 #endif /* MACH_ASSERT */
958 if ((t
= ledger_template_create("Per-task ledger")) == NULL
)
959 panic("couldn't create task ledger template");
961 task_ledgers
.cpu_time
= ledger_entry_add(t
, "cpu_time", "sched", "ns");
962 task_ledgers
.tkm_private
= ledger_entry_add(t
, "tkm_private",
964 task_ledgers
.tkm_shared
= ledger_entry_add(t
, "tkm_shared", "physmem",
966 task_ledgers
.phys_mem
= ledger_entry_add(t
, "phys_mem", "physmem",
968 task_ledgers
.wired_mem
= ledger_entry_add(t
, "wired_mem", "physmem",
970 task_ledgers
.internal
= ledger_entry_add(t
, "internal", "physmem",
972 task_ledgers
.iokit_mapped
= ledger_entry_add(t
, "iokit_mapped", "mappings",
974 task_ledgers
.alternate_accounting
= ledger_entry_add(t
, "alternate_accounting", "physmem",
976 task_ledgers
.alternate_accounting_compressed
= ledger_entry_add(t
, "alternate_accounting_compressed", "physmem",
978 task_ledgers
.page_table
= ledger_entry_add(t
, "page_table", "physmem",
980 task_ledgers
.phys_footprint
= ledger_entry_add(t
, "phys_footprint", "physmem",
982 task_ledgers
.internal_compressed
= ledger_entry_add(t
, "internal_compressed", "physmem",
984 task_ledgers
.purgeable_volatile
= ledger_entry_add(t
, "purgeable_volatile", "physmem", "bytes");
985 task_ledgers
.purgeable_nonvolatile
= ledger_entry_add(t
, "purgeable_nonvolatile", "physmem", "bytes");
986 task_ledgers
.purgeable_volatile_compressed
= ledger_entry_add(t
, "purgeable_volatile_compress", "physmem", "bytes");
987 task_ledgers
.purgeable_nonvolatile_compressed
= ledger_entry_add(t
, "purgeable_nonvolatile_compress", "physmem", "bytes");
989 task_ledgers
.network_volatile
= ledger_entry_add(t
, "network_volatile", "physmem", "bytes");
990 task_ledgers
.network_nonvolatile
= ledger_entry_add(t
, "network_nonvolatile", "physmem", "bytes");
991 task_ledgers
.network_volatile_compressed
= ledger_entry_add(t
, "network_volatile_compressed", "physmem", "bytes");
992 task_ledgers
.network_nonvolatile_compressed
= ledger_entry_add(t
, "network_nonvolatile_compressed", "physmem", "bytes");
994 task_ledgers
.platform_idle_wakeups
= ledger_entry_add(t
, "platform_idle_wakeups", "power",
996 task_ledgers
.interrupt_wakeups
= ledger_entry_add(t
, "interrupt_wakeups", "power",
1000 sfi_class_id_t class_id
, ledger_alias
;
1001 for (class_id
= SFI_CLASS_UNSPECIFIED
; class_id
< MAX_SFI_CLASS_ID
; class_id
++) {
1002 task_ledgers
.sfi_wait_times
[class_id
] = -1;
1005 /* don't account for UNSPECIFIED */
1006 for (class_id
= SFI_CLASS_UNSPECIFIED
+ 1; class_id
< MAX_SFI_CLASS_ID
; class_id
++) {
1007 ledger_alias
= sfi_get_ledger_alias_for_class(class_id
);
1008 if (ledger_alias
!= SFI_CLASS_UNSPECIFIED
) {
1009 /* Check to see if alias has been registered yet */
1010 if (task_ledgers
.sfi_wait_times
[ledger_alias
] != -1) {
1011 task_ledgers
.sfi_wait_times
[class_id
] = task_ledgers
.sfi_wait_times
[ledger_alias
];
1013 /* Otherwise, initialize it first */
1014 task_ledgers
.sfi_wait_times
[class_id
] = task_ledgers
.sfi_wait_times
[ledger_alias
] = sfi_ledger_entry_add(t
, ledger_alias
);
1017 task_ledgers
.sfi_wait_times
[class_id
] = sfi_ledger_entry_add(t
, class_id
);
1020 if (task_ledgers
.sfi_wait_times
[class_id
] < 0) {
1021 panic("couldn't create entries for task ledger template for SFI class 0x%x", class_id
);
1025 assert(task_ledgers
.sfi_wait_times
[MAX_SFI_CLASS_ID
-1] != -1);
1026 #endif /* CONFIG_SCHED_SFI */
1028 task_ledgers
.cpu_time_billed_to_me
= ledger_entry_add(t
, "cpu_time_billed_to_me", "sched", "ns");
1029 task_ledgers
.cpu_time_billed_to_others
= ledger_entry_add(t
, "cpu_time_billed_to_others", "sched", "ns");
1030 task_ledgers
.physical_writes
= ledger_entry_add(t
, "physical_writes", "res", "bytes");
1031 task_ledgers
.logical_writes
= ledger_entry_add(t
, "logical_writes", "res", "bytes");
1032 task_ledgers
.energy_billed_to_me
= ledger_entry_add(t
, "energy_billed_to_me", "power", "nj");
1033 task_ledgers
.energy_billed_to_others
= ledger_entry_add(t
, "energy_billed_to_others", "power", "nj");
1035 if ((task_ledgers
.cpu_time
< 0) ||
1036 (task_ledgers
.tkm_private
< 0) ||
1037 (task_ledgers
.tkm_shared
< 0) ||
1038 (task_ledgers
.phys_mem
< 0) ||
1039 (task_ledgers
.wired_mem
< 0) ||
1040 (task_ledgers
.internal
< 0) ||
1041 (task_ledgers
.iokit_mapped
< 0) ||
1042 (task_ledgers
.alternate_accounting
< 0) ||
1043 (task_ledgers
.alternate_accounting_compressed
< 0) ||
1044 (task_ledgers
.page_table
< 0) ||
1045 (task_ledgers
.phys_footprint
< 0) ||
1046 (task_ledgers
.internal_compressed
< 0) ||
1047 (task_ledgers
.purgeable_volatile
< 0) ||
1048 (task_ledgers
.purgeable_nonvolatile
< 0) ||
1049 (task_ledgers
.purgeable_volatile_compressed
< 0) ||
1050 (task_ledgers
.purgeable_nonvolatile_compressed
< 0) ||
1051 (task_ledgers
.network_volatile
< 0) ||
1052 (task_ledgers
.network_nonvolatile
< 0) ||
1053 (task_ledgers
.network_volatile_compressed
< 0) ||
1054 (task_ledgers
.network_nonvolatile_compressed
< 0) ||
1055 (task_ledgers
.platform_idle_wakeups
< 0) ||
1056 (task_ledgers
.interrupt_wakeups
< 0) ||
1057 (task_ledgers
.cpu_time_billed_to_me
< 0) || (task_ledgers
.cpu_time_billed_to_others
< 0) ||
1058 (task_ledgers
.physical_writes
< 0) ||
1059 (task_ledgers
.logical_writes
< 0) ||
1060 (task_ledgers
.energy_billed_to_me
< 0) ||
1061 (task_ledgers
.energy_billed_to_others
< 0)
1063 panic("couldn't create entries for task ledger template");
1066 ledger_track_credit_only(t
, task_ledgers
.phys_footprint
);
1067 ledger_track_credit_only(t
, task_ledgers
.page_table
);
1068 ledger_track_credit_only(t
, task_ledgers
.internal
);
1069 ledger_track_credit_only(t
, task_ledgers
.internal_compressed
);
1070 ledger_track_credit_only(t
, task_ledgers
.iokit_mapped
);
1071 ledger_track_credit_only(t
, task_ledgers
.alternate_accounting
);
1072 ledger_track_credit_only(t
, task_ledgers
.alternate_accounting_compressed
);
1073 ledger_track_credit_only(t
, task_ledgers
.purgeable_volatile
);
1074 ledger_track_credit_only(t
, task_ledgers
.purgeable_nonvolatile
);
1075 ledger_track_credit_only(t
, task_ledgers
.purgeable_volatile_compressed
);
1076 ledger_track_credit_only(t
, task_ledgers
.purgeable_nonvolatile_compressed
);
1078 ledger_track_credit_only(t
, task_ledgers
.network_volatile
);
1079 ledger_track_credit_only(t
, task_ledgers
.network_nonvolatile
);
1080 ledger_track_credit_only(t
, task_ledgers
.network_volatile_compressed
);
1081 ledger_track_credit_only(t
, task_ledgers
.network_nonvolatile_compressed
);
1083 ledger_track_maximum(t
, task_ledgers
.phys_footprint
, 60);
1085 if (pmap_ledgers_panic
) {
1086 ledger_panic_on_negative(t
, task_ledgers
.phys_footprint
);
1087 ledger_panic_on_negative(t
, task_ledgers
.page_table
);
1088 ledger_panic_on_negative(t
, task_ledgers
.internal
);
1089 ledger_panic_on_negative(t
, task_ledgers
.internal_compressed
);
1090 ledger_panic_on_negative(t
, task_ledgers
.iokit_mapped
);
1091 ledger_panic_on_negative(t
, task_ledgers
.alternate_accounting
);
1092 ledger_panic_on_negative(t
, task_ledgers
.alternate_accounting_compressed
);
1093 ledger_panic_on_negative(t
, task_ledgers
.purgeable_volatile
);
1094 ledger_panic_on_negative(t
, task_ledgers
.purgeable_nonvolatile
);
1095 ledger_panic_on_negative(t
, task_ledgers
.purgeable_volatile_compressed
);
1096 ledger_panic_on_negative(t
, task_ledgers
.purgeable_nonvolatile_compressed
);
1098 ledger_panic_on_negative(t
, task_ledgers
.network_volatile
);
1099 ledger_panic_on_negative(t
, task_ledgers
.network_nonvolatile
);
1100 ledger_panic_on_negative(t
, task_ledgers
.network_volatile_compressed
);
1101 ledger_panic_on_negative(t
, task_ledgers
.network_nonvolatile_compressed
);
1103 #endif /* MACH_ASSERT */
1105 #if CONFIG_MEMORYSTATUS
1106 ledger_set_callback(t
, task_ledgers
.phys_footprint
, task_footprint_exceeded
, NULL
, NULL
);
1107 #endif /* CONFIG_MEMORYSTATUS */
1109 ledger_set_callback(t
, task_ledgers
.interrupt_wakeups
,
1110 task_wakeups_rate_exceeded
, NULL
, NULL
);
1111 ledger_set_callback(t
, task_ledgers
.physical_writes
, task_io_rate_exceeded
, (void *)FLAVOR_IO_PHYSICAL_WRITES
, NULL
);
1112 ledger_set_callback(t
, task_ledgers
.logical_writes
, task_io_rate_exceeded
, (void *)FLAVOR_IO_LOGICAL_WRITES
, NULL
);
1114 ledger_template_complete(t
);
1115 task_ledger_template
= t
;
1118 os_refgrp_decl(static, task_refgrp
, "task", NULL
);
1121 task_create_internal(
1123 coalition_t
*parent_coalitions __unused
,
1124 boolean_t inherit_memory
,
1125 __unused boolean_t is_64bit
,
1126 boolean_t is_64bit_data
,
1128 uint32_t t_procflags
,
1129 task_t
*child_task
) /* OUT */
1132 vm_shared_region_t shared_region
;
1133 ledger_t ledger
= NULL
;
1135 new_task
= (task_t
) zalloc(task_zone
);
1137 if (new_task
== TASK_NULL
)
1138 return(KERN_RESOURCE_SHORTAGE
);
1140 /* one ref for just being alive; one for our caller */
1141 os_ref_init_count(&new_task
->ref_count
, &task_refgrp
, 2);
1143 /* allocate with active entries */
1144 assert(task_ledger_template
!= NULL
);
1145 if ((ledger
= ledger_instantiate(task_ledger_template
,
1146 LEDGER_CREATE_ACTIVE_ENTRIES
)) == NULL
) {
1147 zfree(task_zone
, new_task
);
1148 return(KERN_RESOURCE_SHORTAGE
);
1152 new_task
->ledger
= ledger
;
1154 #if defined(CONFIG_SCHED_MULTIQ)
1155 new_task
->sched_group
= sched_group_create();
1158 /* if inherit_memory is true, parent_task MUST not be NULL */
1159 if (!(t_flags
& TF_CORPSE_FORK
) && inherit_memory
)
1160 new_task
->map
= vm_map_fork(ledger
, parent_task
->map
, 0);
1162 new_task
->map
= vm_map_create(pmap_create(ledger
, 0, is_64bit
),
1163 (vm_map_offset_t
)(VM_MIN_ADDRESS
),
1164 (vm_map_offset_t
)(VM_MAX_ADDRESS
), TRUE
);
1166 /* Inherit memlock limit from parent */
1168 vm_map_set_user_wire_limit(new_task
->map
, (vm_size_t
)parent_task
->map
->user_wire_limit
);
1170 lck_mtx_init(&new_task
->lock
, &task_lck_grp
, &task_lck_attr
);
1171 queue_init(&new_task
->threads
);
1172 new_task
->suspend_count
= 0;
1173 new_task
->thread_count
= 0;
1174 new_task
->active_thread_count
= 0;
1175 new_task
->user_stop_count
= 0;
1176 new_task
->legacy_stop_count
= 0;
1177 new_task
->active
= TRUE
;
1178 new_task
->halting
= FALSE
;
1179 new_task
->priv_flags
= 0;
1180 new_task
->t_flags
= t_flags
;
1181 new_task
->t_procflags
= t_procflags
;
1182 new_task
->importance
= 0;
1183 new_task
->crashed_thread_id
= 0;
1184 new_task
->exec_token
= 0;
1186 new_task
->task_exc_guard
= task_exc_guard_default
;
1189 new_task
->atm_context
= NULL
;
1191 new_task
->bank_context
= NULL
;
1194 new_task
->bsd_info
= NULL
;
1195 new_task
->corpse_info
= NULL
;
1196 #endif /* MACH_BSD */
1199 new_task
->crash_label
= NULL
;
1202 #if CONFIG_MEMORYSTATUS
1203 if (max_task_footprint
!= 0) {
1204 ledger_set_limit(ledger
, task_ledgers
.phys_footprint
, max_task_footprint
, PHYS_FOOTPRINT_WARNING_LEVEL
);
1206 #endif /* CONFIG_MEMORYSTATUS */
1208 if (task_wakeups_monitor_rate
!= 0) {
1209 uint32_t flags
= WAKEMON_ENABLE
| WAKEMON_SET_DEFAULTS
;
1210 int32_t rate
; // Ignored because of WAKEMON_SET_DEFAULTS
1211 task_wakeups_monitor_ctl(new_task
, &flags
, &rate
);
1214 #if CONFIG_IO_ACCOUNTING
1215 uint32_t flags
= IOMON_ENABLE
;
1216 task_io_monitor_ctl(new_task
, &flags
);
1217 #endif /* CONFIG_IO_ACCOUNTING */
1219 machine_task_init(new_task
, parent_task
, inherit_memory
);
1221 new_task
->task_debug
= NULL
;
1223 #if DEVELOPMENT || DEBUG
1224 new_task
->task_unnested
= FALSE
;
1225 new_task
->task_disconnected_count
= 0;
1227 queue_init(&new_task
->semaphore_list
);
1228 new_task
->semaphores_owned
= 0;
1230 ipc_task_init(new_task
, parent_task
);
1232 new_task
->vtimers
= 0;
1234 new_task
->shared_region
= NULL
;
1236 new_task
->affinity_space
= NULL
;
1238 new_task
->t_kpc
= 0;
1240 new_task
->pidsuspended
= FALSE
;
1241 new_task
->frozen
= FALSE
;
1242 new_task
->changing_freeze_state
= FALSE
;
1243 new_task
->rusage_cpu_flags
= 0;
1244 new_task
->rusage_cpu_percentage
= 0;
1245 new_task
->rusage_cpu_interval
= 0;
1246 new_task
->rusage_cpu_deadline
= 0;
1247 new_task
->rusage_cpu_callt
= NULL
;
1249 new_task
->suspends_outstanding
= 0;
1253 new_task
->hv_task_target
= NULL
;
1254 #endif /* HYPERVISOR */
1257 queue_init(&new_task
->task_watchers
);
1258 new_task
->num_taskwatchers
= 0;
1259 new_task
->watchapplying
= 0;
1260 #endif /* CONFIG_EMBEDDED */
1262 new_task
->mem_notify_reserved
= 0;
1263 new_task
->memlimit_attrs_reserved
= 0;
1265 new_task
->requested_policy
= default_task_requested_policy
;
1266 new_task
->effective_policy
= default_task_effective_policy
;
1268 task_importance_init_from_parent(new_task
, parent_task
);
1270 if (parent_task
!= TASK_NULL
) {
1271 new_task
->sec_token
= parent_task
->sec_token
;
1272 new_task
->audit_token
= parent_task
->audit_token
;
1274 /* inherit the parent's shared region */
1275 shared_region
= vm_shared_region_get(parent_task
);
1276 vm_shared_region_set(new_task
, shared_region
);
1278 if(task_has_64Bit_addr(parent_task
)) {
1279 task_set_64Bit_addr(new_task
);
1282 if(task_has_64Bit_data(parent_task
)) {
1283 task_set_64Bit_data(new_task
);
1286 new_task
->all_image_info_addr
= parent_task
->all_image_info_addr
;
1287 new_task
->all_image_info_size
= parent_task
->all_image_info_size
;
1289 if (inherit_memory
&& parent_task
->affinity_space
)
1290 task_affinity_create(parent_task
, new_task
);
1292 new_task
->pset_hint
= parent_task
->pset_hint
= task_choose_pset(parent_task
);
1294 new_task
->priority
= BASEPRI_DEFAULT
;
1295 new_task
->max_priority
= MAXPRI_USER
;
1297 task_policy_create(new_task
, parent_task
);
1299 new_task
->sec_token
= KERNEL_SECURITY_TOKEN
;
1300 new_task
->audit_token
= KERNEL_AUDIT_TOKEN
;
1303 task_set_64Bit_addr(new_task
);
1308 task_set_64Bit_data(new_task
);
1311 new_task
->all_image_info_addr
= (mach_vm_address_t
)0;
1312 new_task
->all_image_info_size
= (mach_vm_size_t
)0;
1314 new_task
->pset_hint
= PROCESSOR_SET_NULL
;
1316 if (kernel_task
== TASK_NULL
) {
1317 new_task
->priority
= BASEPRI_KERNEL
;
1318 new_task
->max_priority
= MAXPRI_KERNEL
;
1320 new_task
->priority
= BASEPRI_DEFAULT
;
1321 new_task
->max_priority
= MAXPRI_USER
;
1325 bzero(new_task
->coalition
, sizeof(new_task
->coalition
));
1326 for (int i
= 0; i
< COALITION_NUM_TYPES
; i
++)
1327 queue_chain_init(new_task
->task_coalition
[i
]);
1329 /* Allocate I/O Statistics */
1330 new_task
->task_io_stats
= (io_stat_info_t
)kalloc(sizeof(struct io_stat_info
));
1331 assert(new_task
->task_io_stats
!= NULL
);
1332 bzero(new_task
->task_io_stats
, sizeof(struct io_stat_info
));
1334 bzero(&(new_task
->cpu_time_eqos_stats
), sizeof(new_task
->cpu_time_eqos_stats
));
1335 bzero(&(new_task
->cpu_time_rqos_stats
), sizeof(new_task
->cpu_time_rqos_stats
));
1337 bzero(&new_task
->extmod_statistics
, sizeof(new_task
->extmod_statistics
));
1339 /* Copy resource acc. info from Parent for Corpe Forked task. */
1340 if (parent_task
!= NULL
&& (t_flags
& TF_CORPSE_FORK
)) {
1341 task_rollup_accounting_info(new_task
, parent_task
);
1343 /* Initialize to zero for standard fork/spawn case */
1344 new_task
->total_user_time
= 0;
1345 new_task
->total_system_time
= 0;
1346 new_task
->total_ptime
= 0;
1347 new_task
->total_runnable_time
= 0;
1348 new_task
->faults
= 0;
1349 new_task
->pageins
= 0;
1350 new_task
->cow_faults
= 0;
1351 new_task
->messages_sent
= 0;
1352 new_task
->messages_received
= 0;
1353 new_task
->syscalls_mach
= 0;
1354 new_task
->syscalls_unix
= 0;
1355 new_task
->c_switch
= 0;
1356 new_task
->p_switch
= 0;
1357 new_task
->ps_switch
= 0;
1358 new_task
->low_mem_notified_warn
= 0;
1359 new_task
->low_mem_notified_critical
= 0;
1360 new_task
->purged_memory_warn
= 0;
1361 new_task
->purged_memory_critical
= 0;
1362 new_task
->low_mem_privileged_listener
= 0;
1363 new_task
->memlimit_is_active
= 0;
1364 new_task
->memlimit_is_fatal
= 0;
1365 new_task
->memlimit_active_exc_resource
= 0;
1366 new_task
->memlimit_inactive_exc_resource
= 0;
1367 new_task
->task_timer_wakeups_bin_1
= 0;
1368 new_task
->task_timer_wakeups_bin_2
= 0;
1369 new_task
->task_gpu_ns
= 0;
1370 new_task
->task_immediate_writes
= 0;
1371 new_task
->task_deferred_writes
= 0;
1372 new_task
->task_invalidated_writes
= 0;
1373 new_task
->task_metadata_writes
= 0;
1374 new_task
->task_energy
= 0;
1376 memset(&new_task
->task_monotonic
, 0, sizeof(new_task
->task_monotonic
));
1377 #endif /* MONOTONIC */
1381 #if CONFIG_COALITIONS
1382 if (!(t_flags
& TF_CORPSE_FORK
)) {
1383 /* TODO: there is no graceful failure path here... */
1384 if (parent_coalitions
&& parent_coalitions
[COALITION_TYPE_RESOURCE
]) {
1385 coalitions_adopt_task(parent_coalitions
, new_task
);
1386 } else if (parent_task
&& parent_task
->coalition
[COALITION_TYPE_RESOURCE
]) {
1388 * all tasks at least have a resource coalition, so
1389 * if the parent has one then inherit all coalitions
1390 * the parent is a part of
1392 coalitions_adopt_task(parent_task
->coalition
, new_task
);
1394 /* TODO: assert that new_task will be PID 1 (launchd) */
1395 coalitions_adopt_init_task(new_task
);
1398 * on exec, we need to transfer the coalition roles from the
1399 * parent task to the exec copy task.
1401 if (parent_task
&& (t_procflags
& TPF_EXEC_COPY
)) {
1402 int coal_roles
[COALITION_NUM_TYPES
];
1403 task_coalition_roles(parent_task
, coal_roles
);
1404 (void)coalitions_set_roles(new_task
->coalition
, new_task
, coal_roles
);
1407 coalitions_adopt_corpse_task(new_task
);
1410 if (new_task
->coalition
[COALITION_TYPE_RESOURCE
] == COALITION_NULL
) {
1411 panic("created task is not a member of a resource coalition");
1413 #endif /* CONFIG_COALITIONS */
1415 new_task
->dispatchqueue_offset
= 0;
1416 if (parent_task
!= NULL
) {
1417 new_task
->dispatchqueue_offset
= parent_task
->dispatchqueue_offset
;
1420 new_task
->task_volatile_objects
= 0;
1421 new_task
->task_nonvolatile_objects
= 0;
1422 new_task
->task_purgeable_disowning
= FALSE
;
1423 new_task
->task_purgeable_disowned
= FALSE
;
1424 queue_init(&new_task
->task_objq
);
1425 task_objq_lock_init(new_task
);
1428 new_task
->task_legacy_footprint
= FALSE
;
1429 #endif /* __arm64__ */
1430 new_task
->task_region_footprint
= FALSE
;
1431 new_task
->task_has_crossed_thread_limit
= FALSE
;
1432 new_task
->task_thread_limit
= 0;
1433 #if CONFIG_SECLUDED_MEMORY
1434 new_task
->task_can_use_secluded_mem
= FALSE
;
1435 new_task
->task_could_use_secluded_mem
= FALSE
;
1436 new_task
->task_could_also_use_secluded_mem
= FALSE
;
1437 new_task
->task_suppressed_secluded
= FALSE
;
1438 #endif /* CONFIG_SECLUDED_MEMORY */
1441 * t_flags is set up above. But since we don't
1442 * support darkwake mode being set that way
1443 * currently, we clear it out here explicitly.
1445 new_task
->t_flags
&= ~(TF_DARKWAKE_MODE
);
1447 queue_init(&new_task
->io_user_clients
);
1449 ipc_task_enable(new_task
);
1451 lck_mtx_lock(&tasks_threads_lock
);
1452 queue_enter(&tasks
, new_task
, task_t
, tasks
);
1454 if (tasks_suspend_state
) {
1455 task_suspend_internal(new_task
);
1457 lck_mtx_unlock(&tasks_threads_lock
);
1459 *child_task
= new_task
;
1460 return(KERN_SUCCESS
);
1464 * task_rollup_accounting_info
1466 * Roll up accounting stats. Used to rollup stats
1467 * for exec copy task and corpse fork.
1470 task_rollup_accounting_info(task_t to_task
, task_t from_task
)
1472 assert(from_task
!= to_task
);
1474 to_task
->total_user_time
= from_task
->total_user_time
;
1475 to_task
->total_system_time
= from_task
->total_system_time
;
1476 to_task
->total_ptime
= from_task
->total_ptime
;
1477 to_task
->total_runnable_time
= from_task
->total_runnable_time
;
1478 to_task
->faults
= from_task
->faults
;
1479 to_task
->pageins
= from_task
->pageins
;
1480 to_task
->cow_faults
= from_task
->cow_faults
;
1481 to_task
->messages_sent
= from_task
->messages_sent
;
1482 to_task
->messages_received
= from_task
->messages_received
;
1483 to_task
->syscalls_mach
= from_task
->syscalls_mach
;
1484 to_task
->syscalls_unix
= from_task
->syscalls_unix
;
1485 to_task
->c_switch
= from_task
->c_switch
;
1486 to_task
->p_switch
= from_task
->p_switch
;
1487 to_task
->ps_switch
= from_task
->ps_switch
;
1488 to_task
->extmod_statistics
= from_task
->extmod_statistics
;
1489 to_task
->low_mem_notified_warn
= from_task
->low_mem_notified_warn
;
1490 to_task
->low_mem_notified_critical
= from_task
->low_mem_notified_critical
;
1491 to_task
->purged_memory_warn
= from_task
->purged_memory_warn
;
1492 to_task
->purged_memory_critical
= from_task
->purged_memory_critical
;
1493 to_task
->low_mem_privileged_listener
= from_task
->low_mem_privileged_listener
;
1494 *to_task
->task_io_stats
= *from_task
->task_io_stats
;
1495 to_task
->cpu_time_eqos_stats
= from_task
->cpu_time_eqos_stats
;
1496 to_task
->cpu_time_rqos_stats
= from_task
->cpu_time_rqos_stats
;
1497 to_task
->task_timer_wakeups_bin_1
= from_task
->task_timer_wakeups_bin_1
;
1498 to_task
->task_timer_wakeups_bin_2
= from_task
->task_timer_wakeups_bin_2
;
1499 to_task
->task_gpu_ns
= from_task
->task_gpu_ns
;
1500 to_task
->task_immediate_writes
= from_task
->task_immediate_writes
;
1501 to_task
->task_deferred_writes
= from_task
->task_deferred_writes
;
1502 to_task
->task_invalidated_writes
= from_task
->task_invalidated_writes
;
1503 to_task
->task_metadata_writes
= from_task
->task_metadata_writes
;
1504 to_task
->task_energy
= from_task
->task_energy
;
1506 /* Skip ledger roll up for memory accounting entries */
1507 ledger_rollup_entry(to_task
->ledger
, from_task
->ledger
, task_ledgers
.cpu_time
);
1508 ledger_rollup_entry(to_task
->ledger
, from_task
->ledger
, task_ledgers
.platform_idle_wakeups
);
1509 ledger_rollup_entry(to_task
->ledger
, from_task
->ledger
, task_ledgers
.interrupt_wakeups
);
1510 #if CONFIG_SCHED_SFI
1511 for (sfi_class_id_t class_id
= SFI_CLASS_UNSPECIFIED
; class_id
< MAX_SFI_CLASS_ID
; class_id
++) {
1512 ledger_rollup_entry(to_task
->ledger
, from_task
->ledger
, task_ledgers
.sfi_wait_times
[class_id
]);
1515 ledger_rollup_entry(to_task
->ledger
, from_task
->ledger
, task_ledgers
.cpu_time_billed_to_me
);
1516 ledger_rollup_entry(to_task
->ledger
, from_task
->ledger
, task_ledgers
.cpu_time_billed_to_others
);
1517 ledger_rollup_entry(to_task
->ledger
, from_task
->ledger
, task_ledgers
.physical_writes
);
1518 ledger_rollup_entry(to_task
->ledger
, from_task
->ledger
, task_ledgers
.logical_writes
);
1519 ledger_rollup_entry(to_task
->ledger
, from_task
->ledger
, task_ledgers
.energy_billed_to_me
);
1520 ledger_rollup_entry(to_task
->ledger
, from_task
->ledger
, task_ledgers
.energy_billed_to_others
);
1523 int task_dropped_imp_count
= 0;
1528 * Drop a reference on a task.
1534 ledger_amount_t credit
, debit
, interrupt_wakeups
, platform_idle_wakeups
;
1535 os_ref_count_t refs
;
1537 if (task
== TASK_NULL
)
1540 refs
= task_deallocate_internal(task
);
1542 #if IMPORTANCE_INHERITANCE
1545 * If last ref potentially comes from the task's importance,
1546 * disconnect it. But more task refs may be added before
1547 * that completes, so wait for the reference to go to zero
1548 * naturally (it may happen on a recursive task_deallocate()
1549 * from the ipc_importance_disconnect_task() call).
1551 if (IIT_NULL
!= task
->task_imp_base
)
1552 ipc_importance_disconnect_task(task
);
1555 #endif /* IMPORTANCE_INHERITANCE */
1561 lck_mtx_lock(&tasks_threads_lock
);
1562 queue_remove(&terminated_tasks
, task
, task_t
, tasks
);
1563 terminated_tasks_count
--;
1564 lck_mtx_unlock(&tasks_threads_lock
);
1567 * remove the reference on atm descriptor
1569 task_atm_reset(task
);
1572 * remove the reference on bank context
1574 task_bank_reset(task
);
1576 if (task
->task_io_stats
)
1577 kfree(task
->task_io_stats
, sizeof(struct io_stat_info
));
1580 * Give the machine dependent code a chance
1581 * to perform cleanup before ripping apart
1584 machine_task_terminate(task
);
1586 ipc_task_terminate(task
);
1588 /* let iokit know */
1589 iokit_task_terminate(task
);
1591 if (task
->affinity_space
)
1592 task_affinity_deallocate(task
);
1595 if (task
->ledger
!= NULL
&&
1596 task
->map
!= NULL
&&
1597 task
->map
->pmap
!= NULL
&&
1598 task
->map
->pmap
->ledger
!= NULL
) {
1599 assert(task
->ledger
== task
->map
->pmap
->ledger
);
1601 #endif /* MACH_ASSERT */
1603 vm_purgeable_disown(task
);
1604 assert(task
->task_purgeable_disowned
);
1605 if (task
->task_volatile_objects
!= 0 ||
1606 task
->task_nonvolatile_objects
!= 0) {
1607 panic("task_deallocate(%p): "
1608 "volatile_objects=%d nonvolatile_objects=%d\n",
1610 task
->task_volatile_objects
,
1611 task
->task_nonvolatile_objects
);
1614 vm_map_deallocate(task
->map
);
1615 is_release(task
->itk_space
);
1617 ledger_get_entries(task
->ledger
, task_ledgers
.interrupt_wakeups
,
1618 &interrupt_wakeups
, &debit
);
1619 ledger_get_entries(task
->ledger
, task_ledgers
.platform_idle_wakeups
,
1620 &platform_idle_wakeups
, &debit
);
1622 #if defined(CONFIG_SCHED_MULTIQ)
1623 sched_group_destroy(task
->sched_group
);
1626 /* Accumulate statistics for dead tasks */
1627 lck_spin_lock(&dead_task_statistics_lock
);
1628 dead_task_statistics
.total_user_time
+= task
->total_user_time
;
1629 dead_task_statistics
.total_system_time
+= task
->total_system_time
;
1631 dead_task_statistics
.task_interrupt_wakeups
+= interrupt_wakeups
;
1632 dead_task_statistics
.task_platform_idle_wakeups
+= platform_idle_wakeups
;
1634 dead_task_statistics
.task_timer_wakeups_bin_1
+= task
->task_timer_wakeups_bin_1
;
1635 dead_task_statistics
.task_timer_wakeups_bin_2
+= task
->task_timer_wakeups_bin_2
;
1636 dead_task_statistics
.total_ptime
+= task
->total_ptime
;
1637 dead_task_statistics
.total_pset_switches
+= task
->ps_switch
;
1638 dead_task_statistics
.task_gpu_ns
+= task
->task_gpu_ns
;
1639 dead_task_statistics
.task_energy
+= task
->task_energy
;
1641 lck_spin_unlock(&dead_task_statistics_lock
);
1642 lck_mtx_destroy(&task
->lock
, &task_lck_grp
);
1644 if (!ledger_get_entries(task
->ledger
, task_ledgers
.tkm_private
, &credit
,
1646 OSAddAtomic64(credit
, (int64_t *)&tasks_tkm_private
.alloc
);
1647 OSAddAtomic64(debit
, (int64_t *)&tasks_tkm_private
.free
);
1649 if (!ledger_get_entries(task
->ledger
, task_ledgers
.tkm_shared
, &credit
,
1651 OSAddAtomic64(credit
, (int64_t *)&tasks_tkm_shared
.alloc
);
1652 OSAddAtomic64(debit
, (int64_t *)&tasks_tkm_shared
.free
);
1654 ledger_dereference(task
->ledger
);
1656 #if TASK_REFERENCE_LEAK_DEBUG
1657 btlog_remove_entries_for_element(task_ref_btlog
, task
);
1660 #if CONFIG_COALITIONS
1661 task_release_coalitions(task
);
1662 #endif /* CONFIG_COALITIONS */
1664 bzero(task
->coalition
, sizeof(task
->coalition
));
1667 /* clean up collected information since last reference to task is gone */
1668 if (task
->corpse_info
) {
1669 void *corpse_info_kernel
= kcdata_memory_get_begin_addr(task
->corpse_info
);
1670 task_crashinfo_destroy(task
->corpse_info
);
1671 task
->corpse_info
= NULL
;
1672 if (corpse_info_kernel
) {
1673 kfree(corpse_info_kernel
, CORPSEINFO_ALLOCATION_SIZE
);
1679 if (task
->crash_label
) {
1680 mac_exc_free_label(task
->crash_label
);
1681 task
->crash_label
= NULL
;
1685 assert(queue_empty(&task
->task_objq
));
1687 zfree(task_zone
, task
);
1691 * task_name_deallocate:
1693 * Drop a reference on a task name.
1696 task_name_deallocate(
1697 task_name_t task_name
)
1699 return(task_deallocate((task_t
)task_name
));
1703 * task_inspect_deallocate:
1705 * Drop a task inspection reference.
1708 task_inspect_deallocate(
1709 task_inspect_t task_inspect
)
1711 return(task_deallocate((task_t
)task_inspect
));
1715 * task_suspension_token_deallocate:
1717 * Drop a reference on a task suspension token.
1720 task_suspension_token_deallocate(
1721 task_suspension_token_t token
)
1723 return(task_deallocate((task_t
)token
));
1728 * task_collect_crash_info:
1730 * collect crash info from bsd and mach based data
1733 task_collect_crash_info(
1736 struct label
*crash_label
,
1740 kern_return_t kr
= KERN_SUCCESS
;
1742 kcdata_descriptor_t crash_data
= NULL
;
1743 kcdata_descriptor_t crash_data_release
= NULL
;
1744 mach_msg_type_number_t size
= CORPSEINFO_ALLOCATION_SIZE
;
1745 mach_vm_offset_t crash_data_ptr
= 0;
1746 void *crash_data_kernel
= NULL
;
1747 void *crash_data_kernel_release
= NULL
;
1749 struct label
*label
, *free_label
;
1752 if (!corpses_enabled()) {
1753 return KERN_NOT_SUPPORTED
;
1757 free_label
= label
= mac_exc_create_label();
1762 assert(is_corpse_fork
|| task
->bsd_info
!= NULL
);
1763 if (task
->corpse_info
== NULL
&& (is_corpse_fork
|| task
->bsd_info
!= NULL
)) {
1765 /* Set the crash label, used by the exception delivery mac hook */
1766 free_label
= task
->crash_label
; // Most likely NULL.
1767 task
->crash_label
= label
;
1768 mac_exc_update_task_crash_label(task
, crash_label
);
1772 crash_data_kernel
= (void *) kalloc(CORPSEINFO_ALLOCATION_SIZE
);
1773 if (crash_data_kernel
== NULL
) {
1774 kr
= KERN_RESOURCE_SHORTAGE
;
1777 bzero(crash_data_kernel
, CORPSEINFO_ALLOCATION_SIZE
);
1778 crash_data_ptr
= (mach_vm_offset_t
) crash_data_kernel
;
1780 /* Do not get a corpse ref for corpse fork */
1781 crash_data
= task_crashinfo_alloc_init((mach_vm_address_t
)crash_data_ptr
, size
,
1782 is_corpse_fork
? 0 : CORPSE_CRASHINFO_HAS_REF
,
1783 KCFLAG_USE_MEMCOPY
);
1786 crash_data_release
= task
->corpse_info
;
1787 crash_data_kernel_release
= kcdata_memory_get_begin_addr(crash_data_release
);
1788 task
->corpse_info
= crash_data
;
1793 kfree(crash_data_kernel
, CORPSEINFO_ALLOCATION_SIZE
);
1797 if (crash_data_release
!= NULL
) {
1798 task_crashinfo_destroy(crash_data_release
);
1800 if (crash_data_kernel_release
!= NULL
) {
1801 kfree(crash_data_kernel_release
, CORPSEINFO_ALLOCATION_SIZE
);
1809 if (free_label
!= NULL
) {
1810 mac_exc_free_label(free_label
);
1817 * task_deliver_crash_notification:
1819 * Makes outcall to registered host port for a corpse.
1822 task_deliver_crash_notification(
1825 exception_type_t etype
,
1826 mach_exception_subcode_t subcode
)
1828 kcdata_descriptor_t crash_info
= task
->corpse_info
;
1829 thread_t th_iter
= NULL
;
1830 kern_return_t kr
= KERN_SUCCESS
;
1831 wait_interrupt_t wsave
;
1832 mach_exception_data_type_t code
[EXCEPTION_CODE_MAX
];
1833 ipc_port_t task_port
, old_notify
;
1835 if (crash_info
== NULL
)
1836 return KERN_FAILURE
;
1839 if (task_is_a_corpse_fork(task
)) {
1840 /* Populate code with EXC_{RESOURCE,GUARD} for corpse fork */
1844 /* Populate code with EXC_CRASH for corpses */
1845 code
[0] = EXC_CRASH
;
1847 /* Update the code[1] if the boot-arg corpse_for_fatal_memkill is set */
1848 if (corpse_for_fatal_memkill
) {
1853 queue_iterate(&task
->threads
, th_iter
, thread_t
, task_threads
)
1855 if (th_iter
->corpse_dup
== FALSE
) {
1856 ipc_thread_reset(th_iter
);
1861 /* Arm the no-sender notification for taskport */
1862 task_reference(task
);
1863 task_port
= convert_task_to_port(task
);
1865 assert(ip_active(task_port
));
1866 ipc_port_nsrequest(task_port
, task_port
->ip_mscount
, ipc_port_make_sonce_locked(task_port
), &old_notify
);
1868 assert(IP_NULL
== old_notify
);
1870 wsave
= thread_interrupt_level(THREAD_UNINT
);
1871 kr
= exception_triage_thread(EXC_CORPSE_NOTIFY
, code
, EXCEPTION_CODE_MAX
, thread
);
1872 if (kr
!= KERN_SUCCESS
) {
1873 printf("Failed to send exception EXC_CORPSE_NOTIFY. error code: %d for pid %d\n", kr
, task_pid(task
));
1876 (void)thread_interrupt_level(wsave
);
1879 * Drop the send right on task port, will fire the
1880 * no-sender notification if exception deliver failed.
1882 ipc_port_release_send(task_port
);
1889 * Terminate the specified task. See comments on thread_terminate
1890 * (kern/thread.c) about problems with terminating the "current task."
1897 if (task
== TASK_NULL
)
1898 return (KERN_INVALID_ARGUMENT
);
1901 return (KERN_FAILURE
);
1903 return (task_terminate_internal(task
));
1907 extern int proc_pid(struct proc
*);
1908 extern void proc_name_kdp(task_t t
, char *buf
, int size
);
1909 #endif /* MACH_ASSERT */
1911 #define VM_MAP_PARTIAL_REAP 0x54 /* 0x150 */
1913 __unused
task_partial_reap(task_t task
, __unused
int pid
)
1915 unsigned int reclaimed_resident
= 0;
1916 unsigned int reclaimed_compressed
= 0;
1917 uint64_t task_page_count
;
1919 task_page_count
= (get_task_phys_footprint(task
) / PAGE_SIZE_64
);
1921 KERNEL_DEBUG_CONSTANT((MACHDBG_CODE(DBG_MACH_VM
, VM_MAP_PARTIAL_REAP
) | DBG_FUNC_START
),
1922 pid
, task_page_count
, 0, 0, 0);
1924 vm_map_partial_reap(task
->map
, &reclaimed_resident
, &reclaimed_compressed
);
1926 KERNEL_DEBUG_CONSTANT((MACHDBG_CODE(DBG_MACH_VM
, VM_MAP_PARTIAL_REAP
) | DBG_FUNC_END
),
1927 pid
, reclaimed_resident
, reclaimed_compressed
, 0, 0);
1931 task_mark_corpse(task_t task
)
1933 kern_return_t kr
= KERN_SUCCESS
;
1934 thread_t self_thread
;
1936 wait_interrupt_t wsave
;
1938 struct label
*crash_label
= NULL
;
1941 assert(task
!= kernel_task
);
1942 assert(task
== current_task());
1943 assert(!task_is_a_corpse(task
));
1946 crash_label
= mac_exc_create_label_for_proc((struct proc
*)task
->bsd_info
);
1949 kr
= task_collect_crash_info(task
,
1954 if (kr
!= KERN_SUCCESS
) {
1958 self_thread
= current_thread();
1960 wsave
= thread_interrupt_level(THREAD_UNINT
);
1963 task_set_corpse_pending_report(task
);
1964 task_set_corpse(task
);
1965 task
->crashed_thread_id
= thread_tid(self_thread
);
1967 kr
= task_start_halt_locked(task
, TRUE
);
1968 assert(kr
== KERN_SUCCESS
);
1970 ipc_task_reset(task
);
1971 /* Remove the naked send right for task port, needed to arm no sender notification */
1972 task_set_special_port(task
, TASK_KERNEL_PORT
, IPC_PORT_NULL
);
1973 ipc_task_enable(task
);
1976 /* terminate the ipc space */
1977 ipc_space_terminate(task
->itk_space
);
1979 /* Add it to global corpse task list */
1980 task_add_to_corpse_task_list(task
);
1982 task_start_halt(task
);
1983 thread_terminate_internal(self_thread
);
1985 (void) thread_interrupt_level(wsave
);
1986 assert(task
->halting
== TRUE
);
1990 mac_exc_free_label(crash_label
);
1998 * Clears the corpse pending bit on task.
1999 * Removes inspection bit on the threads.
2002 task_clear_corpse(task_t task
)
2004 thread_t th_iter
= NULL
;
2007 queue_iterate(&task
->threads
, th_iter
, thread_t
, task_threads
)
2009 thread_mtx_lock(th_iter
);
2010 th_iter
->inspection
= FALSE
;
2011 thread_mtx_unlock(th_iter
);
2014 thread_terminate_crashed_threads();
2015 /* remove the pending corpse report flag */
2016 task_clear_corpse_pending_report(task
);
2024 * Called whenever the Mach port system detects no-senders on
2025 * the task port of a corpse.
2026 * Each notification that comes in should terminate the task (corpse).
2029 task_port_notify(mach_msg_header_t
*msg
)
2031 mach_no_senders_notification_t
*notification
= (void *)msg
;
2032 ipc_port_t port
= notification
->not_header
.msgh_remote_port
;
2035 assert(ip_active(port
));
2036 assert(IKOT_TASK
== ip_kotype(port
));
2037 task
= (task_t
) port
->ip_kobject
;
2039 assert(task_is_a_corpse(task
));
2041 /* Remove the task from global corpse task list */
2042 task_remove_from_corpse_task_list(task
);
2044 task_clear_corpse(task
);
2045 task_terminate_internal(task
);
2049 * task_wait_till_threads_terminate_locked
2051 * Wait till all the threads in the task are terminated.
2052 * Might release the task lock and re-acquire it.
2055 task_wait_till_threads_terminate_locked(task_t task
)
2057 /* wait for all the threads in the task to terminate */
2058 while (task
->active_thread_count
!= 0) {
2059 assert_wait((event_t
)&task
->active_thread_count
, THREAD_UNINT
);
2061 thread_block(THREAD_CONTINUE_NULL
);
2068 * task_duplicate_map_and_threads
2070 * Copy vmmap of source task.
2071 * Copy active threads from source task to destination task.
2072 * Source task would be suspended during the copy.
2075 task_duplicate_map_and_threads(
2079 thread_t
*thread_ret
,
2080 uint64_t **udata_buffer
,
2084 kern_return_t kr
= KERN_SUCCESS
;
2086 thread_t thread
, self
, thread_return
= THREAD_NULL
;
2087 thread_t new_thread
= THREAD_NULL
, first_thread
= THREAD_NULL
;
2088 thread_t
*thread_array
;
2089 uint32_t active_thread_count
= 0, array_count
= 0, i
;
2091 uint64_t *buffer
= NULL
;
2093 int est_knotes
= 0, num_knotes
= 0;
2095 self
= current_thread();
2098 * Suspend the task to copy thread state, use the internal
2099 * variant so that no user-space process can resume
2100 * the task from under us
2102 kr
= task_suspend_internal(task
);
2103 if (kr
!= KERN_SUCCESS
) {
2107 if (task
->map
->disable_vmentry_reuse
== TRUE
) {
2109 * Quite likely GuardMalloc (or some debugging tool)
2110 * is being used on this task. And it has gone through
2111 * its limit. Making a corpse will likely encounter
2112 * a lot of VM entries that will need COW.
2116 #if DEVELOPMENT || DEBUG
2117 memorystatus_abort_vm_map_fork(task
);
2119 task_resume_internal(task
);
2120 return KERN_FAILURE
;
2123 /* Check with VM if vm_map_fork is allowed for this task */
2124 if (memorystatus_allowed_vm_map_fork(task
)) {
2126 /* Setup new task's vmmap, switch from parent task's map to it COW map */
2127 oldmap
= new_task
->map
;
2128 new_task
->map
= vm_map_fork(new_task
->ledger
,
2130 (VM_MAP_FORK_SHARE_IF_INHERIT_NONE
|
2131 VM_MAP_FORK_PRESERVE_PURGEABLE
|
2132 VM_MAP_FORK_CORPSE_FOOTPRINT
));
2133 vm_map_deallocate(oldmap
);
2135 /* copy ledgers that impact the memory footprint */
2136 vm_map_copy_footprint_ledgers(task
, new_task
);
2138 /* Get all the udata pointers from kqueue */
2139 est_knotes
= kevent_proc_copy_uptrs(p
, NULL
, 0);
2140 if (est_knotes
> 0) {
2141 buf_size
= (est_knotes
+ 32) * sizeof(uint64_t);
2142 buffer
= (uint64_t *) kalloc(buf_size
);
2143 num_knotes
= kevent_proc_copy_uptrs(p
, buffer
, buf_size
);
2144 if (num_knotes
> est_knotes
+ 32) {
2145 num_knotes
= est_knotes
+ 32;
2150 active_thread_count
= task
->active_thread_count
;
2151 if (active_thread_count
== 0) {
2152 if (buffer
!= NULL
) {
2153 kfree(buffer
, buf_size
);
2155 task_resume_internal(task
);
2156 return KERN_FAILURE
;
2159 thread_array
= (thread_t
*) kalloc(sizeof(thread_t
) * active_thread_count
);
2161 /* Iterate all the threads and drop the task lock before calling thread_create_with_continuation */
2163 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
2164 /* Skip inactive threads */
2165 active
= thread
->active
;
2170 if (array_count
>= active_thread_count
) {
2174 thread_array
[array_count
++] = thread
;
2175 thread_reference(thread
);
2179 for (i
= 0; i
< array_count
; i
++) {
2181 kr
= thread_create_with_continuation(new_task
, &new_thread
, (thread_continue_t
)thread_corpse_continue
);
2182 if (kr
!= KERN_SUCCESS
) {
2186 /* Equivalent of current thread in corpse */
2187 if (thread_array
[i
] == self
) {
2188 thread_return
= new_thread
;
2189 new_task
->crashed_thread_id
= thread_tid(new_thread
);
2190 } else if (first_thread
== NULL
) {
2191 first_thread
= new_thread
;
2193 /* drop the extra ref returned by thread_create_with_continuation */
2194 thread_deallocate(new_thread
);
2197 kr
= thread_dup2(thread_array
[i
], new_thread
);
2198 if (kr
!= KERN_SUCCESS
) {
2199 thread_mtx_lock(new_thread
);
2200 new_thread
->corpse_dup
= TRUE
;
2201 thread_mtx_unlock(new_thread
);
2205 /* Copy thread name */
2206 bsd_copythreadname(new_thread
->uthread
, thread_array
[i
]->uthread
);
2207 new_thread
->thread_tag
= thread_array
[i
]->thread_tag
;
2208 thread_copy_resource_info(new_thread
, thread_array
[i
]);
2211 /* return the first thread if we couldn't find the equivalent of current */
2212 if (thread_return
== THREAD_NULL
) {
2213 thread_return
= first_thread
;
2215 else if (first_thread
!= THREAD_NULL
) {
2216 /* drop the extra ref returned by thread_create_with_continuation */
2217 thread_deallocate(first_thread
);
2220 task_resume_internal(task
);
2222 for (i
= 0; i
< array_count
; i
++) {
2223 thread_deallocate(thread_array
[i
]);
2225 kfree(thread_array
, sizeof(thread_t
) * active_thread_count
);
2227 if (kr
== KERN_SUCCESS
) {
2228 *thread_ret
= thread_return
;
2229 *udata_buffer
= buffer
;
2231 *num_udata
= num_knotes
;
2233 if (thread_return
!= THREAD_NULL
) {
2234 thread_deallocate(thread_return
);
2236 if (buffer
!= NULL
) {
2237 kfree(buffer
, buf_size
);
2244 #if CONFIG_SECLUDED_MEMORY
2245 extern void task_set_can_use_secluded_mem_locked(
2247 boolean_t can_use_secluded_mem
);
2248 #endif /* CONFIG_SECLUDED_MEMORY */
2251 task_terminate_internal(
2254 thread_t thread
, self
;
2256 boolean_t interrupt_save
;
2259 assert(task
!= kernel_task
);
2261 self
= current_thread();
2262 self_task
= self
->task
;
2265 * Get the task locked and make sure that we are not racing
2266 * with someone else trying to terminate us.
2268 if (task
== self_task
)
2271 if (task
< self_task
) {
2273 task_lock(self_task
);
2276 task_lock(self_task
);
2280 #if CONFIG_SECLUDED_MEMORY
2281 if (task
->task_can_use_secluded_mem
) {
2282 task_set_can_use_secluded_mem_locked(task
, FALSE
);
2284 task
->task_could_use_secluded_mem
= FALSE
;
2285 task
->task_could_also_use_secluded_mem
= FALSE
;
2287 if (task
->task_suppressed_secluded
) {
2288 stop_secluded_suppression(task
);
2290 #endif /* CONFIG_SECLUDED_MEMORY */
2292 if (!task
->active
) {
2294 * Task is already being terminated.
2295 * Just return an error. If we are dying, this will
2296 * just get us to our AST special handler and that
2297 * will get us to finalize the termination of ourselves.
2300 if (self_task
!= task
)
2301 task_unlock(self_task
);
2303 return (KERN_FAILURE
);
2306 if (task_corpse_pending_report(task
)) {
2308 * Task is marked for reporting as corpse.
2309 * Just return an error. This will
2310 * just get us to our AST special handler and that
2311 * will get us to finish the path to death
2314 if (self_task
!= task
)
2315 task_unlock(self_task
);
2317 return (KERN_FAILURE
);
2320 if (self_task
!= task
)
2321 task_unlock(self_task
);
2324 * Make sure the current thread does not get aborted out of
2325 * the waits inside these operations.
2327 interrupt_save
= thread_interrupt_level(THREAD_UNINT
);
2330 * Indicate that we want all the threads to stop executing
2331 * at user space by holding the task (we would have held
2332 * each thread independently in thread_terminate_internal -
2333 * but this way we may be more likely to already find it
2334 * held there). Mark the task inactive, and prevent
2335 * further task operations via the task port.
2337 task_hold_locked(task
);
2338 task
->active
= FALSE
;
2339 ipc_task_disable(task
);
2341 #if CONFIG_TELEMETRY
2343 * Notify telemetry that this task is going away.
2345 telemetry_task_ctl_locked(task
, TF_TELEMETRY
, 0);
2349 * Terminate each thread in the task.
2351 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
2352 thread_terminate_internal(thread
);
2356 if (task
->bsd_info
!= NULL
&& !task_is_exec_copy(task
)) {
2357 pid
= proc_pid(task
->bsd_info
);
2359 #endif /* MACH_BSD */
2363 proc_set_task_policy(task
, TASK_POLICY_ATTRIBUTE
,
2364 TASK_POLICY_TERMINATED
, TASK_POLICY_ENABLE
);
2366 /* Early object reap phase */
2368 // PR-17045188: Revisit implementation
2369 // task_partial_reap(task, pid);
2373 * remove all task watchers
2375 task_removewatchers(task
);
2377 #endif /* CONFIG_EMBEDDED */
2380 * Destroy all synchronizers owned by the task.
2382 task_synchronizer_destroy_all(task
);
2385 * Destroy the IPC space, leaving just a reference for it.
2387 ipc_space_terminate(task
->itk_space
);
2390 /* if some ledgers go negative on tear-down again... */
2391 ledger_disable_panic_on_negative(task
->map
->pmap
->ledger
,
2392 task_ledgers
.phys_footprint
);
2393 ledger_disable_panic_on_negative(task
->map
->pmap
->ledger
,
2394 task_ledgers
.internal
);
2395 ledger_disable_panic_on_negative(task
->map
->pmap
->ledger
,
2396 task_ledgers
.internal_compressed
);
2397 ledger_disable_panic_on_negative(task
->map
->pmap
->ledger
,
2398 task_ledgers
.iokit_mapped
);
2399 ledger_disable_panic_on_negative(task
->map
->pmap
->ledger
,
2400 task_ledgers
.alternate_accounting
);
2401 ledger_disable_panic_on_negative(task
->map
->pmap
->ledger
,
2402 task_ledgers
.alternate_accounting_compressed
);
2406 * If the current thread is a member of the task
2407 * being terminated, then the last reference to
2408 * the task will not be dropped until the thread
2409 * is finally reaped. To avoid incurring the
2410 * expense of removing the address space regions
2411 * at reap time, we do it explictly here.
2414 vm_map_lock(task
->map
);
2415 vm_map_disable_hole_optimization(task
->map
);
2416 vm_map_unlock(task
->map
);
2420 * Identify the pmap's process, in case the pmap ledgers drift
2421 * and we have to report it.
2424 if (task
->bsd_info
&& !task_is_exec_copy(task
)) {
2425 pid
= proc_pid(task
->bsd_info
);
2426 proc_name_kdp(task
, procname
, sizeof (procname
));
2429 strlcpy(procname
, "<unknown>", sizeof (procname
));
2431 pmap_set_process(task
->map
->pmap
, pid
, procname
);
2432 #endif /* MACH_ASSERT */
2434 vm_map_remove(task
->map
,
2435 task
->map
->min_offset
,
2436 task
->map
->max_offset
,
2440 * + remove immutable mappings
2441 * + allow gaps in range
2443 (VM_MAP_REMOVE_NO_UNNESTING
|
2444 VM_MAP_REMOVE_IMMUTABLE
|
2445 VM_MAP_REMOVE_GAPS_OK
));
2447 /* release our shared region */
2448 vm_shared_region_set(task
, NULL
);
2451 lck_mtx_lock(&tasks_threads_lock
);
2452 queue_remove(&tasks
, task
, task_t
, tasks
);
2453 queue_enter(&terminated_tasks
, task
, task_t
, tasks
);
2455 terminated_tasks_count
++;
2456 lck_mtx_unlock(&tasks_threads_lock
);
2459 * We no longer need to guard against being aborted, so restore
2460 * the previous interruptible state.
2462 thread_interrupt_level(interrupt_save
);
2465 /* force the task to release all ctrs */
2466 if (task
->t_kpc
& TASK_KPC_FORCED_ALL_CTRS
)
2467 kpc_force_all_ctrs(task
, 0);
2470 #if CONFIG_COALITIONS
2472 * Leave our coalitions. (drop activation but not reference)
2474 coalitions_remove_task(task
);
2478 * Get rid of the task active reference on itself.
2480 task_deallocate(task
);
2482 return (KERN_SUCCESS
);
2486 tasks_system_suspend(boolean_t suspend
)
2490 lck_mtx_lock(&tasks_threads_lock
);
2491 assert(tasks_suspend_state
!= suspend
);
2492 tasks_suspend_state
= suspend
;
2493 queue_iterate(&tasks
, task
, task_t
, tasks
) {
2494 if (task
== kernel_task
) {
2497 suspend
? task_suspend_internal(task
) : task_resume_internal(task
);
2499 lck_mtx_unlock(&tasks_threads_lock
);
2505 * Shut the current task down (except for the current thread) in
2506 * preparation for dramatic changes to the task (probably exec).
2507 * We hold the task and mark all other threads in the task for
2511 task_start_halt(task_t task
)
2513 kern_return_t kr
= KERN_SUCCESS
;
2515 kr
= task_start_halt_locked(task
, FALSE
);
2520 static kern_return_t
2521 task_start_halt_locked(task_t task
, boolean_t should_mark_corpse
)
2523 thread_t thread
, self
;
2524 uint64_t dispatchqueue_offset
;
2526 assert(task
!= kernel_task
);
2528 self
= current_thread();
2530 if (task
!= self
->task
&& !task_is_a_corpse_fork(task
))
2531 return (KERN_INVALID_ARGUMENT
);
2533 if (task
->halting
|| !task
->active
|| !self
->active
) {
2535 * Task or current thread is already being terminated.
2536 * Hurry up and return out of the current kernel context
2537 * so that we run our AST special handler to terminate
2540 return (KERN_FAILURE
);
2543 task
->halting
= TRUE
;
2546 * Mark all the threads to keep them from starting any more
2547 * user-level execution. The thread_terminate_internal code
2548 * would do this on a thread by thread basis anyway, but this
2549 * gives us a better chance of not having to wait there.
2551 task_hold_locked(task
);
2552 dispatchqueue_offset
= get_dispatchqueue_offset_from_proc(task
->bsd_info
);
2555 * Terminate all the other threads in the task.
2557 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
)
2559 if (should_mark_corpse
) {
2560 thread_mtx_lock(thread
);
2561 thread
->inspection
= TRUE
;
2562 thread_mtx_unlock(thread
);
2565 thread_terminate_internal(thread
);
2567 task
->dispatchqueue_offset
= dispatchqueue_offset
;
2569 task_release_locked(task
);
2571 return KERN_SUCCESS
;
2576 * task_complete_halt:
2578 * Complete task halt by waiting for threads to terminate, then clean
2579 * up task resources (VM, port namespace, etc...) and then let the
2580 * current thread go in the (practically empty) task context.
2582 * Note: task->halting flag is not cleared in order to avoid creation
2583 * of new thread in old exec'ed task.
2586 task_complete_halt(task_t task
)
2589 assert(task
->halting
);
2590 assert(task
== current_task());
2593 * Wait for the other threads to get shut down.
2594 * When the last other thread is reaped, we'll be
2597 if (task
->thread_count
> 1) {
2598 assert_wait((event_t
)&task
->halting
, THREAD_UNINT
);
2600 thread_block(THREAD_CONTINUE_NULL
);
2606 * Give the machine dependent code a chance
2607 * to perform cleanup of task-level resources
2608 * associated with the current thread before
2609 * ripping apart the task.
2611 machine_task_terminate(task
);
2614 * Destroy all synchronizers owned by the task.
2616 task_synchronizer_destroy_all(task
);
2619 * Destroy the contents of the IPC space, leaving just
2620 * a reference for it.
2622 ipc_space_clean(task
->itk_space
);
2625 * Clean out the address space, as we are going to be
2626 * getting a new one.
2628 vm_map_remove(task
->map
, task
->map
->min_offset
,
2629 task
->map
->max_offset
,
2633 * + remove immutable mappings
2634 * + allow gaps in the range
2636 (VM_MAP_REMOVE_NO_UNNESTING
|
2637 VM_MAP_REMOVE_IMMUTABLE
|
2638 VM_MAP_REMOVE_GAPS_OK
));
2641 * Kick out any IOKitUser handles to the task. At best they're stale,
2642 * at worst someone is racing a SUID exec.
2644 iokit_task_terminate(task
);
2650 * Suspend execution of the specified task.
2651 * This is a recursive-style suspension of the task, a count of
2652 * suspends is maintained.
2654 * CONDITIONS: the task is locked and active.
2662 assert(task
->active
);
2664 if (task
->suspend_count
++ > 0)
2667 if (task
->bsd_info
) {
2668 workq_proc_suspended(task
->bsd_info
);
2672 * Iterate through all the threads and hold them.
2674 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
2675 thread_mtx_lock(thread
);
2676 thread_hold(thread
);
2677 thread_mtx_unlock(thread
);
2684 * Same as the internal routine above, except that is must lock
2685 * and verify that the task is active. This differs from task_suspend
2686 * in that it places a kernel hold on the task rather than just a
2687 * user-level hold. This keeps users from over resuming and setting
2688 * it running out from under the kernel.
2690 * CONDITIONS: the caller holds a reference on the task
2696 if (task
== TASK_NULL
)
2697 return (KERN_INVALID_ARGUMENT
);
2701 if (!task
->active
) {
2704 return (KERN_FAILURE
);
2707 task_hold_locked(task
);
2710 return (KERN_SUCCESS
);
2716 boolean_t until_not_runnable
)
2718 if (task
== TASK_NULL
)
2719 return (KERN_INVALID_ARGUMENT
);
2723 if (!task
->active
) {
2726 return (KERN_FAILURE
);
2729 task_wait_locked(task
, until_not_runnable
);
2732 return (KERN_SUCCESS
);
2738 * Wait for all threads in task to stop.
2741 * Called with task locked, active, and held.
2746 boolean_t until_not_runnable
)
2748 thread_t thread
, self
;
2750 assert(task
->active
);
2751 assert(task
->suspend_count
> 0);
2753 self
= current_thread();
2756 * Iterate through all the threads and wait for them to
2757 * stop. Do not wait for the current thread if it is within
2760 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
2762 thread_wait(thread
, until_not_runnable
);
2767 * task_release_locked:
2769 * Release a kernel hold on a task.
2771 * CONDITIONS: the task is locked and active
2774 task_release_locked(
2779 assert(task
->active
);
2780 assert(task
->suspend_count
> 0);
2782 if (--task
->suspend_count
> 0)
2785 if (task
->bsd_info
) {
2786 workq_proc_resumed(task
->bsd_info
);
2789 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
2790 thread_mtx_lock(thread
);
2791 thread_release(thread
);
2792 thread_mtx_unlock(thread
);
2799 * Same as the internal routine above, except that it must lock
2800 * and verify that the task is active.
2802 * CONDITIONS: The caller holds a reference to the task
2808 if (task
== TASK_NULL
)
2809 return (KERN_INVALID_ARGUMENT
);
2813 if (!task
->active
) {
2816 return (KERN_FAILURE
);
2819 task_release_locked(task
);
2822 return (KERN_SUCCESS
);
2828 thread_act_array_t
*threads_out
,
2829 mach_msg_type_number_t
*count
)
2831 mach_msg_type_number_t actual
;
2832 thread_t
*thread_list
;
2834 vm_size_t size
, size_needed
;
2838 if (task
== TASK_NULL
)
2839 return (KERN_INVALID_ARGUMENT
);
2841 size
= 0; addr
= NULL
;
2845 if (!task
->active
) {
2851 return (KERN_FAILURE
);
2854 actual
= task
->thread_count
;
2856 /* do we have the memory we need? */
2857 size_needed
= actual
* sizeof (mach_port_t
);
2858 if (size_needed
<= size
)
2861 /* unlock the task and allocate more memory */
2867 assert(size_needed
> 0);
2870 addr
= kalloc(size
);
2872 return (KERN_RESOURCE_SHORTAGE
);
2875 /* OK, have memory and the task is locked & active */
2876 thread_list
= (thread_t
*)addr
;
2880 for (thread
= (thread_t
)queue_first(&task
->threads
); i
< actual
;
2881 ++i
, thread
= (thread_t
)queue_next(&thread
->task_threads
)) {
2882 thread_reference_internal(thread
);
2883 thread_list
[j
++] = thread
;
2886 assert(queue_end(&task
->threads
, (queue_entry_t
)thread
));
2889 size_needed
= actual
* sizeof (mach_port_t
);
2891 /* can unlock task now that we've got the thread refs */
2895 /* no threads, so return null pointer and deallocate memory */
2897 *threads_out
= NULL
;
2904 /* if we allocated too much, must copy */
2906 if (size_needed
< size
) {
2909 newaddr
= kalloc(size_needed
);
2911 for (i
= 0; i
< actual
; ++i
)
2912 thread_deallocate(thread_list
[i
]);
2914 return (KERN_RESOURCE_SHORTAGE
);
2917 bcopy(addr
, newaddr
, size_needed
);
2919 thread_list
= (thread_t
*)newaddr
;
2922 *threads_out
= thread_list
;
2925 /* do the conversion that Mig should handle */
2927 for (i
= 0; i
< actual
; ++i
)
2928 ((ipc_port_t
*) thread_list
)[i
] = convert_thread_to_port(thread_list
[i
]);
2931 return (KERN_SUCCESS
);
2934 #define TASK_HOLD_NORMAL 0
2935 #define TASK_HOLD_PIDSUSPEND 1
2936 #define TASK_HOLD_LEGACY 2
2937 #define TASK_HOLD_LEGACY_ALL 3
2939 static kern_return_t
2944 if (!task
->active
&& !task_is_a_corpse(task
)) {
2945 return (KERN_FAILURE
);
2948 /* Return success for corpse task */
2949 if (task_is_a_corpse(task
)) {
2950 return KERN_SUCCESS
;
2953 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
2954 MACHDBG_CODE(DBG_MACH_IPC
,MACH_TASK_SUSPEND
) | DBG_FUNC_NONE
,
2955 task_pid(task
), ((thread_t
)queue_first(&task
->threads
))->thread_id
,
2956 task
->user_stop_count
, task
->user_stop_count
+ 1, 0);
2959 current_task()->suspends_outstanding
++;
2962 if (mode
== TASK_HOLD_LEGACY
)
2963 task
->legacy_stop_count
++;
2965 if (task
->user_stop_count
++ > 0) {
2967 * If the stop count was positive, the task is
2968 * already stopped and we can exit.
2970 return (KERN_SUCCESS
);
2974 * Put a kernel-level hold on the threads in the task (all
2975 * user-level task suspensions added together represent a
2976 * single kernel-level hold). We then wait for the threads
2977 * to stop executing user code.
2979 task_hold_locked(task
);
2980 task_wait_locked(task
, FALSE
);
2982 return (KERN_SUCCESS
);
2985 static kern_return_t
2990 boolean_t release
= FALSE
;
2992 if (!task
->active
&& !task_is_a_corpse(task
)) {
2993 return (KERN_FAILURE
);
2996 /* Return success for corpse task */
2997 if (task_is_a_corpse(task
)) {
2998 return KERN_SUCCESS
;
3001 if (mode
== TASK_HOLD_PIDSUSPEND
) {
3002 if (task
->pidsuspended
== FALSE
) {
3003 return (KERN_FAILURE
);
3005 task
->pidsuspended
= FALSE
;
3008 if (task
->user_stop_count
> (task
->pidsuspended
? 1 : 0)) {
3010 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
3011 MACHDBG_CODE(DBG_MACH_IPC
,MACH_TASK_RESUME
) | DBG_FUNC_NONE
,
3012 task_pid(task
), ((thread_t
)queue_first(&task
->threads
))->thread_id
,
3013 task
->user_stop_count
, mode
, task
->legacy_stop_count
);
3017 * This is obviously not robust; if we suspend one task and then resume a different one,
3018 * we'll fly under the radar. This is only meant to catch the common case of a crashed
3019 * or buggy suspender.
3021 current_task()->suspends_outstanding
--;
3024 if (mode
== TASK_HOLD_LEGACY_ALL
) {
3025 if (task
->legacy_stop_count
>= task
->user_stop_count
) {
3026 task
->user_stop_count
= 0;
3029 task
->user_stop_count
-= task
->legacy_stop_count
;
3031 task
->legacy_stop_count
= 0;
3033 if (mode
== TASK_HOLD_LEGACY
&& task
->legacy_stop_count
> 0)
3034 task
->legacy_stop_count
--;
3035 if (--task
->user_stop_count
== 0)
3040 return (KERN_FAILURE
);
3044 * Release the task if necessary.
3047 task_release_locked(task
);
3049 return (KERN_SUCCESS
);
3056 * Implement an (old-fashioned) user-level suspension on a task.
3058 * Because the user isn't expecting to have to manage a suspension
3059 * token, we'll track it for him in the kernel in the form of a naked
3060 * send right to the task's resume port. All such send rights
3061 * account for a single suspension against the task (unlike task_suspend2()
3062 * where each caller gets a unique suspension count represented by a
3063 * unique send-once right).
3066 * The caller holds a reference to the task
3073 mach_port_t port
, send
, old_notify
;
3074 mach_port_name_t name
;
3076 if (task
== TASK_NULL
|| task
== kernel_task
)
3077 return (KERN_INVALID_ARGUMENT
);
3082 * Claim a send right on the task resume port, and request a no-senders
3083 * notification on that port (if none outstanding).
3085 if (task
->itk_resume
== IP_NULL
) {
3086 task
->itk_resume
= ipc_port_alloc_kernel();
3087 if (!IP_VALID(task
->itk_resume
))
3088 panic("failed to create resume port");
3089 ipc_kobject_set(task
->itk_resume
, (ipc_kobject_t
)task
, IKOT_TASK_RESUME
);
3092 port
= task
->itk_resume
;
3094 assert(ip_active(port
));
3096 send
= ipc_port_make_send_locked(port
);
3097 assert(IP_VALID(send
));
3099 if (port
->ip_nsrequest
== IP_NULL
) {
3100 ipc_port_nsrequest(port
, port
->ip_mscount
, ipc_port_make_sonce_locked(port
), &old_notify
);
3101 assert(old_notify
== IP_NULL
);
3108 * place a legacy hold on the task.
3110 kr
= place_task_hold(task
, TASK_HOLD_LEGACY
);
3111 if (kr
!= KERN_SUCCESS
) {
3113 ipc_port_release_send(send
);
3120 * Copyout the send right into the calling task's IPC space. It won't know it is there,
3121 * but we'll look it up when calling a traditional resume. Any IPC operations that
3122 * deallocate the send right will auto-release the suspension.
3124 if ((kr
= ipc_kmsg_copyout_object(current_task()->itk_space
, (ipc_object_t
)send
,
3125 MACH_MSG_TYPE_MOVE_SEND
, &name
)) != KERN_SUCCESS
) {
3126 printf("warning: %s(%d) failed to copyout suspension token for pid %d with error: %d\n",
3127 proc_name_address(current_task()->bsd_info
), proc_pid(current_task()->bsd_info
),
3128 task_pid(task
), kr
);
3137 * Release a user hold on a task.
3140 * The caller holds a reference to the task
3147 mach_port_name_t resume_port_name
;
3148 ipc_entry_t resume_port_entry
;
3149 ipc_space_t space
= current_task()->itk_space
;
3151 if (task
== TASK_NULL
|| task
== kernel_task
)
3152 return (KERN_INVALID_ARGUMENT
);
3154 /* release a legacy task hold */
3156 kr
= release_task_hold(task
, TASK_HOLD_LEGACY
);
3159 is_write_lock(space
);
3160 if (is_active(space
) && IP_VALID(task
->itk_resume
) &&
3161 ipc_hash_lookup(space
, (ipc_object_t
)task
->itk_resume
, &resume_port_name
, &resume_port_entry
) == TRUE
) {
3163 * We found a suspension token in the caller's IPC space. Release a send right to indicate that
3164 * we are holding one less legacy hold on the task from this caller. If the release failed,
3165 * go ahead and drop all the rights, as someone either already released our holds or the task
3168 if (kr
== KERN_SUCCESS
)
3169 ipc_right_dealloc(space
, resume_port_name
, resume_port_entry
);
3171 ipc_right_destroy(space
, resume_port_name
, resume_port_entry
, FALSE
, 0);
3172 /* space unlocked */
3174 is_write_unlock(space
);
3175 if (kr
== KERN_SUCCESS
)
3176 printf("warning: %s(%d) performed out-of-band resume on pid %d\n",
3177 proc_name_address(current_task()->bsd_info
), proc_pid(current_task()->bsd_info
),
3185 * Suspend the target task.
3186 * Making/holding a token/reference/port is the callers responsibility.
3189 task_suspend_internal(task_t task
)
3193 if (task
== TASK_NULL
|| task
== kernel_task
)
3194 return (KERN_INVALID_ARGUMENT
);
3197 kr
= place_task_hold(task
, TASK_HOLD_NORMAL
);
3203 * Suspend the target task, and return a suspension token. The token
3204 * represents a reference on the suspended task.
3209 task_suspension_token_t
*suspend_token
)
3213 kr
= task_suspend_internal(task
);
3214 if (kr
!= KERN_SUCCESS
) {
3215 *suspend_token
= TASK_NULL
;
3220 * Take a reference on the target task and return that to the caller
3221 * as a "suspension token," which can be converted into an SO right to
3222 * the now-suspended task's resume port.
3224 task_reference_internal(task
);
3225 *suspend_token
= task
;
3227 return (KERN_SUCCESS
);
3232 * (reference/token/port management is caller's responsibility).
3235 task_resume_internal(
3236 task_suspension_token_t task
)
3240 if (task
== TASK_NULL
|| task
== kernel_task
)
3241 return (KERN_INVALID_ARGUMENT
);
3244 kr
= release_task_hold(task
, TASK_HOLD_NORMAL
);
3250 * Resume the task using a suspension token. Consumes the token's ref.
3254 task_suspension_token_t task
)
3258 kr
= task_resume_internal(task
);
3259 task_suspension_token_deallocate(task
);
3265 task_suspension_notify(mach_msg_header_t
*request_header
)
3267 ipc_port_t port
= (ipc_port_t
) request_header
->msgh_remote_port
;
3268 task_t task
= convert_port_to_task_suspension_token(port
);
3269 mach_msg_type_number_t not_count
;
3271 if (task
== TASK_NULL
|| task
== kernel_task
)
3272 return TRUE
; /* nothing to do */
3274 switch (request_header
->msgh_id
) {
3276 case MACH_NOTIFY_SEND_ONCE
:
3277 /* release the hold held by this specific send-once right */
3279 release_task_hold(task
, TASK_HOLD_NORMAL
);
3283 case MACH_NOTIFY_NO_SENDERS
:
3284 not_count
= ((mach_no_senders_notification_t
*)request_header
)->not_count
;
3288 if (port
->ip_mscount
== not_count
) {
3290 /* release all the [remaining] outstanding legacy holds */
3291 assert(port
->ip_nsrequest
== IP_NULL
);
3293 release_task_hold(task
, TASK_HOLD_LEGACY_ALL
);
3296 } else if (port
->ip_nsrequest
== IP_NULL
) {
3297 ipc_port_t old_notify
;
3300 /* new send rights, re-arm notification at current make-send count */
3301 ipc_port_nsrequest(port
, port
->ip_mscount
, ipc_port_make_sonce_locked(port
), &old_notify
);
3302 assert(old_notify
== IP_NULL
);
3314 task_suspension_token_deallocate(task
); /* drop token reference */
3319 task_pidsuspend_locked(task_t task
)
3323 if (task
->pidsuspended
) {
3328 task
->pidsuspended
= TRUE
;
3330 kr
= place_task_hold(task
, TASK_HOLD_PIDSUSPEND
);
3331 if (kr
!= KERN_SUCCESS
) {
3332 task
->pidsuspended
= FALSE
;
3342 * Suspends a task by placing a hold on its threads.
3345 * The caller holds a reference to the task
3353 if (task
== TASK_NULL
|| task
== kernel_task
)
3354 return (KERN_INVALID_ARGUMENT
);
3358 kr
= task_pidsuspend_locked(task
);
3367 * Resumes a previously suspended task.
3370 * The caller holds a reference to the task
3378 if (task
== TASK_NULL
|| task
== kernel_task
)
3379 return (KERN_INVALID_ARGUMENT
);
3385 while (task
->changing_freeze_state
) {
3387 assert_wait((event_t
)&task
->changing_freeze_state
, THREAD_UNINT
);
3389 thread_block(THREAD_CONTINUE_NULL
);
3393 task
->changing_freeze_state
= TRUE
;
3396 kr
= release_task_hold(task
, TASK_HOLD_PIDSUSPEND
);
3404 if (kr
== KERN_SUCCESS
)
3405 task
->frozen
= FALSE
;
3406 task
->changing_freeze_state
= FALSE
;
3407 thread_wakeup(&task
->changing_freeze_state
);
3416 #if DEVELOPMENT || DEBUG
3418 extern void IOSleep(int);
3421 task_disconnect_page_mappings(task_t task
)
3425 if (task
== TASK_NULL
|| task
== kernel_task
)
3426 return (KERN_INVALID_ARGUMENT
);
3429 * this function is used to strip all of the mappings from
3430 * the pmap for the specified task to force the task to
3431 * re-fault all of the pages it is actively using... this
3432 * allows us to approximate the true working set of the
3433 * specified task. We only engage if at least 1 of the
3434 * threads in the task is runnable, but we want to continuously
3435 * sweep (at least for a while - I've arbitrarily set the limit at
3436 * 100 sweeps to be re-looked at as we gain experience) to get a better
3437 * view into what areas within a page are being visited (as opposed to only
3438 * seeing the first fault of a page after the task becomes
3439 * runnable)... in the future I may
3440 * try to block until awakened by a thread in this task
3441 * being made runnable, but for now we'll periodically poll from the
3442 * user level debug tool driving the sysctl
3444 for (n
= 0; n
< 100; n
++) {
3447 boolean_t do_unnest
;
3455 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
3457 if (thread
->state
& TH_RUN
) {
3463 task
->task_disconnected_count
++;
3465 if (task
->task_unnested
== FALSE
) {
3466 if (runnable
== TRUE
) {
3467 task
->task_unnested
= TRUE
;
3473 if (runnable
== FALSE
)
3476 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
, (MACHDBG_CODE(DBG_MACH_WORKINGSET
, VM_DISCONNECT_TASK_PAGE_MAPPINGS
)) | DBG_FUNC_START
,
3477 task
, do_unnest
, task
->task_disconnected_count
, 0, 0);
3479 page_count
= vm_map_disconnect_page_mappings(task
->map
, do_unnest
);
3481 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
, (MACHDBG_CODE(DBG_MACH_WORKINGSET
, VM_DISCONNECT_TASK_PAGE_MAPPINGS
)) | DBG_FUNC_END
,
3482 task
, page_count
, 0, 0, 0);
3487 return (KERN_SUCCESS
);
3501 * The caller holds a reference to the task
3503 extern void vm_wake_compactor_swapper(void);
3504 extern queue_head_t c_swapout_list_head
;
3509 uint32_t *purgeable_count
,
3510 uint32_t *wired_count
,
3511 uint32_t *clean_count
,
3512 uint32_t *dirty_count
,
3513 uint32_t dirty_budget
,
3514 uint32_t *shared_count
,
3515 int *freezer_error_code
,
3516 boolean_t eval_only
)
3518 kern_return_t kr
= KERN_SUCCESS
;
3520 if (task
== TASK_NULL
|| task
== kernel_task
)
3521 return (KERN_INVALID_ARGUMENT
);
3525 while (task
->changing_freeze_state
) {
3527 assert_wait((event_t
)&task
->changing_freeze_state
, THREAD_UNINT
);
3529 thread_block(THREAD_CONTINUE_NULL
);
3535 return (KERN_FAILURE
);
3537 task
->changing_freeze_state
= TRUE
;
3541 kr
= vm_map_freeze(task
->map
,
3553 if ((kr
== KERN_SUCCESS
) && (eval_only
== FALSE
)) {
3554 task
->frozen
= TRUE
;
3557 task
->changing_freeze_state
= FALSE
;
3558 thread_wakeup(&task
->changing_freeze_state
);
3562 if (VM_CONFIG_COMPRESSOR_IS_PRESENT
&&
3563 (eval_only
== FALSE
)) {
3564 vm_wake_compactor_swapper();
3566 * We do an explicit wakeup of the swapout thread here
3567 * because the compact_and_swap routines don't have
3568 * knowledge about these kind of "per-task packed c_segs"
3569 * and so will not be evaluating whether we need to do
3572 thread_wakeup((event_t
)&c_swapout_list_head
);
3581 * Thaw a currently frozen task.
3584 * The caller holds a reference to the task
3590 if (task
== TASK_NULL
|| task
== kernel_task
)
3591 return (KERN_INVALID_ARGUMENT
);
3595 while (task
->changing_freeze_state
) {
3597 assert_wait((event_t
)&task
->changing_freeze_state
, THREAD_UNINT
);
3599 thread_block(THREAD_CONTINUE_NULL
);
3603 if (!task
->frozen
) {
3605 return (KERN_FAILURE
);
3607 task
->frozen
= FALSE
;
3611 return (KERN_SUCCESS
);
3614 #endif /* CONFIG_FREEZE */
3617 host_security_set_task_token(
3618 host_security_t host_security
,
3620 security_token_t sec_token
,
3621 audit_token_t audit_token
,
3622 host_priv_t host_priv
)
3624 ipc_port_t host_port
;
3627 if (task
== TASK_NULL
)
3628 return(KERN_INVALID_ARGUMENT
);
3630 if (host_security
== HOST_NULL
)
3631 return(KERN_INVALID_SECURITY
);
3634 task
->sec_token
= sec_token
;
3635 task
->audit_token
= audit_token
;
3639 if (host_priv
!= HOST_PRIV_NULL
) {
3640 kr
= host_get_host_priv_port(host_priv
, &host_port
);
3642 kr
= host_get_host_port(host_priv_self(), &host_port
);
3644 assert(kr
== KERN_SUCCESS
);
3645 kr
= task_set_special_port(task
, TASK_HOST_PORT
, host_port
);
3650 task_send_trace_memory(
3651 __unused task_t target_task
,
3652 __unused
uint32_t pid
,
3653 __unused
uint64_t uniqueid
)
3655 return KERN_INVALID_ARGUMENT
;
3659 * This routine was added, pretty much exclusively, for registering the
3660 * RPC glue vector for in-kernel short circuited tasks. Rather than
3661 * removing it completely, I have only disabled that feature (which was
3662 * the only feature at the time). It just appears that we are going to
3663 * want to add some user data to tasks in the future (i.e. bsd info,
3664 * task names, etc...), so I left it in the formal task interface.
3669 task_flavor_t flavor
,
3670 __unused task_info_t task_info_in
, /* pointer to IN array */
3671 __unused mach_msg_type_number_t task_info_count
)
3673 if (task
== TASK_NULL
)
3674 return(KERN_INVALID_ARGUMENT
);
3679 case TASK_TRACE_MEMORY_INFO
:
3681 if (task_info_count
!= TASK_TRACE_MEMORY_INFO_COUNT
)
3682 return (KERN_INVALID_ARGUMENT
);
3684 assert(task_info_in
!= NULL
);
3685 task_trace_memory_info_t mem_info
;
3686 mem_info
= (task_trace_memory_info_t
) task_info_in
;
3687 kern_return_t kr
= atm_register_trace_memory(task
,
3688 mem_info
->user_memory_address
,
3689 mem_info
->buffer_size
);
3695 return (KERN_INVALID_ARGUMENT
);
3697 return (KERN_SUCCESS
);
3700 int radar_20146450
= 1;
3704 task_flavor_t flavor
,
3705 task_info_t task_info_out
,
3706 mach_msg_type_number_t
*task_info_count
)
3708 kern_return_t error
= KERN_SUCCESS
;
3709 mach_msg_type_number_t original_task_info_count
;
3711 if (task
== TASK_NULL
)
3712 return (KERN_INVALID_ARGUMENT
);
3714 original_task_info_count
= *task_info_count
;
3717 if ((task
!= current_task()) && (!task
->active
)) {
3719 return (KERN_INVALID_ARGUMENT
);
3724 case TASK_BASIC_INFO_32
:
3725 case TASK_BASIC2_INFO_32
:
3726 #if defined(__arm__) || defined(__arm64__)
3727 case TASK_BASIC_INFO_64
:
3730 task_basic_info_32_t basic_info
;
3735 if (*task_info_count
< TASK_BASIC_INFO_32_COUNT
) {
3736 error
= KERN_INVALID_ARGUMENT
;
3740 basic_info
= (task_basic_info_32_t
)task_info_out
;
3742 map
= (task
== kernel_task
)? kernel_map
: task
->map
;
3743 basic_info
->virtual_size
= (typeof(basic_info
->virtual_size
))map
->size
;
3744 if (flavor
== TASK_BASIC2_INFO_32
) {
3746 * The "BASIC2" flavor gets the maximum resident
3747 * size instead of the current resident size...
3749 basic_info
->resident_size
= pmap_resident_max(map
->pmap
);
3751 basic_info
->resident_size
= pmap_resident_count(map
->pmap
);
3753 basic_info
->resident_size
*= PAGE_SIZE
;
3755 basic_info
->policy
= ((task
!= kernel_task
)?
3756 POLICY_TIMESHARE
: POLICY_RR
);
3757 basic_info
->suspend_count
= task
->user_stop_count
;
3759 absolutetime_to_microtime(task
->total_user_time
, &secs
, &usecs
);
3760 basic_info
->user_time
.seconds
=
3761 (typeof(basic_info
->user_time
.seconds
))secs
;
3762 basic_info
->user_time
.microseconds
= usecs
;
3764 absolutetime_to_microtime(task
->total_system_time
, &secs
, &usecs
);
3765 basic_info
->system_time
.seconds
=
3766 (typeof(basic_info
->system_time
.seconds
))secs
;
3767 basic_info
->system_time
.microseconds
= usecs
;
3769 *task_info_count
= TASK_BASIC_INFO_32_COUNT
;
3773 #if defined(__arm__) || defined(__arm64__)
3774 case TASK_BASIC_INFO_64_2
:
3776 task_basic_info_64_2_t basic_info
;
3781 if (*task_info_count
< TASK_BASIC_INFO_64_2_COUNT
) {
3782 error
= KERN_INVALID_ARGUMENT
;
3786 basic_info
= (task_basic_info_64_2_t
)task_info_out
;
3788 map
= (task
== kernel_task
)? kernel_map
: task
->map
;
3789 basic_info
->virtual_size
= map
->size
;
3790 basic_info
->resident_size
=
3791 (mach_vm_size_t
)(pmap_resident_count(map
->pmap
))
3794 basic_info
->policy
= ((task
!= kernel_task
)?
3795 POLICY_TIMESHARE
: POLICY_RR
);
3796 basic_info
->suspend_count
= task
->user_stop_count
;
3798 absolutetime_to_microtime(task
->total_user_time
, &secs
, &usecs
);
3799 basic_info
->user_time
.seconds
=
3800 (typeof(basic_info
->user_time
.seconds
))secs
;
3801 basic_info
->user_time
.microseconds
= usecs
;
3803 absolutetime_to_microtime(task
->total_system_time
, &secs
, &usecs
);
3804 basic_info
->system_time
.seconds
=
3805 (typeof(basic_info
->system_time
.seconds
))secs
;
3806 basic_info
->system_time
.microseconds
= usecs
;
3808 *task_info_count
= TASK_BASIC_INFO_64_2_COUNT
;
3812 #else /* defined(__arm__) || defined(__arm64__) */
3813 case TASK_BASIC_INFO_64
:
3815 task_basic_info_64_t basic_info
;
3820 if (*task_info_count
< TASK_BASIC_INFO_64_COUNT
) {
3821 error
= KERN_INVALID_ARGUMENT
;
3825 basic_info
= (task_basic_info_64_t
)task_info_out
;
3827 map
= (task
== kernel_task
)? kernel_map
: task
->map
;
3828 basic_info
->virtual_size
= map
->size
;
3829 basic_info
->resident_size
=
3830 (mach_vm_size_t
)(pmap_resident_count(map
->pmap
))
3833 basic_info
->policy
= ((task
!= kernel_task
)?
3834 POLICY_TIMESHARE
: POLICY_RR
);
3835 basic_info
->suspend_count
= task
->user_stop_count
;
3837 absolutetime_to_microtime(task
->total_user_time
, &secs
, &usecs
);
3838 basic_info
->user_time
.seconds
=
3839 (typeof(basic_info
->user_time
.seconds
))secs
;
3840 basic_info
->user_time
.microseconds
= usecs
;
3842 absolutetime_to_microtime(task
->total_system_time
, &secs
, &usecs
);
3843 basic_info
->system_time
.seconds
=
3844 (typeof(basic_info
->system_time
.seconds
))secs
;
3845 basic_info
->system_time
.microseconds
= usecs
;
3847 *task_info_count
= TASK_BASIC_INFO_64_COUNT
;
3850 #endif /* defined(__arm__) || defined(__arm64__) */
3852 case MACH_TASK_BASIC_INFO
:
3854 mach_task_basic_info_t basic_info
;
3859 if (*task_info_count
< MACH_TASK_BASIC_INFO_COUNT
) {
3860 error
= KERN_INVALID_ARGUMENT
;
3864 basic_info
= (mach_task_basic_info_t
)task_info_out
;
3866 map
= (task
== kernel_task
) ? kernel_map
: task
->map
;
3868 basic_info
->virtual_size
= map
->size
;
3870 basic_info
->resident_size
=
3871 (mach_vm_size_t
)(pmap_resident_count(map
->pmap
));
3872 basic_info
->resident_size
*= PAGE_SIZE_64
;
3874 basic_info
->resident_size_max
=
3875 (mach_vm_size_t
)(pmap_resident_max(map
->pmap
));
3876 basic_info
->resident_size_max
*= PAGE_SIZE_64
;
3878 basic_info
->policy
= ((task
!= kernel_task
) ?
3879 POLICY_TIMESHARE
: POLICY_RR
);
3881 basic_info
->suspend_count
= task
->user_stop_count
;
3883 absolutetime_to_microtime(task
->total_user_time
, &secs
, &usecs
);
3884 basic_info
->user_time
.seconds
=
3885 (typeof(basic_info
->user_time
.seconds
))secs
;
3886 basic_info
->user_time
.microseconds
= usecs
;
3888 absolutetime_to_microtime(task
->total_system_time
, &secs
, &usecs
);
3889 basic_info
->system_time
.seconds
=
3890 (typeof(basic_info
->system_time
.seconds
))secs
;
3891 basic_info
->system_time
.microseconds
= usecs
;
3893 *task_info_count
= MACH_TASK_BASIC_INFO_COUNT
;
3897 case TASK_THREAD_TIMES_INFO
:
3899 task_thread_times_info_t times_info
;
3902 if (*task_info_count
< TASK_THREAD_TIMES_INFO_COUNT
) {
3903 error
= KERN_INVALID_ARGUMENT
;
3907 times_info
= (task_thread_times_info_t
) task_info_out
;
3908 times_info
->user_time
.seconds
= 0;
3909 times_info
->user_time
.microseconds
= 0;
3910 times_info
->system_time
.seconds
= 0;
3911 times_info
->system_time
.microseconds
= 0;
3914 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
3915 time_value_t user_time
, system_time
;
3917 if (thread
->options
& TH_OPT_IDLE_THREAD
)
3920 thread_read_times(thread
, &user_time
, &system_time
, NULL
);
3922 time_value_add(×_info
->user_time
, &user_time
);
3923 time_value_add(×_info
->system_time
, &system_time
);
3926 *task_info_count
= TASK_THREAD_TIMES_INFO_COUNT
;
3930 case TASK_ABSOLUTETIME_INFO
:
3932 task_absolutetime_info_t info
;
3935 if (*task_info_count
< TASK_ABSOLUTETIME_INFO_COUNT
) {
3936 error
= KERN_INVALID_ARGUMENT
;
3940 info
= (task_absolutetime_info_t
)task_info_out
;
3941 info
->threads_user
= info
->threads_system
= 0;
3944 info
->total_user
= task
->total_user_time
;
3945 info
->total_system
= task
->total_system_time
;
3947 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
3951 if (thread
->options
& TH_OPT_IDLE_THREAD
)
3955 thread_lock(thread
);
3957 tval
= timer_grab(&thread
->user_timer
);
3958 info
->threads_user
+= tval
;
3959 info
->total_user
+= tval
;
3961 tval
= timer_grab(&thread
->system_timer
);
3962 if (thread
->precise_user_kernel_time
) {
3963 info
->threads_system
+= tval
;
3964 info
->total_system
+= tval
;
3966 /* system_timer may represent either sys or user */
3967 info
->threads_user
+= tval
;
3968 info
->total_user
+= tval
;
3971 thread_unlock(thread
);
3976 *task_info_count
= TASK_ABSOLUTETIME_INFO_COUNT
;
3980 case TASK_DYLD_INFO
:
3982 task_dyld_info_t info
;
3985 * We added the format field to TASK_DYLD_INFO output. For
3986 * temporary backward compatibility, accept the fact that
3987 * clients may ask for the old version - distinquished by the
3988 * size of the expected result structure.
3990 #define TASK_LEGACY_DYLD_INFO_COUNT \
3991 offsetof(struct task_dyld_info, all_image_info_format)/sizeof(natural_t)
3993 if (*task_info_count
< TASK_LEGACY_DYLD_INFO_COUNT
) {
3994 error
= KERN_INVALID_ARGUMENT
;
3998 info
= (task_dyld_info_t
)task_info_out
;
3999 info
->all_image_info_addr
= task
->all_image_info_addr
;
4000 info
->all_image_info_size
= task
->all_image_info_size
;
4002 /* only set format on output for those expecting it */
4003 if (*task_info_count
>= TASK_DYLD_INFO_COUNT
) {
4004 info
->all_image_info_format
= task_has_64Bit_addr(task
) ?
4005 TASK_DYLD_ALL_IMAGE_INFO_64
:
4006 TASK_DYLD_ALL_IMAGE_INFO_32
;
4007 *task_info_count
= TASK_DYLD_INFO_COUNT
;
4009 *task_info_count
= TASK_LEGACY_DYLD_INFO_COUNT
;
4014 case TASK_EXTMOD_INFO
:
4016 task_extmod_info_t info
;
4019 if (*task_info_count
< TASK_EXTMOD_INFO_COUNT
) {
4020 error
= KERN_INVALID_ARGUMENT
;
4024 info
= (task_extmod_info_t
)task_info_out
;
4026 p
= get_bsdtask_info(task
);
4028 proc_getexecutableuuid(p
, info
->task_uuid
, sizeof(info
->task_uuid
));
4030 bzero(info
->task_uuid
, sizeof(info
->task_uuid
));
4032 info
->extmod_statistics
= task
->extmod_statistics
;
4033 *task_info_count
= TASK_EXTMOD_INFO_COUNT
;
4038 case TASK_KERNELMEMORY_INFO
:
4040 task_kernelmemory_info_t tkm_info
;
4041 ledger_amount_t credit
, debit
;
4043 if (*task_info_count
< TASK_KERNELMEMORY_INFO_COUNT
) {
4044 error
= KERN_INVALID_ARGUMENT
;
4048 tkm_info
= (task_kernelmemory_info_t
) task_info_out
;
4049 tkm_info
->total_palloc
= 0;
4050 tkm_info
->total_pfree
= 0;
4051 tkm_info
->total_salloc
= 0;
4052 tkm_info
->total_sfree
= 0;
4054 if (task
== kernel_task
) {
4056 * All shared allocs/frees from other tasks count against
4057 * the kernel private memory usage. If we are looking up
4058 * info for the kernel task, gather from everywhere.
4062 /* start by accounting for all the terminated tasks against the kernel */
4063 tkm_info
->total_palloc
= tasks_tkm_private
.alloc
+ tasks_tkm_shared
.alloc
;
4064 tkm_info
->total_pfree
= tasks_tkm_private
.free
+ tasks_tkm_shared
.free
;
4066 /* count all other task/thread shared alloc/free against the kernel */
4067 lck_mtx_lock(&tasks_threads_lock
);
4069 /* XXX this really shouldn't be using the function parameter 'task' as a local var! */
4070 queue_iterate(&tasks
, task
, task_t
, tasks
) {
4071 if (task
== kernel_task
) {
4072 if (ledger_get_entries(task
->ledger
,
4073 task_ledgers
.tkm_private
, &credit
,
4074 &debit
) == KERN_SUCCESS
) {
4075 tkm_info
->total_palloc
+= credit
;
4076 tkm_info
->total_pfree
+= debit
;
4079 if (!ledger_get_entries(task
->ledger
,
4080 task_ledgers
.tkm_shared
, &credit
, &debit
)) {
4081 tkm_info
->total_palloc
+= credit
;
4082 tkm_info
->total_pfree
+= debit
;
4085 lck_mtx_unlock(&tasks_threads_lock
);
4087 if (!ledger_get_entries(task
->ledger
,
4088 task_ledgers
.tkm_private
, &credit
, &debit
)) {
4089 tkm_info
->total_palloc
= credit
;
4090 tkm_info
->total_pfree
= debit
;
4092 if (!ledger_get_entries(task
->ledger
,
4093 task_ledgers
.tkm_shared
, &credit
, &debit
)) {
4094 tkm_info
->total_salloc
= credit
;
4095 tkm_info
->total_sfree
= debit
;
4100 *task_info_count
= TASK_KERNELMEMORY_INFO_COUNT
;
4101 return KERN_SUCCESS
;
4105 case TASK_SCHED_FIFO_INFO
:
4108 if (*task_info_count
< POLICY_FIFO_BASE_COUNT
) {
4109 error
= KERN_INVALID_ARGUMENT
;
4113 error
= KERN_INVALID_POLICY
;
4118 case TASK_SCHED_RR_INFO
:
4120 policy_rr_base_t rr_base
;
4121 uint32_t quantum_time
;
4122 uint64_t quantum_ns
;
4124 if (*task_info_count
< POLICY_RR_BASE_COUNT
) {
4125 error
= KERN_INVALID_ARGUMENT
;
4129 rr_base
= (policy_rr_base_t
) task_info_out
;
4131 if (task
!= kernel_task
) {
4132 error
= KERN_INVALID_POLICY
;
4136 rr_base
->base_priority
= task
->priority
;
4138 quantum_time
= SCHED(initial_quantum_size
)(THREAD_NULL
);
4139 absolutetime_to_nanoseconds(quantum_time
, &quantum_ns
);
4141 rr_base
->quantum
= (uint32_t)(quantum_ns
/ 1000 / 1000);
4143 *task_info_count
= POLICY_RR_BASE_COUNT
;
4148 case TASK_SCHED_TIMESHARE_INFO
:
4150 policy_timeshare_base_t ts_base
;
4152 if (*task_info_count
< POLICY_TIMESHARE_BASE_COUNT
) {
4153 error
= KERN_INVALID_ARGUMENT
;
4157 ts_base
= (policy_timeshare_base_t
) task_info_out
;
4159 if (task
== kernel_task
) {
4160 error
= KERN_INVALID_POLICY
;
4164 ts_base
->base_priority
= task
->priority
;
4166 *task_info_count
= POLICY_TIMESHARE_BASE_COUNT
;
4170 case TASK_SECURITY_TOKEN
:
4172 security_token_t
*sec_token_p
;
4174 if (*task_info_count
< TASK_SECURITY_TOKEN_COUNT
) {
4175 error
= KERN_INVALID_ARGUMENT
;
4179 sec_token_p
= (security_token_t
*) task_info_out
;
4181 *sec_token_p
= task
->sec_token
;
4183 *task_info_count
= TASK_SECURITY_TOKEN_COUNT
;
4187 case TASK_AUDIT_TOKEN
:
4189 audit_token_t
*audit_token_p
;
4191 if (*task_info_count
< TASK_AUDIT_TOKEN_COUNT
) {
4192 error
= KERN_INVALID_ARGUMENT
;
4196 audit_token_p
= (audit_token_t
*) task_info_out
;
4198 *audit_token_p
= task
->audit_token
;
4200 *task_info_count
= TASK_AUDIT_TOKEN_COUNT
;
4204 case TASK_SCHED_INFO
:
4205 error
= KERN_INVALID_ARGUMENT
;
4208 case TASK_EVENTS_INFO
:
4210 task_events_info_t events_info
;
4213 if (*task_info_count
< TASK_EVENTS_INFO_COUNT
) {
4214 error
= KERN_INVALID_ARGUMENT
;
4218 events_info
= (task_events_info_t
) task_info_out
;
4221 events_info
->faults
= task
->faults
;
4222 events_info
->pageins
= task
->pageins
;
4223 events_info
->cow_faults
= task
->cow_faults
;
4224 events_info
->messages_sent
= task
->messages_sent
;
4225 events_info
->messages_received
= task
->messages_received
;
4226 events_info
->syscalls_mach
= task
->syscalls_mach
;
4227 events_info
->syscalls_unix
= task
->syscalls_unix
;
4229 events_info
->csw
= task
->c_switch
;
4231 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
4232 events_info
->csw
+= thread
->c_switch
;
4233 events_info
->syscalls_mach
+= thread
->syscalls_mach
;
4234 events_info
->syscalls_unix
+= thread
->syscalls_unix
;
4238 *task_info_count
= TASK_EVENTS_INFO_COUNT
;
4241 case TASK_AFFINITY_TAG_INFO
:
4243 if (*task_info_count
< TASK_AFFINITY_TAG_INFO_COUNT
) {
4244 error
= KERN_INVALID_ARGUMENT
;
4248 error
= task_affinity_info(task
, task_info_out
, task_info_count
);
4251 case TASK_POWER_INFO
:
4253 if (*task_info_count
< TASK_POWER_INFO_COUNT
) {
4254 error
= KERN_INVALID_ARGUMENT
;
4258 task_power_info_locked(task
, (task_power_info_t
)task_info_out
, NULL
, NULL
);
4262 case TASK_POWER_INFO_V2
:
4264 if (*task_info_count
< TASK_POWER_INFO_V2_COUNT_OLD
) {
4265 error
= KERN_INVALID_ARGUMENT
;
4268 task_power_info_v2_t tpiv2
= (task_power_info_v2_t
) task_info_out
;
4269 task_power_info_locked(task
, &tpiv2
->cpu_energy
, &tpiv2
->gpu_energy
, tpiv2
);
4274 case TASK_VM_INFO_PURGEABLE
:
4276 task_vm_info_t vm_info
;
4279 if (*task_info_count
< TASK_VM_INFO_REV0_COUNT
) {
4280 error
= KERN_INVALID_ARGUMENT
;
4284 vm_info
= (task_vm_info_t
)task_info_out
;
4286 if (task
== kernel_task
) {
4291 vm_map_lock_read(map
);
4294 vm_info
->virtual_size
= (typeof(vm_info
->virtual_size
))map
->size
;
4295 vm_info
->region_count
= map
->hdr
.nentries
;
4296 vm_info
->page_size
= vm_map_page_size(map
);
4298 vm_info
->resident_size
= pmap_resident_count(map
->pmap
);
4299 vm_info
->resident_size
*= PAGE_SIZE
;
4300 vm_info
->resident_size_peak
= pmap_resident_max(map
->pmap
);
4301 vm_info
->resident_size_peak
*= PAGE_SIZE
;
4303 #define _VM_INFO(_name) \
4304 vm_info->_name = ((mach_vm_size_t) map->pmap->stats._name) * PAGE_SIZE
4307 _VM_INFO(device_peak
);
4309 _VM_INFO(external_peak
);
4311 _VM_INFO(internal_peak
);
4313 _VM_INFO(reusable_peak
);
4314 _VM_INFO(compressed
);
4315 _VM_INFO(compressed_peak
);
4316 _VM_INFO(compressed_lifetime
);
4318 vm_info
->purgeable_volatile_pmap
= 0;
4319 vm_info
->purgeable_volatile_resident
= 0;
4320 vm_info
->purgeable_volatile_virtual
= 0;
4321 if (task
== kernel_task
) {
4323 * We do not maintain the detailed stats for the
4324 * kernel_pmap, so just count everything as
4327 vm_info
->internal
= vm_info
->resident_size
;
4329 * ... but since the memory held by the VM compressor
4330 * in the kernel address space ought to be attributed
4331 * to user-space tasks, we subtract it from "internal"
4332 * to give memory reporting tools a more accurate idea
4333 * of what the kernel itself is actually using, instead
4334 * of making it look like the kernel is leaking memory
4335 * when the system is under memory pressure.
4337 vm_info
->internal
-= (VM_PAGE_COMPRESSOR_COUNT
*
4340 mach_vm_size_t volatile_virtual_size
;
4341 mach_vm_size_t volatile_resident_size
;
4342 mach_vm_size_t volatile_compressed_size
;
4343 mach_vm_size_t volatile_pmap_size
;
4344 mach_vm_size_t volatile_compressed_pmap_size
;
4347 if (flavor
== TASK_VM_INFO_PURGEABLE
) {
4348 kr
= vm_map_query_volatile(
4350 &volatile_virtual_size
,
4351 &volatile_resident_size
,
4352 &volatile_compressed_size
,
4353 &volatile_pmap_size
,
4354 &volatile_compressed_pmap_size
);
4355 if (kr
== KERN_SUCCESS
) {
4356 vm_info
->purgeable_volatile_pmap
=
4358 if (radar_20146450
) {
4359 vm_info
->compressed
-=
4360 volatile_compressed_pmap_size
;
4362 vm_info
->purgeable_volatile_resident
=
4363 volatile_resident_size
;
4364 vm_info
->purgeable_volatile_virtual
=
4365 volatile_virtual_size
;
4369 *task_info_count
= TASK_VM_INFO_REV0_COUNT
;
4371 if (original_task_info_count
>= TASK_VM_INFO_REV1_COUNT
) {
4372 vm_info
->phys_footprint
=
4373 (mach_vm_size_t
) get_task_phys_footprint(task
);
4374 *task_info_count
= TASK_VM_INFO_REV1_COUNT
;
4376 if (original_task_info_count
>= TASK_VM_INFO_REV2_COUNT
) {
4377 vm_info
->min_address
= map
->min_offset
;
4378 vm_info
->max_address
= map
->max_offset
;
4379 *task_info_count
= TASK_VM_INFO_REV2_COUNT
;
4382 if (task
!= kernel_task
) {
4383 vm_map_unlock_read(map
);
4389 case TASK_WAIT_STATE_INFO
:
4392 * Deprecated flavor. Currently allowing some results until all users
4393 * stop calling it. The results may not be accurate.
4395 task_wait_state_info_t wait_state_info
;
4396 uint64_t total_sfi_ledger_val
= 0;
4398 if (*task_info_count
< TASK_WAIT_STATE_INFO_COUNT
) {
4399 error
= KERN_INVALID_ARGUMENT
;
4403 wait_state_info
= (task_wait_state_info_t
) task_info_out
;
4405 wait_state_info
->total_wait_state_time
= 0;
4406 bzero(wait_state_info
->_reserved
, sizeof(wait_state_info
->_reserved
));
4408 #if CONFIG_SCHED_SFI
4409 int i
, prev_lentry
= -1;
4410 int64_t val_credit
, val_debit
;
4412 for (i
= 0; i
< MAX_SFI_CLASS_ID
; i
++){
4415 * checking with prev_lentry != entry ensures adjacent classes
4416 * which share the same ledger do not add wait times twice.
4417 * Note: Use ledger() call to get data for each individual sfi class.
4419 if (prev_lentry
!= task_ledgers
.sfi_wait_times
[i
] &&
4420 KERN_SUCCESS
== ledger_get_entries(task
->ledger
,
4421 task_ledgers
.sfi_wait_times
[i
], &val_credit
, &val_debit
)) {
4422 total_sfi_ledger_val
+= val_credit
;
4424 prev_lentry
= task_ledgers
.sfi_wait_times
[i
];
4427 #endif /* CONFIG_SCHED_SFI */
4428 wait_state_info
->total_wait_sfi_state_time
= total_sfi_ledger_val
;
4429 *task_info_count
= TASK_WAIT_STATE_INFO_COUNT
;
4433 case TASK_VM_INFO_PURGEABLE_ACCOUNT
:
4435 #if DEVELOPMENT || DEBUG
4436 pvm_account_info_t acnt_info
;
4438 if (*task_info_count
< PVM_ACCOUNT_INFO_COUNT
) {
4439 error
= KERN_INVALID_ARGUMENT
;
4443 if (task_info_out
== NULL
) {
4444 error
= KERN_INVALID_ARGUMENT
;
4448 acnt_info
= (pvm_account_info_t
) task_info_out
;
4450 error
= vm_purgeable_account(task
, acnt_info
);
4452 *task_info_count
= PVM_ACCOUNT_INFO_COUNT
;
4455 #else /* DEVELOPMENT || DEBUG */
4456 error
= KERN_NOT_SUPPORTED
;
4458 #endif /* DEVELOPMENT || DEBUG */
4460 case TASK_FLAGS_INFO
:
4462 task_flags_info_t flags_info
;
4464 if (*task_info_count
< TASK_FLAGS_INFO_COUNT
) {
4465 error
= KERN_INVALID_ARGUMENT
;
4469 flags_info
= (task_flags_info_t
)task_info_out
;
4471 /* only publish the 64-bit flag of the task */
4472 flags_info
->flags
= task
->t_flags
& (TF_64B_ADDR
| TF_64B_DATA
);
4474 *task_info_count
= TASK_FLAGS_INFO_COUNT
;
4478 case TASK_DEBUG_INFO_INTERNAL
:
4480 #if DEVELOPMENT || DEBUG
4481 task_debug_info_internal_t dbg_info
;
4482 if (*task_info_count
< TASK_DEBUG_INFO_INTERNAL_COUNT
) {
4483 error
= KERN_NOT_SUPPORTED
;
4487 if (task_info_out
== NULL
) {
4488 error
= KERN_INVALID_ARGUMENT
;
4491 dbg_info
= (task_debug_info_internal_t
) task_info_out
;
4492 dbg_info
->ipc_space_size
= 0;
4493 if (task
->itk_space
){
4494 dbg_info
->ipc_space_size
= task
->itk_space
->is_table_size
;
4497 dbg_info
->suspend_count
= task
->suspend_count
;
4499 error
= KERN_SUCCESS
;
4500 *task_info_count
= TASK_DEBUG_INFO_INTERNAL_COUNT
;
4502 #else /* DEVELOPMENT || DEBUG */
4503 error
= KERN_NOT_SUPPORTED
;
4505 #endif /* DEVELOPMENT || DEBUG */
4508 error
= KERN_INVALID_ARGUMENT
;
4516 * task_info_from_user
4518 * When calling task_info from user space,
4519 * this function will be executed as mig server side
4520 * instead of calling directly into task_info.
4521 * This gives the possibility to perform more security
4522 * checks on task_port.
4524 * In the case of TASK_DYLD_INFO, we require the more
4525 * privileged task_port not the less-privileged task_name_port.
4529 task_info_from_user(
4530 mach_port_t task_port
,
4531 task_flavor_t flavor
,
4532 task_info_t task_info_out
,
4533 mach_msg_type_number_t
*task_info_count
)
4538 if (flavor
== TASK_DYLD_INFO
)
4539 task
= convert_port_to_task(task_port
);
4541 task
= convert_port_to_task_name(task_port
);
4543 ret
= task_info(task
, flavor
, task_info_out
, task_info_count
);
4545 task_deallocate(task
);
4553 * Returns power stats for the task.
4554 * Note: Called with task locked.
4557 task_power_info_locked(
4559 task_power_info_t info
,
4560 gpu_energy_data_t ginfo
,
4561 task_power_info_v2_t infov2
)
4564 ledger_amount_t tmp
;
4566 task_lock_assert_owned(task
);
4568 ledger_get_entries(task
->ledger
, task_ledgers
.interrupt_wakeups
,
4569 (ledger_amount_t
*)&info
->task_interrupt_wakeups
, &tmp
);
4570 ledger_get_entries(task
->ledger
, task_ledgers
.platform_idle_wakeups
,
4571 (ledger_amount_t
*)&info
->task_platform_idle_wakeups
, &tmp
);
4573 info
->task_timer_wakeups_bin_1
= task
->task_timer_wakeups_bin_1
;
4574 info
->task_timer_wakeups_bin_2
= task
->task_timer_wakeups_bin_2
;
4576 info
->total_user
= task
->total_user_time
;
4577 info
->total_system
= task
->total_system_time
;
4581 infov2
->task_energy
= task
->task_energy
;
4586 ginfo
->task_gpu_utilisation
= task
->task_gpu_ns
;
4590 infov2
->task_ptime
= task
->total_ptime
;
4591 infov2
->task_pset_switches
= task
->ps_switch
;
4594 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
4598 if (thread
->options
& TH_OPT_IDLE_THREAD
)
4602 thread_lock(thread
);
4604 info
->task_timer_wakeups_bin_1
+= thread
->thread_timer_wakeups_bin_1
;
4605 info
->task_timer_wakeups_bin_2
+= thread
->thread_timer_wakeups_bin_2
;
4609 infov2
->task_energy
+= ml_energy_stat(thread
);
4613 tval
= timer_grab(&thread
->user_timer
);
4614 info
->total_user
+= tval
;
4617 tval
= timer_grab(&thread
->ptime
);
4618 infov2
->task_ptime
+= tval
;
4619 infov2
->task_pset_switches
+= thread
->ps_switch
;
4622 tval
= timer_grab(&thread
->system_timer
);
4623 if (thread
->precise_user_kernel_time
) {
4624 info
->total_system
+= tval
;
4626 /* system_timer may represent either sys or user */
4627 info
->total_user
+= tval
;
4631 ginfo
->task_gpu_utilisation
+= ml_gpu_stat(thread
);
4633 thread_unlock(thread
);
4639 * task_gpu_utilisation
4641 * Returns the total gpu time used by the all the threads of the task
4642 * (both dead and alive)
4645 task_gpu_utilisation(
4648 uint64_t gpu_time
= 0;
4649 #if !CONFIG_EMBEDDED
4653 gpu_time
+= task
->task_gpu_ns
;
4655 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
4658 thread_lock(thread
);
4659 gpu_time
+= ml_gpu_stat(thread
);
4660 thread_unlock(thread
);
4665 #else /* CONFIG_EMBEDDED */
4666 /* silence compiler warning */
4668 #endif /* !CONFIG_EMBEDDED */
4675 * Returns the total energy used by the all the threads of the task
4676 * (both dead and alive)
4682 uint64_t energy
= 0;
4686 energy
+= task
->task_energy
;
4688 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
4691 thread_lock(thread
);
4692 energy
+= ml_energy_stat(thread
);
4693 thread_unlock(thread
);
4704 __unused task_t task
)
4710 /* This function updates the cpu time in the arrays for each
4711 * effective and requested QoS class
4714 task_update_cpu_time_qos_stats(
4716 uint64_t *eqos_stats
,
4717 uint64_t *rqos_stats
)
4719 if (!eqos_stats
&& !rqos_stats
) {
4725 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
4726 if (thread
->options
& TH_OPT_IDLE_THREAD
) {
4730 thread_update_qos_cpu_time(thread
);
4734 eqos_stats
[THREAD_QOS_DEFAULT
] += task
->cpu_time_eqos_stats
.cpu_time_qos_default
;
4735 eqos_stats
[THREAD_QOS_MAINTENANCE
] += task
->cpu_time_eqos_stats
.cpu_time_qos_maintenance
;
4736 eqos_stats
[THREAD_QOS_BACKGROUND
] += task
->cpu_time_eqos_stats
.cpu_time_qos_background
;
4737 eqos_stats
[THREAD_QOS_UTILITY
] += task
->cpu_time_eqos_stats
.cpu_time_qos_utility
;
4738 eqos_stats
[THREAD_QOS_LEGACY
] += task
->cpu_time_eqos_stats
.cpu_time_qos_legacy
;
4739 eqos_stats
[THREAD_QOS_USER_INITIATED
] += task
->cpu_time_eqos_stats
.cpu_time_qos_user_initiated
;
4740 eqos_stats
[THREAD_QOS_USER_INTERACTIVE
] += task
->cpu_time_eqos_stats
.cpu_time_qos_user_interactive
;
4744 rqos_stats
[THREAD_QOS_DEFAULT
] += task
->cpu_time_rqos_stats
.cpu_time_qos_default
;
4745 rqos_stats
[THREAD_QOS_MAINTENANCE
] += task
->cpu_time_rqos_stats
.cpu_time_qos_maintenance
;
4746 rqos_stats
[THREAD_QOS_BACKGROUND
] += task
->cpu_time_rqos_stats
.cpu_time_qos_background
;
4747 rqos_stats
[THREAD_QOS_UTILITY
] += task
->cpu_time_rqos_stats
.cpu_time_qos_utility
;
4748 rqos_stats
[THREAD_QOS_LEGACY
] += task
->cpu_time_rqos_stats
.cpu_time_qos_legacy
;
4749 rqos_stats
[THREAD_QOS_USER_INITIATED
] += task
->cpu_time_rqos_stats
.cpu_time_qos_user_initiated
;
4750 rqos_stats
[THREAD_QOS_USER_INTERACTIVE
] += task
->cpu_time_rqos_stats
.cpu_time_qos_user_interactive
;
4759 task_purgable_info_t
*stats
)
4761 if (task
== TASK_NULL
|| stats
== NULL
)
4762 return KERN_INVALID_ARGUMENT
;
4763 /* Take task reference */
4764 task_reference(task
);
4765 vm_purgeable_stats((vm_purgeable_info_t
)stats
, task
);
4766 /* Drop task reference */
4767 task_deallocate(task
);
4768 return KERN_SUCCESS
;
4781 task
->vtimers
|= which
;
4785 case TASK_VTIMER_USER
:
4786 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
4788 thread_lock(thread
);
4789 if (thread
->precise_user_kernel_time
)
4790 thread
->vtimer_user_save
= timer_grab(&thread
->user_timer
);
4792 thread
->vtimer_user_save
= timer_grab(&thread
->system_timer
);
4793 thread_unlock(thread
);
4798 case TASK_VTIMER_PROF
:
4799 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
4801 thread_lock(thread
);
4802 thread
->vtimer_prof_save
= timer_grab(&thread
->user_timer
);
4803 thread
->vtimer_prof_save
+= timer_grab(&thread
->system_timer
);
4804 thread_unlock(thread
);
4809 case TASK_VTIMER_RLIM
:
4810 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
4812 thread_lock(thread
);
4813 thread
->vtimer_rlim_save
= timer_grab(&thread
->user_timer
);
4814 thread
->vtimer_rlim_save
+= timer_grab(&thread
->system_timer
);
4815 thread_unlock(thread
);
4829 assert(task
== current_task());
4833 task
->vtimers
&= ~which
;
4843 uint32_t *microsecs
)
4845 thread_t thread
= current_thread();
4847 clock_sec_t secs
= 0;
4850 assert(task
== current_task());
4852 spl_t s
= splsched();
4853 thread_lock(thread
);
4855 if ((task
->vtimers
& which
) != (uint32_t)which
) {
4856 thread_unlock(thread
);
4863 case TASK_VTIMER_USER
:
4864 if (thread
->precise_user_kernel_time
) {
4865 tdelt
= (uint32_t)timer_delta(&thread
->user_timer
,
4866 &thread
->vtimer_user_save
);
4868 tdelt
= (uint32_t)timer_delta(&thread
->system_timer
,
4869 &thread
->vtimer_user_save
);
4871 absolutetime_to_microtime(tdelt
, &secs
, microsecs
);
4874 case TASK_VTIMER_PROF
:
4875 tsum
= timer_grab(&thread
->user_timer
);
4876 tsum
+= timer_grab(&thread
->system_timer
);
4877 tdelt
= (uint32_t)(tsum
- thread
->vtimer_prof_save
);
4878 absolutetime_to_microtime(tdelt
, &secs
, microsecs
);
4879 /* if the time delta is smaller than a usec, ignore */
4880 if (*microsecs
!= 0)
4881 thread
->vtimer_prof_save
= tsum
;
4884 case TASK_VTIMER_RLIM
:
4885 tsum
= timer_grab(&thread
->user_timer
);
4886 tsum
+= timer_grab(&thread
->system_timer
);
4887 tdelt
= (uint32_t)(tsum
- thread
->vtimer_rlim_save
);
4888 thread
->vtimer_rlim_save
= tsum
;
4889 absolutetime_to_microtime(tdelt
, &secs
, microsecs
);
4893 thread_unlock(thread
);
4900 * Change the assigned processor set for the task
4904 __unused task_t task
,
4905 __unused processor_set_t new_pset
,
4906 __unused boolean_t assign_threads
)
4908 return(KERN_FAILURE
);
4912 * task_assign_default:
4914 * Version of task_assign to assign to default processor set.
4917 task_assign_default(
4919 boolean_t assign_threads
)
4921 return (task_assign(task
, &pset0
, assign_threads
));
4925 * task_get_assignment
4927 * Return name of processor set that task is assigned to.
4930 task_get_assignment(
4932 processor_set_t
*pset
)
4934 if (!task
|| !task
->active
)
4935 return KERN_FAILURE
;
4939 return KERN_SUCCESS
;
4943 get_task_dispatchqueue_offset(
4946 return task
->dispatchqueue_offset
;
4952 * Set scheduling policy and parameters, both base and limit, for
4953 * the given task. Policy must be a policy which is enabled for the
4954 * processor set. Change contained threads if requested.
4958 __unused task_t task
,
4959 __unused policy_t policy_id
,
4960 __unused policy_base_t base
,
4961 __unused mach_msg_type_number_t count
,
4962 __unused boolean_t set_limit
,
4963 __unused boolean_t change
)
4965 return(KERN_FAILURE
);
4971 * Set scheduling policy and parameters, both base and limit, for
4972 * the given task. Policy can be any policy implemented by the
4973 * processor set, whether enabled or not. Change contained threads
4978 __unused task_t task
,
4979 __unused processor_set_t pset
,
4980 __unused policy_t policy_id
,
4981 __unused policy_base_t base
,
4982 __unused mach_msg_type_number_t base_count
,
4983 __unused policy_limit_t limit
,
4984 __unused mach_msg_type_number_t limit_count
,
4985 __unused boolean_t change
)
4987 return(KERN_FAILURE
);
4992 __unused task_t task
,
4993 __unused vm_offset_t pc
,
4994 __unused vm_offset_t endpc
)
4996 return KERN_FAILURE
;
5000 task_synchronizer_destroy_all(task_t task
)
5003 * Destroy owned semaphores
5005 semaphore_destroy_all(task
);
5009 * Install default (machine-dependent) initial thread state
5010 * on the task. Subsequent thread creation will have this initial
5011 * state set on the thread by machine_thread_inherit_taskwide().
5012 * Flavors and structures are exactly the same as those to thread_set_state()
5018 thread_state_t state
,
5019 mach_msg_type_number_t state_count
)
5023 if (task
== TASK_NULL
) {
5024 return (KERN_INVALID_ARGUMENT
);
5029 if (!task
->active
) {
5031 return (KERN_FAILURE
);
5034 ret
= machine_task_set_state(task
, flavor
, state
, state_count
);
5041 * Examine the default (machine-dependent) initial thread state
5042 * on the task, as set by task_set_state(). Flavors and structures
5043 * are exactly the same as those passed to thread_get_state().
5049 thread_state_t state
,
5050 mach_msg_type_number_t
*state_count
)
5054 if (task
== TASK_NULL
) {
5055 return (KERN_INVALID_ARGUMENT
);
5060 if (!task
->active
) {
5062 return (KERN_FAILURE
);
5065 ret
= machine_task_get_state(task
, flavor
, state
, state_count
);
5072 static kern_return_t
__attribute__((noinline
,not_tail_called
))
5073 PROC_VIOLATED_GUARD__SEND_EXC_GUARD_AND_SUSPEND(
5074 mach_exception_code_t code
,
5075 mach_exception_subcode_t subcode
,
5079 if (1 == proc_selfpid())
5080 return KERN_NOT_SUPPORTED
; // initproc is immune
5082 mach_exception_data_type_t codes
[EXCEPTION_CODE_MAX
] = {
5086 task_t task
= current_task();
5089 /* (See jetsam-related comments below) */
5091 proc_memstat_terminated(task
->bsd_info
, TRUE
);
5092 kr
= task_enqueue_exception_with_corpse(task
, EXC_GUARD
, codes
, 2, reason
);
5093 proc_memstat_terminated(task
->bsd_info
, FALSE
);
5098 task_violated_guard(
5099 mach_exception_code_t code
,
5100 mach_exception_subcode_t subcode
,
5103 return PROC_VIOLATED_GUARD__SEND_EXC_GUARD_AND_SUSPEND(code
, subcode
, reason
);
5107 #if CONFIG_MEMORYSTATUS
5110 task_get_memlimit_is_active(task_t task
)
5112 assert (task
!= NULL
);
5114 if (task
->memlimit_is_active
== 1) {
5122 task_set_memlimit_is_active(task_t task
, boolean_t memlimit_is_active
)
5124 assert (task
!= NULL
);
5126 if (memlimit_is_active
) {
5127 task
->memlimit_is_active
= 1;
5129 task
->memlimit_is_active
= 0;
5134 task_get_memlimit_is_fatal(task_t task
)
5136 assert(task
!= NULL
);
5138 if (task
->memlimit_is_fatal
== 1) {
5146 task_set_memlimit_is_fatal(task_t task
, boolean_t memlimit_is_fatal
)
5148 assert (task
!= NULL
);
5150 if (memlimit_is_fatal
) {
5151 task
->memlimit_is_fatal
= 1;
5153 task
->memlimit_is_fatal
= 0;
5158 task_has_triggered_exc_resource(task_t task
, boolean_t memlimit_is_active
)
5160 boolean_t triggered
= FALSE
;
5162 assert(task
== current_task());
5165 * Returns true, if task has already triggered an exc_resource exception.
5168 if (memlimit_is_active
) {
5169 triggered
= (task
->memlimit_active_exc_resource
? TRUE
: FALSE
);
5171 triggered
= (task
->memlimit_inactive_exc_resource
? TRUE
: FALSE
);
5178 task_mark_has_triggered_exc_resource(task_t task
, boolean_t memlimit_is_active
)
5180 assert(task
== current_task());
5183 * We allow one exc_resource per process per active/inactive limit.
5184 * The limit's fatal attribute does not come into play.
5187 if (memlimit_is_active
) {
5188 task
->memlimit_active_exc_resource
= 1;
5190 task
->memlimit_inactive_exc_resource
= 1;
5194 #define HWM_USERCORE_MINSPACE 250 // free space (in MB) required *after* core file creation
5196 void __attribute__((noinline
))
5197 PROC_CROSSED_HIGH_WATERMARK__SEND_EXC_RESOURCE_AND_SUSPEND(int max_footprint_mb
, boolean_t is_fatal
)
5199 task_t task
= current_task();
5201 const char *procname
= "unknown";
5202 mach_exception_data_type_t code
[EXCEPTION_CODE_MAX
];
5203 boolean_t send_sync_exc_resource
= FALSE
;
5206 pid
= proc_selfpid();
5210 * Cannot have ReportCrash analyzing
5211 * a suspended initproc.
5216 if (task
->bsd_info
!= NULL
) {
5217 procname
= proc_name_address(current_task()->bsd_info
);
5218 send_sync_exc_resource
= proc_send_synchronous_EXC_RESOURCE(current_task()->bsd_info
);
5222 if (hwm_user_cores
) {
5224 uint64_t starttime
, end
;
5225 clock_sec_t secs
= 0;
5226 uint32_t microsecs
= 0;
5228 starttime
= mach_absolute_time();
5230 * Trigger a coredump of this process. Don't proceed unless we know we won't
5231 * be filling up the disk; and ignore the core size resource limit for this
5234 if ((error
= coredump(current_task()->bsd_info
, HWM_USERCORE_MINSPACE
, COREDUMP_IGNORE_ULIMIT
)) != 0) {
5235 printf("couldn't take coredump of %s[%d]: %d\n", procname
, pid
, error
);
5238 * coredump() leaves the task suspended.
5240 task_resume_internal(current_task());
5242 end
= mach_absolute_time();
5243 absolutetime_to_microtime(end
- starttime
, &secs
, µsecs
);
5244 printf("coredump of %s[%d] taken in %d secs %d microsecs\n",
5245 proc_name_address(current_task()->bsd_info
), pid
, (int)secs
, microsecs
);
5247 #endif /* CONFIG_COREDUMP */
5249 if (disable_exc_resource
) {
5250 printf("process %s[%d] crossed memory high watermark (%d MB); EXC_RESOURCE "
5251 "supressed by a boot-arg.\n", procname
, pid
, max_footprint_mb
);
5256 * A task that has triggered an EXC_RESOURCE, should not be
5257 * jetsammed when the device is under memory pressure. Here
5258 * we set the P_MEMSTAT_TERMINATED flag so that the process
5259 * will be skipped if the memorystatus_thread wakes up.
5261 proc_memstat_terminated(current_task()->bsd_info
, TRUE
);
5263 code
[0] = code
[1] = 0;
5264 EXC_RESOURCE_ENCODE_TYPE(code
[0], RESOURCE_TYPE_MEMORY
);
5265 EXC_RESOURCE_ENCODE_FLAVOR(code
[0], FLAVOR_HIGH_WATERMARK
);
5266 EXC_RESOURCE_HWM_ENCODE_LIMIT(code
[0], max_footprint_mb
);
5269 * Do not generate a corpse fork if the violation is a fatal one
5270 * or the process wants synchronous EXC_RESOURCE exceptions.
5272 if (is_fatal
|| send_sync_exc_resource
|| exc_via_corpse_forking
== 0) {
5273 /* Do not send a EXC_RESOURCE if corpse_for_fatal_memkill is set */
5274 if (send_sync_exc_resource
|| corpse_for_fatal_memkill
== 0) {
5276 * Use the _internal_ variant so that no user-space
5277 * process can resume our task from under us.
5279 task_suspend_internal(task
);
5280 exception_triage(EXC_RESOURCE
, code
, EXCEPTION_CODE_MAX
);
5281 task_resume_internal(task
);
5285 printf("process %s[%d] crossed memory high watermark (%d MB); EXC_RESOURCE "
5286 "supressed due to audio playback.\n", procname
, pid
, max_footprint_mb
);
5288 task_enqueue_exception_with_corpse(task
, EXC_RESOURCE
,
5289 code
, EXCEPTION_CODE_MAX
, NULL
);
5294 * After the EXC_RESOURCE has been handled, we must clear the
5295 * P_MEMSTAT_TERMINATED flag so that the process can again be
5296 * considered for jetsam if the memorystatus_thread wakes up.
5298 proc_memstat_terminated(current_task()->bsd_info
, FALSE
); /* clear the flag */
5302 * Callback invoked when a task exceeds its physical footprint limit.
5305 task_footprint_exceeded(int warning
, __unused
const void *param0
, __unused
const void *param1
)
5307 ledger_amount_t max_footprint
, max_footprint_mb
;
5309 boolean_t is_warning
;
5310 boolean_t memlimit_is_active
;
5311 boolean_t memlimit_is_fatal
;
5313 if (warning
== LEDGER_WARNING_DIPPED_BELOW
) {
5315 * Task memory limits only provide a warning on the way up.
5318 } else if (warning
== LEDGER_WARNING_ROSE_ABOVE
) {
5320 * This task is in danger of violating a memory limit,
5321 * It has exceeded a percentage level of the limit.
5326 * The task has exceeded the physical footprint limit.
5327 * This is not a warning but a true limit violation.
5332 task
= current_task();
5334 ledger_get_limit(task
->ledger
, task_ledgers
.phys_footprint
, &max_footprint
);
5335 max_footprint_mb
= max_footprint
>> 20;
5337 memlimit_is_active
= task_get_memlimit_is_active(task
);
5338 memlimit_is_fatal
= task_get_memlimit_is_fatal(task
);
5341 * If this is an actual violation (not a warning), then generate EXC_RESOURCE exception.
5342 * We only generate the exception once per process per memlimit (active/inactive limit).
5343 * To enforce this, we monitor state based on the memlimit's active/inactive attribute
5344 * and we disable it by marking that memlimit as exception triggered.
5346 if ((is_warning
== FALSE
) && (!task_has_triggered_exc_resource(task
, memlimit_is_active
))) {
5347 PROC_CROSSED_HIGH_WATERMARK__SEND_EXC_RESOURCE_AND_SUSPEND((int)max_footprint_mb
, memlimit_is_fatal
);
5348 memorystatus_log_exception((int)max_footprint_mb
, memlimit_is_active
, memlimit_is_fatal
);
5349 task_mark_has_triggered_exc_resource(task
, memlimit_is_active
);
5352 memorystatus_on_ledger_footprint_exceeded(is_warning
, memlimit_is_active
, memlimit_is_fatal
);
5355 extern int proc_check_footprint_priv(void);
5358 task_set_phys_footprint_limit(
5363 kern_return_t error
;
5365 boolean_t memlimit_is_active
;
5366 boolean_t memlimit_is_fatal
;
5368 if ((error
= proc_check_footprint_priv())) {
5369 return (KERN_NO_ACCESS
);
5373 * This call should probably be obsoleted.
5374 * But for now, we default to current state.
5376 memlimit_is_active
= task_get_memlimit_is_active(task
);
5377 memlimit_is_fatal
= task_get_memlimit_is_fatal(task
);
5379 return task_set_phys_footprint_limit_internal(task
, new_limit_mb
, old_limit_mb
, memlimit_is_active
, memlimit_is_fatal
);
5383 task_convert_phys_footprint_limit(
5385 int *converted_limit_mb
)
5387 if (limit_mb
== -1) {
5391 if (max_task_footprint
!= 0) {
5392 *converted_limit_mb
= (int)(max_task_footprint
/ 1024 / 1024); /* bytes to MB */
5394 *converted_limit_mb
= (int)(LEDGER_LIMIT_INFINITY
>> 20);
5397 /* nothing to convert */
5398 *converted_limit_mb
= limit_mb
;
5400 return (KERN_SUCCESS
);
5405 task_set_phys_footprint_limit_internal(
5409 boolean_t memlimit_is_active
,
5410 boolean_t memlimit_is_fatal
)
5412 ledger_amount_t old
;
5414 ledger_get_limit(task
->ledger
, task_ledgers
.phys_footprint
, &old
);
5417 * Check that limit >> 20 will not give an "unexpected" 32-bit
5418 * result. There are, however, implicit assumptions that -1 mb limit
5419 * equates to LEDGER_LIMIT_INFINITY.
5421 assert(((old
& 0xFFF0000000000000LL
) == 0) || (old
== LEDGER_LIMIT_INFINITY
));
5424 *old_limit_mb
= (int)(old
>> 20);
5427 if (new_limit_mb
== -1) {
5429 * Caller wishes to remove the limit.
5431 ledger_set_limit(task
->ledger
, task_ledgers
.phys_footprint
,
5432 max_task_footprint
? max_task_footprint
: LEDGER_LIMIT_INFINITY
,
5433 max_task_footprint
? max_task_footprint_warning_level
: 0);
5436 task_set_memlimit_is_active(task
, memlimit_is_active
);
5437 task_set_memlimit_is_fatal(task
, memlimit_is_fatal
);
5440 return (KERN_SUCCESS
);
5443 #ifdef CONFIG_NOMONITORS
5444 return (KERN_SUCCESS
);
5445 #endif /* CONFIG_NOMONITORS */
5449 if ((memlimit_is_active
== task_get_memlimit_is_active(task
)) &&
5450 (memlimit_is_fatal
== task_get_memlimit_is_fatal(task
)) &&
5451 (((ledger_amount_t
)new_limit_mb
<< 20) == old
)) {
5453 * memlimit state is not changing
5456 return(KERN_SUCCESS
);
5459 task_set_memlimit_is_active(task
, memlimit_is_active
);
5460 task_set_memlimit_is_fatal(task
, memlimit_is_fatal
);
5462 ledger_set_limit(task
->ledger
, task_ledgers
.phys_footprint
,
5463 (ledger_amount_t
)new_limit_mb
<< 20, PHYS_FOOTPRINT_WARNING_LEVEL
);
5465 if (task
== current_task()) {
5466 ledger_check_new_balance(current_thread(), task
->ledger
,
5467 task_ledgers
.phys_footprint
);
5472 return (KERN_SUCCESS
);
5476 task_get_phys_footprint_limit(
5480 ledger_amount_t limit
;
5482 ledger_get_limit(task
->ledger
, task_ledgers
.phys_footprint
, &limit
);
5484 * Check that limit >> 20 will not give an "unexpected" signed, 32-bit
5485 * result. There are, however, implicit assumptions that -1 mb limit
5486 * equates to LEDGER_LIMIT_INFINITY.
5488 assert(((limit
& 0xFFF0000000000000LL
) == 0) || (limit
== LEDGER_LIMIT_INFINITY
));
5489 *limit_mb
= (int)(limit
>> 20);
5491 return (KERN_SUCCESS
);
5493 #else /* CONFIG_MEMORYSTATUS */
5495 task_set_phys_footprint_limit(
5496 __unused task_t task
,
5497 __unused
int new_limit_mb
,
5498 __unused
int *old_limit_mb
)
5500 return (KERN_FAILURE
);
5504 task_get_phys_footprint_limit(
5505 __unused task_t task
,
5506 __unused
int *limit_mb
)
5508 return (KERN_FAILURE
);
5510 #endif /* CONFIG_MEMORYSTATUS */
5513 task_set_thread_limit(task_t task
, uint16_t thread_limit
)
5515 assert(task
!= kernel_task
);
5516 if (thread_limit
<= TASK_MAX_THREAD_LIMIT
) {
5518 task
->task_thread_limit
= thread_limit
;
5524 * We need to export some functions to other components that
5525 * are currently implemented in macros within the osfmk
5526 * component. Just export them as functions of the same name.
5528 boolean_t
is_kerneltask(task_t t
)
5530 if (t
== kernel_task
)
5536 boolean_t
is_corpsetask(task_t t
)
5538 return (task_is_a_corpse(t
));
5542 task_t
current_task(void);
5543 task_t
current_task(void)
5545 return (current_task_fast());
5548 #undef task_reference
5549 void task_reference(task_t task
);
5554 if (task
!= TASK_NULL
)
5555 task_reference_internal(task
);
5558 /* defined in bsd/kern/kern_prot.c */
5559 extern int get_audit_token_pid(audit_token_t
*audit_token
);
5561 int task_pid(task_t task
)
5564 return get_audit_token_pid(&task
->audit_token
);
5570 * This routine finds a thread in a task by its unique id
5571 * Returns a referenced thread or THREAD_NULL if the thread was not found
5573 * TODO: This is super inefficient - it's an O(threads in task) list walk!
5574 * We should make a tid hash, or transition all tid clients to thread ports
5576 * Precondition: No locks held (will take task lock)
5579 task_findtid(task_t task
, uint64_t tid
)
5581 thread_t self
= current_thread();
5582 thread_t found_thread
= THREAD_NULL
;
5583 thread_t iter_thread
= THREAD_NULL
;
5585 /* Short-circuit the lookup if we're looking up ourselves */
5586 if (tid
== self
->thread_id
|| tid
== TID_NULL
) {
5587 assert(self
->task
== task
);
5589 thread_reference(self
);
5596 queue_iterate(&task
->threads
, iter_thread
, thread_t
, task_threads
) {
5597 if (iter_thread
->thread_id
== tid
) {
5598 found_thread
= iter_thread
;
5599 thread_reference(found_thread
);
5606 return (found_thread
);
5609 int pid_from_task(task_t task
)
5613 if (task
->bsd_info
) {
5614 pid
= proc_pid(task
->bsd_info
);
5616 pid
= task_pid(task
);
5623 * Control the CPU usage monitor for a task.
5626 task_cpu_usage_monitor_ctl(task_t task
, uint32_t *flags
)
5628 int error
= KERN_SUCCESS
;
5630 if (*flags
& CPUMON_MAKE_FATAL
) {
5631 task
->rusage_cpu_flags
|= TASK_RUSECPU_FLAGS_FATAL_CPUMON
;
5633 error
= KERN_INVALID_ARGUMENT
;
5640 * Control the wakeups monitor for a task.
5643 task_wakeups_monitor_ctl(task_t task
, uint32_t *flags
, int32_t *rate_hz
)
5645 ledger_t ledger
= task
->ledger
;
5648 if (*flags
& WAKEMON_GET_PARAMS
) {
5649 ledger_amount_t limit
;
5652 ledger_get_limit(ledger
, task_ledgers
.interrupt_wakeups
, &limit
);
5653 ledger_get_period(ledger
, task_ledgers
.interrupt_wakeups
, &period
);
5655 if (limit
!= LEDGER_LIMIT_INFINITY
) {
5657 * An active limit means the wakeups monitor is enabled.
5659 *rate_hz
= (int32_t)(limit
/ (int64_t)(period
/ NSEC_PER_SEC
));
5660 *flags
= WAKEMON_ENABLE
;
5661 if (task
->rusage_cpu_flags
& TASK_RUSECPU_FLAGS_FATAL_WAKEUPSMON
) {
5662 *flags
|= WAKEMON_MAKE_FATAL
;
5665 *flags
= WAKEMON_DISABLE
;
5670 * If WAKEMON_GET_PARAMS is present in flags, all other flags are ignored.
5673 return KERN_SUCCESS
;
5676 if (*flags
& WAKEMON_ENABLE
) {
5677 if (*flags
& WAKEMON_SET_DEFAULTS
) {
5678 *rate_hz
= task_wakeups_monitor_rate
;
5681 #ifndef CONFIG_NOMONITORS
5682 if (*flags
& WAKEMON_MAKE_FATAL
) {
5683 task
->rusage_cpu_flags
|= TASK_RUSECPU_FLAGS_FATAL_WAKEUPSMON
;
5685 #endif /* CONFIG_NOMONITORS */
5687 if (*rate_hz
<= 0) {
5689 return KERN_INVALID_ARGUMENT
;
5692 #ifndef CONFIG_NOMONITORS
5693 ledger_set_limit(ledger
, task_ledgers
.interrupt_wakeups
, *rate_hz
* task_wakeups_monitor_interval
,
5694 task_wakeups_monitor_ustackshots_trigger_pct
);
5695 ledger_set_period(ledger
, task_ledgers
.interrupt_wakeups
, task_wakeups_monitor_interval
* NSEC_PER_SEC
);
5696 ledger_enable_callback(ledger
, task_ledgers
.interrupt_wakeups
);
5697 #endif /* CONFIG_NOMONITORS */
5698 } else if (*flags
& WAKEMON_DISABLE
) {
5700 * Caller wishes to disable wakeups monitor on the task.
5702 * Disable telemetry if it was triggered by the wakeups monitor, and
5703 * remove the limit & callback on the wakeups ledger entry.
5705 #if CONFIG_TELEMETRY
5706 telemetry_task_ctl_locked(task
, TF_WAKEMON_WARNING
, 0);
5708 ledger_disable_refill(ledger
, task_ledgers
.interrupt_wakeups
);
5709 ledger_disable_callback(ledger
, task_ledgers
.interrupt_wakeups
);
5713 return KERN_SUCCESS
;
5717 task_wakeups_rate_exceeded(int warning
, __unused
const void *param0
, __unused
const void *param1
)
5719 if (warning
== LEDGER_WARNING_ROSE_ABOVE
) {
5720 #if CONFIG_TELEMETRY
5722 * This task is in danger of violating the wakeups monitor. Enable telemetry on this task
5723 * so there are micro-stackshots available if and when EXC_RESOURCE is triggered.
5725 telemetry_task_ctl(current_task(), TF_WAKEMON_WARNING
, 1);
5730 #if CONFIG_TELEMETRY
5732 * If the balance has dipped below the warning level (LEDGER_WARNING_DIPPED_BELOW) or
5733 * exceeded the limit, turn telemetry off for the task.
5735 telemetry_task_ctl(current_task(), TF_WAKEMON_WARNING
, 0);
5739 SENDING_NOTIFICATION__THIS_PROCESS_IS_CAUSING_TOO_MANY_WAKEUPS();
5743 void __attribute__((noinline
))
5744 SENDING_NOTIFICATION__THIS_PROCESS_IS_CAUSING_TOO_MANY_WAKEUPS(void)
5746 task_t task
= current_task();
5748 const char *procname
= "unknown";
5751 #ifdef EXC_RESOURCE_MONITORS
5752 mach_exception_data_type_t code
[EXCEPTION_CODE_MAX
];
5753 #endif /* EXC_RESOURCE_MONITORS */
5754 struct ledger_entry_info lei
;
5757 pid
= proc_selfpid();
5758 if (task
->bsd_info
!= NULL
)
5759 procname
= proc_name_address(current_task()->bsd_info
);
5762 ledger_get_entry_info(task
->ledger
, task_ledgers
.interrupt_wakeups
, &lei
);
5765 * Disable the exception notification so we don't overwhelm
5766 * the listener with an endless stream of redundant exceptions.
5767 * TODO: detect whether another thread is already reporting the violation.
5769 uint32_t flags
= WAKEMON_DISABLE
;
5770 task_wakeups_monitor_ctl(task
, &flags
, NULL
);
5772 fatal
= task
->rusage_cpu_flags
& TASK_RUSECPU_FLAGS_FATAL_WAKEUPSMON
;
5773 trace_resource_violation(RMON_CPUWAKES_VIOLATED
, &lei
);
5774 os_log(OS_LOG_DEFAULT
, "process %s[%d] caught waking the CPU %llu times "
5775 "over ~%llu seconds, averaging %llu wakes / second and "
5776 "violating a %slimit of %llu wakes over %llu seconds.\n",
5778 lei
.lei_balance
, lei
.lei_last_refill
/ NSEC_PER_SEC
,
5779 lei
.lei_last_refill
== 0 ? 0 :
5780 (NSEC_PER_SEC
* lei
.lei_balance
/ lei
.lei_last_refill
),
5781 fatal
? "FATAL " : "",
5782 lei
.lei_limit
, lei
.lei_refill_period
/ NSEC_PER_SEC
);
5784 kr
= send_resource_violation(send_cpu_wakes_violation
, task
, &lei
,
5785 fatal
? kRNFatalLimitFlag
: 0);
5787 printf("send_resource_violation(CPU wakes, ...): error %#x\n", kr
);
5790 #ifdef EXC_RESOURCE_MONITORS
5791 if (disable_exc_resource
) {
5792 printf("process %s[%d] caught causing excessive wakeups. EXC_RESOURCE "
5793 "supressed by a boot-arg\n", procname
, pid
);
5797 os_log(OS_LOG_DEFAULT
, "process %s[%d] caught causing excessive wakeups. EXC_RESOURCE "
5798 "supressed due to audio playback\n", procname
, pid
);
5801 if (lei
.lei_last_refill
== 0) {
5802 os_log(OS_LOG_DEFAULT
, "process %s[%d] caught causing excessive wakeups. EXC_RESOURCE "
5803 "supressed due to lei.lei_last_refill = 0 \n", procname
, pid
);
5806 code
[0] = code
[1] = 0;
5807 EXC_RESOURCE_ENCODE_TYPE(code
[0], RESOURCE_TYPE_WAKEUPS
);
5808 EXC_RESOURCE_ENCODE_FLAVOR(code
[0], FLAVOR_WAKEUPS_MONITOR
);
5809 EXC_RESOURCE_CPUMONITOR_ENCODE_WAKEUPS_PERMITTED(code
[0],
5810 NSEC_PER_SEC
* lei
.lei_limit
/ lei
.lei_refill_period
);
5811 EXC_RESOURCE_CPUMONITOR_ENCODE_OBSERVATION_INTERVAL(code
[0],
5812 lei
.lei_last_refill
);
5813 EXC_RESOURCE_CPUMONITOR_ENCODE_WAKEUPS_OBSERVED(code
[1],
5814 NSEC_PER_SEC
* lei
.lei_balance
/ lei
.lei_last_refill
);
5815 exception_triage(EXC_RESOURCE
, code
, EXCEPTION_CODE_MAX
);
5816 #endif /* EXC_RESOURCE_MONITORS */
5819 task_terminate_internal(task
);
5824 global_update_logical_writes(int64_t io_delta
)
5826 int64_t old_count
, new_count
;
5827 boolean_t needs_telemetry
;
5830 new_count
= old_count
= global_logical_writes_count
;
5831 new_count
+= io_delta
;
5832 if (new_count
>= io_telemetry_limit
) {
5834 needs_telemetry
= TRUE
;
5836 needs_telemetry
= FALSE
;
5838 } while(!OSCompareAndSwap64(old_count
, new_count
, &global_logical_writes_count
));
5839 return needs_telemetry
;
5842 void task_update_logical_writes(task_t task
, uint32_t io_size
, int flags
, void *vp
)
5844 int64_t io_delta
= 0;
5845 boolean_t needs_telemetry
= FALSE
;
5847 if ((!task
) || (!io_size
) || (!vp
))
5850 KERNEL_DEBUG_CONSTANT((MACHDBG_CODE(DBG_MACH_VM
, VM_DATA_WRITE
)) | DBG_FUNC_NONE
,
5851 task_pid(task
), io_size
, flags
, (uintptr_t)VM_KERNEL_ADDRPERM(vp
), 0);
5852 DTRACE_IO4(logical_writes
, struct task
*, task
, uint32_t, io_size
, int, flags
, vnode
*, vp
);
5854 case TASK_WRITE_IMMEDIATE
:
5855 OSAddAtomic64(io_size
, (SInt64
*)&(task
->task_immediate_writes
));
5856 ledger_credit(task
->ledger
, task_ledgers
.logical_writes
, io_size
);
5858 case TASK_WRITE_DEFERRED
:
5859 OSAddAtomic64(io_size
, (SInt64
*)&(task
->task_deferred_writes
));
5860 ledger_credit(task
->ledger
, task_ledgers
.logical_writes
, io_size
);
5862 case TASK_WRITE_INVALIDATED
:
5863 OSAddAtomic64(io_size
, (SInt64
*)&(task
->task_invalidated_writes
));
5864 ledger_debit(task
->ledger
, task_ledgers
.logical_writes
, io_size
);
5866 case TASK_WRITE_METADATA
:
5867 OSAddAtomic64(io_size
, (SInt64
*)&(task
->task_metadata_writes
));
5868 ledger_credit(task
->ledger
, task_ledgers
.logical_writes
, io_size
);
5872 io_delta
= (flags
== TASK_WRITE_INVALIDATED
) ? ((int64_t)io_size
* -1ll) : ((int64_t)io_size
);
5873 if (io_telemetry_limit
!= 0) {
5874 /* If io_telemetry_limit is 0, disable global updates and I/O telemetry */
5875 needs_telemetry
= global_update_logical_writes(io_delta
);
5876 if (needs_telemetry
) {
5877 act_set_io_telemetry_ast(current_thread());
5883 * Control the I/O monitor for a task.
5886 task_io_monitor_ctl(task_t task
, uint32_t *flags
)
5888 ledger_t ledger
= task
->ledger
;
5891 if (*flags
& IOMON_ENABLE
) {
5892 /* Configure the physical I/O ledger */
5893 ledger_set_limit(ledger
, task_ledgers
.physical_writes
, (task_iomon_limit_mb
* 1024 * 1024), 0);
5894 ledger_set_period(ledger
, task_ledgers
.physical_writes
, (task_iomon_interval_secs
* NSEC_PER_SEC
));
5896 /* Configure the logical I/O ledger */
5897 ledger_set_limit(ledger
, task_ledgers
.logical_writes
, (task_iomon_limit_mb
* 1024 * 1024), 0);
5898 ledger_set_period(ledger
, task_ledgers
.logical_writes
, (task_iomon_interval_secs
* NSEC_PER_SEC
));
5900 } else if (*flags
& IOMON_DISABLE
) {
5902 * Caller wishes to disable I/O monitor on the task.
5904 ledger_disable_refill(ledger
, task_ledgers
.physical_writes
);
5905 ledger_disable_callback(ledger
, task_ledgers
.physical_writes
);
5906 ledger_disable_refill(ledger
, task_ledgers
.logical_writes
);
5907 ledger_disable_callback(ledger
, task_ledgers
.logical_writes
);
5911 return KERN_SUCCESS
;
5915 task_io_rate_exceeded(int warning
, const void *param0
, __unused
const void *param1
)
5918 SENDING_NOTIFICATION__THIS_PROCESS_IS_CAUSING_TOO_MUCH_IO((int)param0
);
5922 void __attribute__((noinline
)) SENDING_NOTIFICATION__THIS_PROCESS_IS_CAUSING_TOO_MUCH_IO(int flavor
)
5925 task_t task
= current_task();
5926 #ifdef EXC_RESOURCE_MONITORS
5927 mach_exception_data_type_t code
[EXCEPTION_CODE_MAX
];
5928 #endif /* EXC_RESOURCE_MONITORS */
5929 struct ledger_entry_info lei
;
5933 pid
= proc_selfpid();
5936 * Get the ledger entry info. We need to do this before disabling the exception
5937 * to get correct values for all fields.
5940 case FLAVOR_IO_PHYSICAL_WRITES
:
5941 ledger_get_entry_info(task
->ledger
, task_ledgers
.physical_writes
, &lei
);
5943 case FLAVOR_IO_LOGICAL_WRITES
:
5944 ledger_get_entry_info(task
->ledger
, task_ledgers
.logical_writes
, &lei
);
5950 * Disable the exception notification so we don't overwhelm
5951 * the listener with an endless stream of redundant exceptions.
5952 * TODO: detect whether another thread is already reporting the violation.
5954 uint32_t flags
= IOMON_DISABLE
;
5955 task_io_monitor_ctl(task
, &flags
);
5957 if (flavor
== FLAVOR_IO_LOGICAL_WRITES
) {
5958 trace_resource_violation(RMON_LOGWRITES_VIOLATED
, &lei
);
5960 os_log(OS_LOG_DEFAULT
, "process [%d] caught causing excessive I/O (flavor: %d). Task I/O: %lld MB. [Limit : %lld MB per %lld secs]\n",
5961 pid
, flavor
, (lei
.lei_balance
/ (1024 * 1024)), (lei
.lei_limit
/ (1024 * 1024)), (lei
.lei_refill_period
/ NSEC_PER_SEC
));
5963 kr
= send_resource_violation(send_disk_writes_violation
, task
, &lei
, kRNFlagsNone
);
5965 printf("send_resource_violation(disk_writes, ...): error %#x\n", kr
);
5968 #ifdef EXC_RESOURCE_MONITORS
5969 code
[0] = code
[1] = 0;
5970 EXC_RESOURCE_ENCODE_TYPE(code
[0], RESOURCE_TYPE_IO
);
5971 EXC_RESOURCE_ENCODE_FLAVOR(code
[0], flavor
);
5972 EXC_RESOURCE_IO_ENCODE_INTERVAL(code
[0], (lei
.lei_refill_period
/ NSEC_PER_SEC
));
5973 EXC_RESOURCE_IO_ENCODE_LIMIT(code
[0], (lei
.lei_limit
/ (1024 * 1024)));
5974 EXC_RESOURCE_IO_ENCODE_OBSERVED(code
[1], (lei
.lei_balance
/ (1024 * 1024)));
5975 exception_triage(EXC_RESOURCE
, code
, EXCEPTION_CODE_MAX
);
5976 #endif /* EXC_RESOURCE_MONITORS */
5979 /* Placeholders for the task set/get voucher interfaces */
5981 task_get_mach_voucher(
5983 mach_voucher_selector_t __unused which
,
5984 ipc_voucher_t
*voucher
)
5986 if (TASK_NULL
== task
)
5987 return KERN_INVALID_TASK
;
5990 return KERN_SUCCESS
;
5994 task_set_mach_voucher(
5996 ipc_voucher_t __unused voucher
)
5998 if (TASK_NULL
== task
)
5999 return KERN_INVALID_TASK
;
6001 return KERN_SUCCESS
;
6005 task_swap_mach_voucher(
6007 ipc_voucher_t new_voucher
,
6008 ipc_voucher_t
*in_out_old_voucher
)
6010 if (TASK_NULL
== task
)
6011 return KERN_INVALID_TASK
;
6013 *in_out_old_voucher
= new_voucher
;
6014 return KERN_SUCCESS
;
6017 void task_set_gpu_denied(task_t task
, boolean_t denied
)
6022 task
->t_flags
|= TF_GPU_DENIED
;
6024 task
->t_flags
&= ~TF_GPU_DENIED
;
6030 boolean_t
task_is_gpu_denied(task_t task
)
6032 /* We don't need the lock to read this flag */
6033 return (task
->t_flags
& TF_GPU_DENIED
) ? TRUE
: FALSE
;
6037 uint64_t get_task_memory_region_count(task_t task
)
6040 map
= (task
== kernel_task
) ? kernel_map
: task
->map
;
6041 return((uint64_t)get_map_nentries(map
));
6045 kdebug_trace_dyld_internal(uint32_t base_code
,
6046 struct dyld_kernel_image_info
*info
)
6048 static_assert(sizeof(info
->uuid
) >= 16);
6050 #if defined(__LP64__)
6051 uint64_t *uuid
= (uint64_t *)&(info
->uuid
);
6053 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
6054 KDBG_EVENTID(DBG_DYLD
, DBG_DYLD_UUID
, base_code
), uuid
[0],
6055 uuid
[1], info
->load_addr
,
6056 (uint64_t)info
->fsid
.val
[0] | ((uint64_t)info
->fsid
.val
[1] << 32),
6058 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
6059 KDBG_EVENTID(DBG_DYLD
, DBG_DYLD_UUID
, base_code
+ 1),
6060 (uint64_t)info
->fsobjid
.fid_objno
|
6061 ((uint64_t)info
->fsobjid
.fid_generation
<< 32),
6063 #else /* defined(__LP64__) */
6064 uint32_t *uuid
= (uint32_t *)&(info
->uuid
);
6066 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
6067 KDBG_EVENTID(DBG_DYLD
, DBG_DYLD_UUID
, base_code
+ 2), uuid
[0],
6068 uuid
[1], uuid
[2], uuid
[3], 0);
6069 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
6070 KDBG_EVENTID(DBG_DYLD
, DBG_DYLD_UUID
, base_code
+ 3),
6071 (uint32_t)info
->load_addr
, info
->fsid
.val
[0], info
->fsid
.val
[1],
6072 info
->fsobjid
.fid_objno
, 0);
6073 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
6074 KDBG_EVENTID(DBG_DYLD
, DBG_DYLD_UUID
, base_code
+ 4),
6075 info
->fsobjid
.fid_generation
, 0, 0, 0, 0);
6076 #endif /* !defined(__LP64__) */
6079 static kern_return_t
6080 kdebug_trace_dyld(task_t task
, uint32_t base_code
,
6081 vm_map_copy_t infos_copy
, mach_msg_type_number_t infos_len
)
6084 dyld_kernel_image_info_array_t infos
;
6085 vm_map_offset_t map_data
;
6089 return KERN_INVALID_ADDRESS
;
6092 if (!kdebug_enable
||
6093 !kdebug_debugid_enabled(KDBG_EVENTID(DBG_DYLD
, DBG_DYLD_UUID
, 0)))
6095 vm_map_copy_discard(infos_copy
);
6096 return KERN_SUCCESS
;
6099 if (task
== NULL
|| task
!= current_task()) {
6100 return KERN_INVALID_TASK
;
6103 kr
= vm_map_copyout(ipc_kernel_map
, &map_data
, (vm_map_copy_t
)infos_copy
);
6104 if (kr
!= KERN_SUCCESS
) {
6108 infos
= CAST_DOWN(dyld_kernel_image_info_array_t
, map_data
);
6110 for (mach_msg_type_number_t i
= 0; i
< infos_len
; i
++) {
6111 kdebug_trace_dyld_internal(base_code
, &(infos
[i
]));
6114 data
= CAST_DOWN(vm_offset_t
, map_data
);
6115 mach_vm_deallocate(ipc_kernel_map
, data
, infos_len
* sizeof(infos
[0]));
6116 return KERN_SUCCESS
;
6120 task_register_dyld_image_infos(task_t task
,
6121 dyld_kernel_image_info_array_t infos_copy
,
6122 mach_msg_type_number_t infos_len
)
6124 return kdebug_trace_dyld(task
, DBG_DYLD_UUID_MAP_A
,
6125 (vm_map_copy_t
)infos_copy
, infos_len
);
6129 task_unregister_dyld_image_infos(task_t task
,
6130 dyld_kernel_image_info_array_t infos_copy
,
6131 mach_msg_type_number_t infos_len
)
6133 return kdebug_trace_dyld(task
, DBG_DYLD_UUID_UNMAP_A
,
6134 (vm_map_copy_t
)infos_copy
, infos_len
);
6138 task_get_dyld_image_infos(__unused task_t task
,
6139 __unused dyld_kernel_image_info_array_t
* dyld_images
,
6140 __unused mach_msg_type_number_t
* dyld_imagesCnt
)
6142 return KERN_NOT_SUPPORTED
;
6146 task_register_dyld_shared_cache_image_info(task_t task
,
6147 dyld_kernel_image_info_t cache_img
,
6148 __unused boolean_t no_cache
,
6149 __unused boolean_t private_cache
)
6151 if (task
== NULL
|| task
!= current_task()) {
6152 return KERN_INVALID_TASK
;
6155 kdebug_trace_dyld_internal(DBG_DYLD_UUID_SHARED_CACHE_A
, &cache_img
);
6156 return KERN_SUCCESS
;
6160 task_register_dyld_set_dyld_state(__unused task_t task
,
6161 __unused
uint8_t dyld_state
)
6163 return KERN_NOT_SUPPORTED
;
6167 task_register_dyld_get_process_state(__unused task_t task
,
6168 __unused dyld_kernel_process_info_t
* dyld_process_state
)
6170 return KERN_NOT_SUPPORTED
;
6174 task_inspect(task_inspect_t task_insp
, task_inspect_flavor_t flavor
,
6175 task_inspect_info_t info_out
, mach_msg_type_number_t
*size_in_out
)
6178 task_t task
= (task_t
)task_insp
;
6179 kern_return_t kr
= KERN_SUCCESS
;
6180 mach_msg_type_number_t size
;
6182 if (task
== TASK_NULL
) {
6183 return KERN_INVALID_ARGUMENT
;
6186 size
= *size_in_out
;
6189 case TASK_INSPECT_BASIC_COUNTS
: {
6190 struct task_inspect_basic_counts
*bc
;
6191 uint64_t task_counts
[MT_CORE_NFIXED
] = { 0 };
6193 if (size
< TASK_INSPECT_BASIC_COUNTS_COUNT
) {
6194 kr
= KERN_INVALID_ARGUMENT
;
6198 mt_fixed_task_counts(task
, task_counts
);
6199 bc
= (struct task_inspect_basic_counts
*)info_out
;
6200 #ifdef MT_CORE_INSTRS
6201 bc
->instructions
= task_counts
[MT_CORE_INSTRS
];
6202 #else /* defined(MT_CORE_INSTRS) */
6203 bc
->instructions
= 0;
6204 #endif /* !defined(MT_CORE_INSTRS) */
6205 bc
->cycles
= task_counts
[MT_CORE_CYCLES
];
6206 size
= TASK_INSPECT_BASIC_COUNTS_COUNT
;
6210 kr
= KERN_INVALID_ARGUMENT
;
6214 if (kr
== KERN_SUCCESS
) {
6215 *size_in_out
= size
;
6218 #else /* MONOTONIC */
6219 #pragma unused(task_insp, flavor, info_out, size_in_out)
6220 return KERN_NOT_SUPPORTED
;
6221 #endif /* !MONOTONIC */
6224 #if CONFIG_SECLUDED_MEMORY
6225 int num_tasks_can_use_secluded_mem
= 0;
6228 task_set_can_use_secluded_mem(
6230 boolean_t can_use_secluded_mem
)
6232 if (!task
->task_could_use_secluded_mem
) {
6236 task_set_can_use_secluded_mem_locked(task
, can_use_secluded_mem
);
6241 task_set_can_use_secluded_mem_locked(
6243 boolean_t can_use_secluded_mem
)
6245 assert(task
->task_could_use_secluded_mem
);
6246 if (can_use_secluded_mem
&&
6247 secluded_for_apps
&& /* global boot-arg */
6248 !task
->task_can_use_secluded_mem
) {
6249 assert(num_tasks_can_use_secluded_mem
>= 0);
6251 (volatile SInt32
*)&num_tasks_can_use_secluded_mem
);
6252 task
->task_can_use_secluded_mem
= TRUE
;
6253 } else if (!can_use_secluded_mem
&&
6254 task
->task_can_use_secluded_mem
) {
6255 assert(num_tasks_can_use_secluded_mem
> 0);
6257 (volatile SInt32
*)&num_tasks_can_use_secluded_mem
);
6258 task
->task_can_use_secluded_mem
= FALSE
;
6263 task_set_could_use_secluded_mem(
6265 boolean_t could_use_secluded_mem
)
6267 task
->task_could_use_secluded_mem
= could_use_secluded_mem
;
6271 task_set_could_also_use_secluded_mem(
6273 boolean_t could_also_use_secluded_mem
)
6275 task
->task_could_also_use_secluded_mem
= could_also_use_secluded_mem
;
6279 task_can_use_secluded_mem(
6283 if (task
->task_can_use_secluded_mem
) {
6284 assert(task
->task_could_use_secluded_mem
);
6285 assert(num_tasks_can_use_secluded_mem
> 0);
6288 if (task
->task_could_also_use_secluded_mem
&&
6289 num_tasks_can_use_secluded_mem
> 0) {
6290 assert(num_tasks_can_use_secluded_mem
> 0);
6295 * If a single task is using more than some amount of
6296 * memory, allow it to dip into secluded and also begin
6297 * suppression of secluded memory until the tasks exits.
6299 if (is_alloc
&& secluded_shutoff_trigger
!= 0) {
6300 uint64_t phys_used
= get_task_phys_footprint(task
);
6301 if (phys_used
> secluded_shutoff_trigger
) {
6302 start_secluded_suppression(task
);
6311 task_could_use_secluded_mem(
6314 return task
->task_could_use_secluded_mem
;
6316 #endif /* CONFIG_SECLUDED_MEMORY */
6319 task_io_user_clients(task_t task
)
6321 return (&task
->io_user_clients
);
6325 task_copy_fields_for_exec(task_t dst_task
, task_t src_task
)
6327 dst_task
->vtimers
= src_task
->vtimers
;
6330 #if DEVELOPMENT || DEBUG
6331 int vm_region_footprint
= 0;
6332 #endif /* DEVELOPMENT || DEBUG */
6335 task_self_region_footprint(void)
6337 #if DEVELOPMENT || DEBUG
6338 if (vm_region_footprint
) {
6339 /* system-wide override */
6342 #endif /* DEVELOPMENT || DEBUG */
6343 return current_task()->task_region_footprint
;
6347 task_self_region_footprint_set(
6352 curtask
= current_task();
6355 curtask
->task_region_footprint
= TRUE
;
6357 curtask
->task_region_footprint
= FALSE
;
6359 task_unlock(curtask
);
6363 task_set_darkwake_mode(task_t task
, boolean_t set_mode
)
6370 task
->t_flags
|= TF_DARKWAKE_MODE
;
6372 task
->t_flags
&= ~(TF_DARKWAKE_MODE
);
6379 task_get_darkwake_mode(task_t task
)
6382 return ((task
->t_flags
& TF_DARKWAKE_MODE
) != 0);
6387 task_set_legacy_footprint(
6392 task
->task_legacy_footprint
= new_val
;
6395 #endif /* __arm64__ */