2 * Copyright (c) 2000-2020 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>
128 #include <kern/restartable.h>
130 #include <corpses/task_corpse.h>
132 #include <kern/telemetry.h>
136 #include <kern/monotonic.h>
137 #include <machine/monotonic.h>
138 #endif /* MONOTONIC */
143 #include <vm/vm_map.h>
144 #include <vm/vm_kern.h> /* for kernel_map, ipc_kernel_map */
145 #include <vm/vm_pageout.h>
146 #include <vm/vm_protos.h>
147 #include <vm/vm_purgeable_internal.h>
148 #include <vm/vm_compressor_pager.h>
150 #include <sys/resource.h>
151 #include <sys/signalvar.h> /* for coredump */
152 #include <sys/bsdtask_info.h>
154 * Exported interfaces
157 #include <mach/task_server.h>
158 #include <mach/mach_host_server.h>
159 #include <mach/host_security_server.h>
160 #include <mach/mach_port_server.h>
162 #include <vm/vm_shared_region.h>
164 #include <libkern/OSDebug.h>
165 #include <libkern/OSAtomic.h>
166 #include <libkern/section_keywords.h>
168 #include <mach-o/loader.h>
169 #include <kdp/kdp_dyld.h>
171 #include <kern/sfi.h> /* picks up ledger.h */
174 #include <security/mac_mach_internal.h>
177 #include <IOKit/IOBSD.h>
180 extern int kpc_force_all_ctrs(task_t
, int);
183 SECURITY_READ_ONLY_LATE(task_t
) kernel_task
;
185 static SECURITY_READ_ONLY_LATE(zone_t
) task_zone
;
186 ZONE_INIT(&task_zone
, "tasks", sizeof(struct task
),
187 ZC_NOENCRYPT
| ZC_ZFREE_CLEARMEM
,
190 extern int exc_via_corpse_forking
;
191 extern int corpse_for_fatal_memkill
;
192 extern boolean_t
proc_send_synchronous_EXC_RESOURCE(void *p
);
193 extern void task_disown_frozen_csegs(task_t owner_task
);
195 /* Flag set by core audio when audio is playing. Used to stifle EXC_RESOURCE generation when active. */
196 int audio_active
= 0;
199 * structure for tracking zone usage
200 * Used either one per task/thread for all zones or <per-task,per-zone>.
202 typedef struct zinfo_usage_store_t
{
203 /* These fields may be updated atomically, and so must be 8 byte aligned */
204 uint64_t alloc
__attribute__((aligned(8))); /* allocation counter */
205 uint64_t free
__attribute__((aligned(8))); /* free counter */
206 } zinfo_usage_store_t
;
208 zinfo_usage_store_t tasks_tkm_private
;
209 zinfo_usage_store_t tasks_tkm_shared
;
211 /* A container to accumulate statistics for expired tasks */
212 expired_task_statistics_t dead_task_statistics
;
213 LCK_SPIN_DECLARE_ATTR(dead_task_statistics_lock
, &task_lck_grp
, &task_lck_attr
);
215 ledger_template_t task_ledger_template
= NULL
;
217 /* global lock for task_dyld_process_info_notify_{register, deregister, get_trap} */
218 LCK_GRP_DECLARE(g_dyldinfo_mtx_grp
, "g_dyldinfo");
219 LCK_MTX_DECLARE(g_dyldinfo_mtx
, &g_dyldinfo_mtx_grp
);
221 SECURITY_READ_ONLY_LATE(struct _task_ledger_indices
) task_ledgers
__attribute__((used
)) =
229 .alternate_accounting
= -1,
230 .alternate_accounting_compressed
= -1,
232 .phys_footprint
= -1,
233 .internal_compressed
= -1,
234 .purgeable_volatile
= -1,
235 .purgeable_nonvolatile
= -1,
236 .purgeable_volatile_compressed
= -1,
237 .purgeable_nonvolatile_compressed
= -1,
238 .tagged_nofootprint
= -1,
239 .tagged_footprint
= -1,
240 .tagged_nofootprint_compressed
= -1,
241 .tagged_footprint_compressed
= -1,
242 .network_volatile
= -1,
243 .network_nonvolatile
= -1,
244 .network_volatile_compressed
= -1,
245 .network_nonvolatile_compressed
= -1,
246 .media_nofootprint
= -1,
247 .media_footprint
= -1,
248 .media_nofootprint_compressed
= -1,
249 .media_footprint_compressed
= -1,
250 .graphics_nofootprint
= -1,
251 .graphics_footprint
= -1,
252 .graphics_nofootprint_compressed
= -1,
253 .graphics_footprint_compressed
= -1,
254 .neural_nofootprint
= -1,
255 .neural_footprint
= -1,
256 .neural_nofootprint_compressed
= -1,
257 .neural_footprint_compressed
= -1,
258 .platform_idle_wakeups
= -1,
259 .interrupt_wakeups
= -1,
261 .sfi_wait_times
= { 0 /* initialized at runtime */},
262 #endif /* CONFIG_SCHED_SFI */
263 .cpu_time_billed_to_me
= -1,
264 .cpu_time_billed_to_others
= -1,
265 .physical_writes
= -1,
266 .logical_writes
= -1,
267 .logical_writes_to_external
= -1,
268 #if DEBUG || DEVELOPMENT
270 .pages_grabbed_kern
= -1,
271 .pages_grabbed_iopl
= -1,
272 .pages_grabbed_upl
= -1,
275 .frozen_to_swap
= -1,
276 #endif /* CONFIG_FREEZE */
277 .energy_billed_to_me
= -1,
278 .energy_billed_to_others
= -1,
279 #if CONFIG_PHYS_WRITE_ACCT
280 .fs_metadata_writes
= -1,
281 #endif /* CONFIG_PHYS_WRITE_ACCT */
284 /* System sleep state */
285 boolean_t tasks_suspend_state
;
288 void init_task_ledgers(void);
289 void task_footprint_exceeded(int warning
, __unused
const void *param0
, __unused
const void *param1
);
290 void task_wakeups_rate_exceeded(int warning
, __unused
const void *param0
, __unused
const void *param1
);
291 void task_io_rate_exceeded(int warning
, const void *param0
, __unused
const void *param1
);
292 void __attribute__((noinline
)) SENDING_NOTIFICATION__THIS_PROCESS_IS_CAUSING_TOO_MANY_WAKEUPS(void);
293 void __attribute__((noinline
)) PROC_CROSSED_HIGH_WATERMARK__SEND_EXC_RESOURCE_AND_SUSPEND(int max_footprint_mb
, boolean_t is_fatal
);
294 void __attribute__((noinline
)) SENDING_NOTIFICATION__THIS_PROCESS_IS_CAUSING_TOO_MUCH_IO(int flavor
);
296 kern_return_t
task_suspend_internal(task_t
);
297 kern_return_t
task_resume_internal(task_t
);
298 static kern_return_t
task_start_halt_locked(task_t task
, boolean_t should_mark_corpse
);
300 extern kern_return_t
iokit_task_terminate(task_t task
);
301 extern void iokit_task_app_suspended_changed(task_t task
);
303 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
*);
304 extern void bsd_copythreadname(void *dst_uth
, void *src_uth
);
305 extern kern_return_t
thread_resume(thread_t thread
);
307 // Warn tasks when they hit 80% of their memory limit.
308 #define PHYS_FOOTPRINT_WARNING_LEVEL 80
310 #define TASK_WAKEUPS_MONITOR_DEFAULT_LIMIT 150 /* wakeups per second */
311 #define TASK_WAKEUPS_MONITOR_DEFAULT_INTERVAL 300 /* in seconds. */
314 * Level (in terms of percentage of the limit) at which the wakeups monitor triggers telemetry.
316 * (ie when the task's wakeups rate exceeds 70% of the limit, start taking user
317 * stacktraces, aka micro-stackshots)
319 #define TASK_WAKEUPS_MONITOR_DEFAULT_USTACKSHOTS_TRIGGER 70
321 int task_wakeups_monitor_interval
; /* In seconds. Time period over which wakeups rate is observed */
322 int task_wakeups_monitor_rate
; /* In hz. Maximum allowable wakeups per task before EXC_RESOURCE is sent */
324 unsigned int task_wakeups_monitor_ustackshots_trigger_pct
; /* Percentage. Level at which we start gathering telemetry. */
326 int disable_exc_resource
; /* Global override to supress EXC_RESOURCE for resource monitor violations. */
328 ledger_amount_t max_task_footprint
= 0; /* Per-task limit on physical memory consumption in bytes */
329 unsigned int max_task_footprint_warning_level
= 0; /* Per-task limit warning percentage */
330 int max_task_footprint_mb
= 0; /* Per-task limit on physical memory consumption in megabytes */
332 /* I/O Monitor Limits */
333 #define IOMON_DEFAULT_LIMIT (20480ull) /* MB of logical/physical I/O */
334 #define IOMON_DEFAULT_INTERVAL (86400ull) /* in seconds */
336 uint64_t task_iomon_limit_mb
; /* Per-task I/O monitor limit in MBs */
337 uint64_t task_iomon_interval_secs
; /* Per-task I/O monitor interval in secs */
339 #define IO_TELEMETRY_DEFAULT_LIMIT (10ll * 1024ll * 1024ll)
340 int64_t io_telemetry_limit
; /* Threshold to take a microstackshot (0 indicated I/O telemetry is turned off) */
341 int64_t global_logical_writes_count
= 0; /* Global count for logical writes */
342 int64_t global_logical_writes_to_external_count
= 0; /* Global count for logical writes to external storage*/
343 static boolean_t
global_update_logical_writes(int64_t, int64_t*);
345 #define TASK_MAX_THREAD_LIMIT 256
348 int pmap_ledgers_panic
= 1;
349 int pmap_ledgers_panic_leeway
= 3;
350 #endif /* MACH_ASSERT */
352 int task_max
= CONFIG_TASK_MAX
; /* Max number of tasks */
355 int hwm_user_cores
= 0; /* high watermark violations generate user core files */
359 extern uint32_t proc_platform(const struct proc
*);
360 extern uint32_t proc_min_sdk(struct proc
*);
361 extern void proc_getexecutableuuid(void *, unsigned char *, unsigned long);
362 extern int proc_pid(struct proc
*p
);
363 extern int proc_selfpid(void);
364 extern struct proc
*current_proc(void);
365 extern char *proc_name_address(struct proc
*p
);
366 extern uint64_t get_dispatchqueue_offset_from_proc(void *);
367 extern int kevent_proc_copy_uptrs(void *proc
, uint64_t *buf
, uint32_t bufsize
);
368 extern void workq_proc_suspended(struct proc
*p
);
369 extern void workq_proc_resumed(struct proc
*p
);
371 #if CONFIG_MEMORYSTATUS
372 extern void proc_memstat_terminated(struct proc
* p
, boolean_t set
);
373 extern void memorystatus_on_ledger_footprint_exceeded(int warning
, boolean_t memlimit_is_active
, boolean_t memlimit_is_fatal
);
374 extern void memorystatus_log_exception(const int max_footprint_mb
, boolean_t memlimit_is_active
, boolean_t memlimit_is_fatal
);
375 extern boolean_t
memorystatus_allowed_vm_map_fork(task_t task
);
376 extern uint64_t memorystatus_available_memory_internal(struct proc
*p
);
378 #if DEVELOPMENT || DEBUG
379 extern void memorystatus_abort_vm_map_fork(task_t
);
382 #endif /* CONFIG_MEMORYSTATUS */
384 #endif /* MACH_BSD */
386 #if DEVELOPMENT || DEBUG
387 int exc_resource_threads_enabled
;
388 #endif /* DEVELOPMENT || DEBUG */
390 #if (DEVELOPMENT || DEBUG)
391 uint32_t task_exc_guard_default
= TASK_EXC_GUARD_MP_DELIVER
| TASK_EXC_GUARD_MP_ONCE
| TASK_EXC_GUARD_MP_CORPSE
|
392 TASK_EXC_GUARD_VM_DELIVER
| TASK_EXC_GUARD_VM_ONCE
| TASK_EXC_GUARD_VM_CORPSE
;
394 uint32_t task_exc_guard_default
= 0;
399 static void task_hold_locked(task_t task
);
400 static void task_wait_locked(task_t task
, boolean_t until_not_runnable
);
401 static void task_release_locked(task_t task
);
403 static void task_synchronizer_destroy_all(task_t task
);
404 static os_ref_count_t
405 task_add_turnstile_watchports_locked(
407 struct task_watchports
*watchports
,
408 struct task_watchport_elem
**previous_elem_array
,
409 ipc_port_t
*portwatch_ports
,
410 uint32_t portwatch_count
);
412 static os_ref_count_t
413 task_remove_turnstile_watchports_locked(
415 struct task_watchports
*watchports
,
416 ipc_port_t
*port_freelist
);
418 static struct task_watchports
*
419 task_watchports_alloc_init(
425 task_watchports_deallocate(
426 struct task_watchports
*watchports
);
432 boolean_t is_64bit_data
)
434 #if defined(__i386__) || defined(__x86_64__) || defined(__arm64__)
436 #endif /* defined(__i386__) || defined(__x86_64__) || defined(__arm64__) */
441 * Switching to/from 64-bit address spaces
444 if (!task_has_64Bit_addr(task
)) {
445 task_set_64Bit_addr(task
);
448 if (task_has_64Bit_addr(task
)) {
449 task_clear_64Bit_addr(task
);
454 * Switching to/from 64-bit register state.
457 if (task_has_64Bit_data(task
)) {
461 task_set_64Bit_data(task
);
463 if (!task_has_64Bit_data(task
)) {
467 task_clear_64Bit_data(task
);
470 /* FIXME: On x86, the thread save state flavor can diverge from the
471 * task's 64-bit feature flag due to the 32-bit/64-bit register save
472 * state dichotomy. Since we can be pre-empted in this interval,
473 * certain routines may observe the thread as being in an inconsistent
474 * state with respect to its task's 64-bitness.
477 #if defined(__x86_64__) || defined(__arm64__)
478 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
479 thread_mtx_lock(thread
);
480 machine_thread_switch_addrmode(thread
);
481 thread_mtx_unlock(thread
);
483 #endif /* defined(__x86_64__) || defined(__arm64__) */
490 task_get_64bit_data(task_t task
)
492 return task_has_64Bit_data(task
);
496 task_set_platform_binary(
498 boolean_t is_platform
)
502 task
->t_flags
|= TF_PLATFORM
;
503 /* set exc guard default behavior for first-party code */
504 task
->task_exc_guard
= (task_exc_guard_default
& TASK_EXC_GUARD_ALL
);
506 task
->t_flags
&= ~(TF_PLATFORM
);
507 /* set exc guard default behavior for third-party code */
508 task
->task_exc_guard
= ((task_exc_guard_default
>> TASK_EXC_GUARD_THIRD_PARTY_DEFAULT_SHIFT
) & TASK_EXC_GUARD_ALL
);
514 * Set or clear per-task TF_CA_CLIENT_WI flag according to specified argument.
515 * Returns "false" if flag is already set, and "true" in other cases.
518 task_set_ca_client_wi(
520 boolean_t set_or_clear
)
525 /* Tasks can have only one CA_CLIENT work interval */
526 if (task
->t_flags
& TF_CA_CLIENT_WI
) {
529 task
->t_flags
|= TF_CA_CLIENT_WI
;
532 task
->t_flags
&= ~TF_CA_CLIENT_WI
;
541 mach_vm_address_t addr
,
545 task
->all_image_info_addr
= addr
;
546 task
->all_image_info_size
= size
;
551 task_set_mach_header_address(
553 mach_vm_address_t addr
)
556 task
->mach_header_vm_address
= addr
;
561 task_bank_reset(__unused task_t task
)
563 if (task
->bank_context
!= NULL
) {
564 bank_task_destroy(task
);
569 * NOTE: This should only be called when the P_LINTRANSIT
570 * flag is set (the proc_trans lock is held) on the
571 * proc associated with the task.
574 task_bank_init(__unused task_t task
)
576 if (task
->bank_context
!= NULL
) {
577 panic("Task bank init called with non null bank context for task: %p and bank_context: %p", task
, task
->bank_context
);
579 bank_task_initialize(task
);
583 task_set_did_exec_flag(task_t task
)
585 task
->t_procflags
|= TPF_DID_EXEC
;
589 task_clear_exec_copy_flag(task_t task
)
591 task
->t_procflags
&= ~TPF_EXEC_COPY
;
595 task_get_return_wait_event(task_t task
)
597 return (event_t
)&task
->returnwait_inheritor
;
601 task_clear_return_wait(task_t task
, uint32_t flags
)
603 if (flags
& TCRW_CLEAR_INITIAL_WAIT
) {
604 thread_wakeup(task_get_return_wait_event(task
));
607 if (flags
& TCRW_CLEAR_FINAL_WAIT
) {
608 is_write_lock(task
->itk_space
);
610 task
->t_returnwaitflags
&= ~TRW_LRETURNWAIT
;
611 task
->returnwait_inheritor
= NULL
;
613 if (task
->t_returnwaitflags
& TRW_LRETURNWAITER
) {
614 struct turnstile
*turnstile
= turnstile_prepare((uintptr_t) task_get_return_wait_event(task
),
615 NULL
, TURNSTILE_NULL
, TURNSTILE_ULOCK
);
617 waitq_wakeup64_all(&turnstile
->ts_waitq
,
618 CAST_EVENT64_T(task_get_return_wait_event(task
)),
621 turnstile_update_inheritor(turnstile
, NULL
,
622 TURNSTILE_IMMEDIATE_UPDATE
| TURNSTILE_INHERITOR_THREAD
);
623 turnstile_update_inheritor_complete(turnstile
, TURNSTILE_INTERLOCK_HELD
);
625 turnstile_complete((uintptr_t) task_get_return_wait_event(task
), NULL
, NULL
, TURNSTILE_ULOCK
);
627 task
->t_returnwaitflags
&= ~TRW_LRETURNWAITER
;
629 is_write_unlock(task
->itk_space
);
633 void __attribute__((noreturn
))
634 task_wait_to_return(void)
636 task_t task
= current_task();
638 is_write_lock(task
->itk_space
);
640 if (task
->t_returnwaitflags
& TRW_LRETURNWAIT
) {
641 struct turnstile
*turnstile
= turnstile_prepare((uintptr_t) task_get_return_wait_event(task
),
642 NULL
, TURNSTILE_NULL
, TURNSTILE_ULOCK
);
645 task
->t_returnwaitflags
|= TRW_LRETURNWAITER
;
646 turnstile_update_inheritor(turnstile
, task
->returnwait_inheritor
,
647 (TURNSTILE_DELAYED_UPDATE
| TURNSTILE_INHERITOR_THREAD
));
649 waitq_assert_wait64(&turnstile
->ts_waitq
,
650 CAST_EVENT64_T(task_get_return_wait_event(task
)),
651 THREAD_UNINT
, TIMEOUT_WAIT_FOREVER
);
653 is_write_unlock(task
->itk_space
);
655 turnstile_update_inheritor_complete(turnstile
, TURNSTILE_INTERLOCK_NOT_HELD
);
657 thread_block(THREAD_CONTINUE_NULL
);
659 is_write_lock(task
->itk_space
);
660 } while (task
->t_returnwaitflags
& TRW_LRETURNWAIT
);
662 turnstile_complete((uintptr_t) task_get_return_wait_event(task
), NULL
, NULL
, TURNSTILE_ULOCK
);
665 is_write_unlock(task
->itk_space
);
671 * Before jumping to userspace and allowing this process to execute any code,
672 * notify any interested parties.
674 mac_proc_notify_exec_complete(current_proc());
677 thread_bootstrap_return();
680 #ifdef CONFIG_32BIT_TELEMETRY
682 task_consume_32bit_log_flag(task_t task
)
684 if ((task
->t_procflags
& TPF_LOG_32BIT_TELEMETRY
) != 0) {
685 task
->t_procflags
&= ~TPF_LOG_32BIT_TELEMETRY
;
693 task_set_32bit_log_flag(task_t task
)
695 task
->t_procflags
|= TPF_LOG_32BIT_TELEMETRY
;
697 #endif /* CONFIG_32BIT_TELEMETRY */
700 task_is_exec_copy(task_t task
)
702 return task_is_exec_copy_internal(task
);
706 task_did_exec(task_t task
)
708 return task_did_exec_internal(task
);
712 task_is_active(task_t task
)
718 task_is_halting(task_t task
)
720 return task
->halting
;
723 #if TASK_REFERENCE_LEAK_DEBUG
724 #include <kern/btlog.h>
726 static btlog_t
*task_ref_btlog
;
727 #define TASK_REF_OP_INCR 0x1
728 #define TASK_REF_OP_DECR 0x2
730 #define TASK_REF_NUM_RECORDS 100000
731 #define TASK_REF_BTDEPTH 7
734 task_reference_internal(task_t task
)
736 void * bt
[TASK_REF_BTDEPTH
];
740 os_ref_retain(&task
->ref_count
);
742 numsaved
= OSBacktrace(bt
, TASK_REF_BTDEPTH
);
743 btlog_add_entry(task_ref_btlog
, task
, TASK_REF_OP_INCR
,
748 task_deallocate_internal(task_t task
)
750 void * bt
[TASK_REF_BTDEPTH
];
753 numsaved
= OSBacktrace(bt
, TASK_REF_BTDEPTH
);
754 btlog_add_entry(task_ref_btlog
, task
, TASK_REF_OP_DECR
,
757 return os_ref_release(&task
->ref_count
);
760 #endif /* TASK_REFERENCE_LEAK_DEBUG */
766 * Configure per-task memory limit.
767 * The boot-arg is interpreted as Megabytes,
768 * and takes precedence over the device tree.
769 * Setting the boot-arg to 0 disables task limits.
771 if (!PE_parse_boot_argn("max_task_pmem", &max_task_footprint_mb
,
772 sizeof(max_task_footprint_mb
))) {
774 * No limit was found in boot-args, so go look in the device tree.
776 if (!PE_get_default("kern.max_task_pmem", &max_task_footprint_mb
,
777 sizeof(max_task_footprint_mb
))) {
779 * No limit was found in device tree.
781 max_task_footprint_mb
= 0;
785 if (max_task_footprint_mb
!= 0) {
786 #if CONFIG_MEMORYSTATUS
787 if (max_task_footprint_mb
< 50) {
788 printf("Warning: max_task_pmem %d below minimum.\n",
789 max_task_footprint_mb
);
790 max_task_footprint_mb
= 50;
792 printf("Limiting task physical memory footprint to %d MB\n",
793 max_task_footprint_mb
);
795 max_task_footprint
= (ledger_amount_t
)max_task_footprint_mb
* 1024 * 1024; // Convert MB to bytes
798 * Configure the per-task memory limit warning level.
799 * This is computed as a percentage.
801 max_task_footprint_warning_level
= 0;
803 if (max_mem
< 0x40000000) {
805 * On devices with < 1GB of memory:
806 * -- set warnings to 50MB below the per-task limit.
808 if (max_task_footprint_mb
> 50) {
809 max_task_footprint_warning_level
= ((max_task_footprint_mb
- 50) * 100) / max_task_footprint_mb
;
813 * On devices with >= 1GB of memory:
814 * -- set warnings to 100MB below the per-task limit.
816 if (max_task_footprint_mb
> 100) {
817 max_task_footprint_warning_level
= ((max_task_footprint_mb
- 100) * 100) / max_task_footprint_mb
;
822 * Never allow warning level to land below the default.
824 if (max_task_footprint_warning_level
< PHYS_FOOTPRINT_WARNING_LEVEL
) {
825 max_task_footprint_warning_level
= PHYS_FOOTPRINT_WARNING_LEVEL
;
828 printf("Limiting task physical memory warning to %d%%\n", max_task_footprint_warning_level
);
831 printf("Warning: max_task_pmem specified, but jetsam not configured; ignoring.\n");
832 #endif /* CONFIG_MEMORYSTATUS */
835 #if DEVELOPMENT || DEBUG
836 if (!PE_parse_boot_argn("exc_resource_threads",
837 &exc_resource_threads_enabled
,
838 sizeof(exc_resource_threads_enabled
))) {
839 exc_resource_threads_enabled
= 1;
841 PE_parse_boot_argn("task_exc_guard_default",
842 &task_exc_guard_default
,
843 sizeof(task_exc_guard_default
));
844 #endif /* DEVELOPMENT || DEBUG */
847 if (!PE_parse_boot_argn("hwm_user_cores", &hwm_user_cores
,
848 sizeof(hwm_user_cores
))) {
853 proc_init_cpumon_params();
855 if (!PE_parse_boot_argn("task_wakeups_monitor_rate", &task_wakeups_monitor_rate
, sizeof(task_wakeups_monitor_rate
))) {
856 task_wakeups_monitor_rate
= TASK_WAKEUPS_MONITOR_DEFAULT_LIMIT
;
859 if (!PE_parse_boot_argn("task_wakeups_monitor_interval", &task_wakeups_monitor_interval
, sizeof(task_wakeups_monitor_interval
))) {
860 task_wakeups_monitor_interval
= TASK_WAKEUPS_MONITOR_DEFAULT_INTERVAL
;
863 if (!PE_parse_boot_argn("task_wakeups_monitor_ustackshots_trigger_pct", &task_wakeups_monitor_ustackshots_trigger_pct
,
864 sizeof(task_wakeups_monitor_ustackshots_trigger_pct
))) {
865 task_wakeups_monitor_ustackshots_trigger_pct
= TASK_WAKEUPS_MONITOR_DEFAULT_USTACKSHOTS_TRIGGER
;
868 if (!PE_parse_boot_argn("disable_exc_resource", &disable_exc_resource
,
869 sizeof(disable_exc_resource
))) {
870 disable_exc_resource
= 0;
873 if (!PE_parse_boot_argn("task_iomon_limit_mb", &task_iomon_limit_mb
, sizeof(task_iomon_limit_mb
))) {
874 task_iomon_limit_mb
= IOMON_DEFAULT_LIMIT
;
877 if (!PE_parse_boot_argn("task_iomon_interval_secs", &task_iomon_interval_secs
, sizeof(task_iomon_interval_secs
))) {
878 task_iomon_interval_secs
= IOMON_DEFAULT_INTERVAL
;
881 if (!PE_parse_boot_argn("io_telemetry_limit", &io_telemetry_limit
, sizeof(io_telemetry_limit
))) {
882 io_telemetry_limit
= IO_TELEMETRY_DEFAULT_LIMIT
;
886 * If we have coalitions, coalition_init() will call init_task_ledgers() as it
887 * sets up the ledgers for the default coalition. If we don't have coalitions,
888 * then we have to call it now.
890 #if CONFIG_COALITIONS
891 assert(task_ledger_template
);
892 #else /* CONFIG_COALITIONS */
894 #endif /* CONFIG_COALITIONS */
896 #if TASK_REFERENCE_LEAK_DEBUG
897 task_ref_btlog
= btlog_create(TASK_REF_NUM_RECORDS
, TASK_REF_BTDEPTH
, TRUE
/* caller_will_remove_entries_for_element? */);
898 assert(task_ref_btlog
);
902 * Create the kernel task as the first task.
905 if (task_create_internal(TASK_NULL
, NULL
, FALSE
, TRUE
, TRUE
, TF_NONE
, TPF_NONE
, TWF_NONE
, &kernel_task
) != KERN_SUCCESS
)
907 if (task_create_internal(TASK_NULL
, NULL
, FALSE
, FALSE
, FALSE
, TF_NONE
, TPF_NONE
, TWF_NONE
, &kernel_task
) != KERN_SUCCESS
)
909 { panic("task_init\n");}
911 #if defined(HAS_APPLE_PAC)
912 kernel_task
->rop_pid
= ml_default_rop_pid();
913 kernel_task
->jop_pid
= ml_default_jop_pid();
914 // kernel_task never runs at EL0, but machine_thread_state_convert_from/to_user() relies on
915 // disable_user_jop to be false for kernel threads (e.g. in exception delivery on thread_exception_daemon)
916 ml_task_set_disable_user_jop(kernel_task
, FALSE
);
919 vm_map_deallocate(kernel_task
->map
);
920 kernel_task
->map
= kernel_map
;
924 * Create a task running in the kernel address space. It may
925 * have its own map of size mem_size and may have ipc privileges.
929 __unused task_t parent_task
,
930 __unused vm_offset_t map_base
,
931 __unused vm_size_t map_size
,
932 __unused task_t
*child_task
)
934 return KERN_INVALID_ARGUMENT
;
940 __unused ledger_port_array_t ledger_ports
,
941 __unused mach_msg_type_number_t num_ledger_ports
,
942 __unused boolean_t inherit_memory
,
943 __unused task_t
*child_task
) /* OUT */
945 if (parent_task
== TASK_NULL
) {
946 return KERN_INVALID_ARGUMENT
;
950 * No longer supported: too many calls assume that a task has a valid
957 host_security_create_task_token(
958 host_security_t host_security
,
960 __unused security_token_t sec_token
,
961 __unused audit_token_t audit_token
,
962 __unused host_priv_t host_priv
,
963 __unused ledger_port_array_t ledger_ports
,
964 __unused mach_msg_type_number_t num_ledger_ports
,
965 __unused boolean_t inherit_memory
,
966 __unused task_t
*child_task
) /* OUT */
968 if (parent_task
== TASK_NULL
) {
969 return KERN_INVALID_ARGUMENT
;
972 if (host_security
== HOST_NULL
) {
973 return KERN_INVALID_SECURITY
;
977 * No longer supported.
987 * Physical footprint: This is the sum of:
988 * + (internal - alternate_accounting)
989 * + (internal_compressed - alternate_accounting_compressed)
991 * + purgeable_nonvolatile
992 * + purgeable_nonvolatile_compressed
996 * The task's anonymous memory, which on iOS is always resident.
998 * internal_compressed
999 * Amount of this task's internal memory which is held by the compressor.
1000 * Such memory is no longer actually resident for the task [i.e., resident in its pmap],
1001 * and could be either decompressed back into memory, or paged out to storage, depending
1002 * on our implementation.
1005 * IOKit mappings: The total size of all IOKit mappings in this task, regardless of
1006 * clean/dirty or internal/external state].
1008 * alternate_accounting
1009 * The number of internal dirty pages which are part of IOKit mappings. By definition, these pages
1010 * are counted in both internal *and* iokit_mapped, so we must subtract them from the total to avoid
1014 * pages_grabbed counts all page grabs in a task. It is also broken out into three subtypes
1015 * which track UPL, IOPL and Kernel page grabs.
1018 init_task_ledgers(void)
1020 ledger_template_t t
;
1022 assert(task_ledger_template
== NULL
);
1023 assert(kernel_task
== TASK_NULL
);
1026 PE_parse_boot_argn("pmap_ledgers_panic",
1027 &pmap_ledgers_panic
,
1028 sizeof(pmap_ledgers_panic
));
1029 PE_parse_boot_argn("pmap_ledgers_panic_leeway",
1030 &pmap_ledgers_panic_leeway
,
1031 sizeof(pmap_ledgers_panic_leeway
));
1032 #endif /* MACH_ASSERT */
1034 if ((t
= ledger_template_create("Per-task ledger")) == NULL
) {
1035 panic("couldn't create task ledger template");
1038 task_ledgers
.cpu_time
= ledger_entry_add(t
, "cpu_time", "sched", "ns");
1039 task_ledgers
.tkm_private
= ledger_entry_add(t
, "tkm_private",
1040 "physmem", "bytes");
1041 task_ledgers
.tkm_shared
= ledger_entry_add(t
, "tkm_shared", "physmem",
1043 task_ledgers
.phys_mem
= ledger_entry_add(t
, "phys_mem", "physmem",
1045 task_ledgers
.wired_mem
= ledger_entry_add(t
, "wired_mem", "physmem",
1047 task_ledgers
.internal
= ledger_entry_add(t
, "internal", "physmem",
1049 task_ledgers
.iokit_mapped
= ledger_entry_add(t
, "iokit_mapped", "mappings",
1051 task_ledgers
.alternate_accounting
= ledger_entry_add(t
, "alternate_accounting", "physmem",
1053 task_ledgers
.alternate_accounting_compressed
= ledger_entry_add(t
, "alternate_accounting_compressed", "physmem",
1055 task_ledgers
.page_table
= ledger_entry_add(t
, "page_table", "physmem",
1057 task_ledgers
.phys_footprint
= ledger_entry_add(t
, "phys_footprint", "physmem",
1059 task_ledgers
.internal_compressed
= ledger_entry_add(t
, "internal_compressed", "physmem",
1061 task_ledgers
.purgeable_volatile
= ledger_entry_add(t
, "purgeable_volatile", "physmem", "bytes");
1062 task_ledgers
.purgeable_nonvolatile
= ledger_entry_add(t
, "purgeable_nonvolatile", "physmem", "bytes");
1063 task_ledgers
.purgeable_volatile_compressed
= ledger_entry_add(t
, "purgeable_volatile_compress", "physmem", "bytes");
1064 task_ledgers
.purgeable_nonvolatile_compressed
= ledger_entry_add(t
, "purgeable_nonvolatile_compress", "physmem", "bytes");
1065 #if DEBUG || DEVELOPMENT
1066 task_ledgers
.pages_grabbed
= ledger_entry_add(t
, "pages_grabbed", "physmem", "count");
1067 task_ledgers
.pages_grabbed_kern
= ledger_entry_add(t
, "pages_grabbed_kern", "physmem", "count");
1068 task_ledgers
.pages_grabbed_iopl
= ledger_entry_add(t
, "pages_grabbed_iopl", "physmem", "count");
1069 task_ledgers
.pages_grabbed_upl
= ledger_entry_add(t
, "pages_grabbed_upl", "physmem", "count");
1071 task_ledgers
.tagged_nofootprint
= ledger_entry_add(t
, "tagged_nofootprint", "physmem", "bytes");
1072 task_ledgers
.tagged_footprint
= ledger_entry_add(t
, "tagged_footprint", "physmem", "bytes");
1073 task_ledgers
.tagged_nofootprint_compressed
= ledger_entry_add(t
, "tagged_nofootprint_compressed", "physmem", "bytes");
1074 task_ledgers
.tagged_footprint_compressed
= ledger_entry_add(t
, "tagged_footprint_compressed", "physmem", "bytes");
1075 task_ledgers
.network_volatile
= ledger_entry_add(t
, "network_volatile", "physmem", "bytes");
1076 task_ledgers
.network_nonvolatile
= ledger_entry_add(t
, "network_nonvolatile", "physmem", "bytes");
1077 task_ledgers
.network_volatile_compressed
= ledger_entry_add(t
, "network_volatile_compressed", "physmem", "bytes");
1078 task_ledgers
.network_nonvolatile_compressed
= ledger_entry_add(t
, "network_nonvolatile_compressed", "physmem", "bytes");
1079 task_ledgers
.media_nofootprint
= ledger_entry_add(t
, "media_nofootprint", "physmem", "bytes");
1080 task_ledgers
.media_footprint
= ledger_entry_add(t
, "media_footprint", "physmem", "bytes");
1081 task_ledgers
.media_nofootprint_compressed
= ledger_entry_add(t
, "media_nofootprint_compressed", "physmem", "bytes");
1082 task_ledgers
.media_footprint_compressed
= ledger_entry_add(t
, "media_footprint_compressed", "physmem", "bytes");
1083 task_ledgers
.graphics_nofootprint
= ledger_entry_add(t
, "graphics_nofootprint", "physmem", "bytes");
1084 task_ledgers
.graphics_footprint
= ledger_entry_add(t
, "graphics_footprint", "physmem", "bytes");
1085 task_ledgers
.graphics_nofootprint_compressed
= ledger_entry_add(t
, "graphics_nofootprint_compressed", "physmem", "bytes");
1086 task_ledgers
.graphics_footprint_compressed
= ledger_entry_add(t
, "graphics_footprint_compressed", "physmem", "bytes");
1087 task_ledgers
.neural_nofootprint
= ledger_entry_add(t
, "neural_nofootprint", "physmem", "bytes");
1088 task_ledgers
.neural_footprint
= ledger_entry_add(t
, "neural_footprint", "physmem", "bytes");
1089 task_ledgers
.neural_nofootprint_compressed
= ledger_entry_add(t
, "neural_nofootprint_compressed", "physmem", "bytes");
1090 task_ledgers
.neural_footprint_compressed
= ledger_entry_add(t
, "neural_footprint_compressed", "physmem", "bytes");
1093 task_ledgers
.frozen_to_swap
= ledger_entry_add(t
, "frozen_to_swap", "physmem", "bytes");
1094 #endif /* CONFIG_FREEZE */
1096 task_ledgers
.platform_idle_wakeups
= ledger_entry_add(t
, "platform_idle_wakeups", "power",
1098 task_ledgers
.interrupt_wakeups
= ledger_entry_add(t
, "interrupt_wakeups", "power",
1101 #if CONFIG_SCHED_SFI
1102 sfi_class_id_t class_id
, ledger_alias
;
1103 for (class_id
= SFI_CLASS_UNSPECIFIED
; class_id
< MAX_SFI_CLASS_ID
; class_id
++) {
1104 task_ledgers
.sfi_wait_times
[class_id
] = -1;
1107 /* don't account for UNSPECIFIED */
1108 for (class_id
= SFI_CLASS_UNSPECIFIED
+ 1; class_id
< MAX_SFI_CLASS_ID
; class_id
++) {
1109 ledger_alias
= sfi_get_ledger_alias_for_class(class_id
);
1110 if (ledger_alias
!= SFI_CLASS_UNSPECIFIED
) {
1111 /* Check to see if alias has been registered yet */
1112 if (task_ledgers
.sfi_wait_times
[ledger_alias
] != -1) {
1113 task_ledgers
.sfi_wait_times
[class_id
] = task_ledgers
.sfi_wait_times
[ledger_alias
];
1115 /* Otherwise, initialize it first */
1116 task_ledgers
.sfi_wait_times
[class_id
] = task_ledgers
.sfi_wait_times
[ledger_alias
] = sfi_ledger_entry_add(t
, ledger_alias
);
1119 task_ledgers
.sfi_wait_times
[class_id
] = sfi_ledger_entry_add(t
, class_id
);
1122 if (task_ledgers
.sfi_wait_times
[class_id
] < 0) {
1123 panic("couldn't create entries for task ledger template for SFI class 0x%x", class_id
);
1127 assert(task_ledgers
.sfi_wait_times
[MAX_SFI_CLASS_ID
- 1] != -1);
1128 #endif /* CONFIG_SCHED_SFI */
1130 task_ledgers
.cpu_time_billed_to_me
= ledger_entry_add(t
, "cpu_time_billed_to_me", "sched", "ns");
1131 task_ledgers
.cpu_time_billed_to_others
= ledger_entry_add(t
, "cpu_time_billed_to_others", "sched", "ns");
1132 task_ledgers
.physical_writes
= ledger_entry_add(t
, "physical_writes", "res", "bytes");
1133 task_ledgers
.logical_writes
= ledger_entry_add(t
, "logical_writes", "res", "bytes");
1134 task_ledgers
.logical_writes_to_external
= ledger_entry_add(t
, "logical_writes_to_external", "res", "bytes");
1135 #if CONFIG_PHYS_WRITE_ACCT
1136 task_ledgers
.fs_metadata_writes
= ledger_entry_add(t
, "fs_metadata_writes", "res", "bytes");
1137 #endif /* CONFIG_PHYS_WRITE_ACCT */
1138 task_ledgers
.energy_billed_to_me
= ledger_entry_add(t
, "energy_billed_to_me", "power", "nj");
1139 task_ledgers
.energy_billed_to_others
= ledger_entry_add(t
, "energy_billed_to_others", "power", "nj");
1141 if ((task_ledgers
.cpu_time
< 0) ||
1142 (task_ledgers
.tkm_private
< 0) ||
1143 (task_ledgers
.tkm_shared
< 0) ||
1144 (task_ledgers
.phys_mem
< 0) ||
1145 (task_ledgers
.wired_mem
< 0) ||
1146 (task_ledgers
.internal
< 0) ||
1147 (task_ledgers
.iokit_mapped
< 0) ||
1148 (task_ledgers
.alternate_accounting
< 0) ||
1149 (task_ledgers
.alternate_accounting_compressed
< 0) ||
1150 (task_ledgers
.page_table
< 0) ||
1151 (task_ledgers
.phys_footprint
< 0) ||
1152 (task_ledgers
.internal_compressed
< 0) ||
1153 (task_ledgers
.purgeable_volatile
< 0) ||
1154 (task_ledgers
.purgeable_nonvolatile
< 0) ||
1155 (task_ledgers
.purgeable_volatile_compressed
< 0) ||
1156 (task_ledgers
.purgeable_nonvolatile_compressed
< 0) ||
1157 (task_ledgers
.tagged_nofootprint
< 0) ||
1158 (task_ledgers
.tagged_footprint
< 0) ||
1159 (task_ledgers
.tagged_nofootprint_compressed
< 0) ||
1160 (task_ledgers
.tagged_footprint_compressed
< 0) ||
1162 (task_ledgers
.frozen_to_swap
< 0) ||
1163 #endif /* CONFIG_FREEZE */
1164 (task_ledgers
.network_volatile
< 0) ||
1165 (task_ledgers
.network_nonvolatile
< 0) ||
1166 (task_ledgers
.network_volatile_compressed
< 0) ||
1167 (task_ledgers
.network_nonvolatile_compressed
< 0) ||
1168 (task_ledgers
.media_nofootprint
< 0) ||
1169 (task_ledgers
.media_footprint
< 0) ||
1170 (task_ledgers
.media_nofootprint_compressed
< 0) ||
1171 (task_ledgers
.media_footprint_compressed
< 0) ||
1172 (task_ledgers
.graphics_nofootprint
< 0) ||
1173 (task_ledgers
.graphics_footprint
< 0) ||
1174 (task_ledgers
.graphics_nofootprint_compressed
< 0) ||
1175 (task_ledgers
.graphics_footprint_compressed
< 0) ||
1176 (task_ledgers
.neural_nofootprint
< 0) ||
1177 (task_ledgers
.neural_footprint
< 0) ||
1178 (task_ledgers
.neural_nofootprint_compressed
< 0) ||
1179 (task_ledgers
.neural_footprint_compressed
< 0) ||
1180 (task_ledgers
.platform_idle_wakeups
< 0) ||
1181 (task_ledgers
.interrupt_wakeups
< 0) ||
1182 (task_ledgers
.cpu_time_billed_to_me
< 0) || (task_ledgers
.cpu_time_billed_to_others
< 0) ||
1183 (task_ledgers
.physical_writes
< 0) ||
1184 (task_ledgers
.logical_writes
< 0) ||
1185 (task_ledgers
.logical_writes_to_external
< 0) ||
1186 #if CONFIG_PHYS_WRITE_ACCT
1187 (task_ledgers
.fs_metadata_writes
< 0) ||
1188 #endif /* CONFIG_PHYS_WRITE_ACCT */
1189 (task_ledgers
.energy_billed_to_me
< 0) ||
1190 (task_ledgers
.energy_billed_to_others
< 0)
1192 panic("couldn't create entries for task ledger template");
1195 ledger_track_credit_only(t
, task_ledgers
.phys_footprint
);
1196 ledger_track_credit_only(t
, task_ledgers
.page_table
);
1197 ledger_track_credit_only(t
, task_ledgers
.internal
);
1198 ledger_track_credit_only(t
, task_ledgers
.internal_compressed
);
1199 ledger_track_credit_only(t
, task_ledgers
.iokit_mapped
);
1200 ledger_track_credit_only(t
, task_ledgers
.alternate_accounting
);
1201 ledger_track_credit_only(t
, task_ledgers
.alternate_accounting_compressed
);
1202 ledger_track_credit_only(t
, task_ledgers
.purgeable_volatile
);
1203 ledger_track_credit_only(t
, task_ledgers
.purgeable_nonvolatile
);
1204 ledger_track_credit_only(t
, task_ledgers
.purgeable_volatile_compressed
);
1205 ledger_track_credit_only(t
, task_ledgers
.purgeable_nonvolatile_compressed
);
1206 #if DEBUG || DEVELOPMENT
1207 ledger_track_credit_only(t
, task_ledgers
.pages_grabbed
);
1208 ledger_track_credit_only(t
, task_ledgers
.pages_grabbed_kern
);
1209 ledger_track_credit_only(t
, task_ledgers
.pages_grabbed_iopl
);
1210 ledger_track_credit_only(t
, task_ledgers
.pages_grabbed_upl
);
1213 ledger_track_credit_only(t
, task_ledgers
.tagged_nofootprint
);
1214 ledger_track_credit_only(t
, task_ledgers
.tagged_footprint
);
1215 ledger_track_credit_only(t
, task_ledgers
.tagged_nofootprint_compressed
);
1216 ledger_track_credit_only(t
, task_ledgers
.tagged_footprint_compressed
);
1217 ledger_track_credit_only(t
, task_ledgers
.network_volatile
);
1218 ledger_track_credit_only(t
, task_ledgers
.network_nonvolatile
);
1219 ledger_track_credit_only(t
, task_ledgers
.network_volatile_compressed
);
1220 ledger_track_credit_only(t
, task_ledgers
.network_nonvolatile_compressed
);
1221 ledger_track_credit_only(t
, task_ledgers
.media_nofootprint
);
1222 ledger_track_credit_only(t
, task_ledgers
.media_footprint
);
1223 ledger_track_credit_only(t
, task_ledgers
.media_nofootprint_compressed
);
1224 ledger_track_credit_only(t
, task_ledgers
.media_footprint_compressed
);
1225 ledger_track_credit_only(t
, task_ledgers
.graphics_nofootprint
);
1226 ledger_track_credit_only(t
, task_ledgers
.graphics_footprint
);
1227 ledger_track_credit_only(t
, task_ledgers
.graphics_nofootprint_compressed
);
1228 ledger_track_credit_only(t
, task_ledgers
.graphics_footprint_compressed
);
1229 ledger_track_credit_only(t
, task_ledgers
.neural_nofootprint
);
1230 ledger_track_credit_only(t
, task_ledgers
.neural_footprint
);
1231 ledger_track_credit_only(t
, task_ledgers
.neural_nofootprint_compressed
);
1232 ledger_track_credit_only(t
, task_ledgers
.neural_footprint_compressed
);
1234 ledger_track_maximum(t
, task_ledgers
.phys_footprint
, 60);
1236 if (pmap_ledgers_panic
) {
1237 ledger_panic_on_negative(t
, task_ledgers
.phys_footprint
);
1238 ledger_panic_on_negative(t
, task_ledgers
.page_table
);
1239 ledger_panic_on_negative(t
, task_ledgers
.internal
);
1240 ledger_panic_on_negative(t
, task_ledgers
.internal_compressed
);
1241 ledger_panic_on_negative(t
, task_ledgers
.iokit_mapped
);
1242 ledger_panic_on_negative(t
, task_ledgers
.alternate_accounting
);
1243 ledger_panic_on_negative(t
, task_ledgers
.alternate_accounting_compressed
);
1244 ledger_panic_on_negative(t
, task_ledgers
.purgeable_volatile
);
1245 ledger_panic_on_negative(t
, task_ledgers
.purgeable_nonvolatile
);
1246 ledger_panic_on_negative(t
, task_ledgers
.purgeable_volatile_compressed
);
1247 ledger_panic_on_negative(t
, task_ledgers
.purgeable_nonvolatile_compressed
);
1248 #if CONFIG_PHYS_WRITE_ACCT
1249 ledger_panic_on_negative(t
, task_ledgers
.fs_metadata_writes
);
1250 #endif /* CONFIG_PHYS_WRITE_ACCT */
1252 ledger_panic_on_negative(t
, task_ledgers
.tagged_nofootprint
);
1253 ledger_panic_on_negative(t
, task_ledgers
.tagged_footprint
);
1254 ledger_panic_on_negative(t
, task_ledgers
.tagged_nofootprint_compressed
);
1255 ledger_panic_on_negative(t
, task_ledgers
.tagged_footprint_compressed
);
1256 ledger_panic_on_negative(t
, task_ledgers
.network_volatile
);
1257 ledger_panic_on_negative(t
, task_ledgers
.network_nonvolatile
);
1258 ledger_panic_on_negative(t
, task_ledgers
.network_volatile_compressed
);
1259 ledger_panic_on_negative(t
, task_ledgers
.network_nonvolatile_compressed
);
1260 ledger_panic_on_negative(t
, task_ledgers
.media_nofootprint
);
1261 ledger_panic_on_negative(t
, task_ledgers
.media_footprint
);
1262 ledger_panic_on_negative(t
, task_ledgers
.media_nofootprint_compressed
);
1263 ledger_panic_on_negative(t
, task_ledgers
.media_footprint_compressed
);
1264 ledger_panic_on_negative(t
, task_ledgers
.graphics_nofootprint
);
1265 ledger_panic_on_negative(t
, task_ledgers
.graphics_footprint
);
1266 ledger_panic_on_negative(t
, task_ledgers
.graphics_nofootprint_compressed
);
1267 ledger_panic_on_negative(t
, task_ledgers
.graphics_footprint_compressed
);
1268 ledger_panic_on_negative(t
, task_ledgers
.neural_nofootprint
);
1269 ledger_panic_on_negative(t
, task_ledgers
.neural_footprint
);
1270 ledger_panic_on_negative(t
, task_ledgers
.neural_nofootprint_compressed
);
1271 ledger_panic_on_negative(t
, task_ledgers
.neural_footprint_compressed
);
1273 #endif /* MACH_ASSERT */
1275 #if CONFIG_MEMORYSTATUS
1276 ledger_set_callback(t
, task_ledgers
.phys_footprint
, task_footprint_exceeded
, NULL
, NULL
);
1277 #endif /* CONFIG_MEMORYSTATUS */
1279 ledger_set_callback(t
, task_ledgers
.interrupt_wakeups
,
1280 task_wakeups_rate_exceeded
, NULL
, NULL
);
1281 ledger_set_callback(t
, task_ledgers
.physical_writes
, task_io_rate_exceeded
, (void *)FLAVOR_IO_PHYSICAL_WRITES
, NULL
);
1284 ledger_template_complete_secure_alloc(t
);
1285 #else /* XNU_MONITOR */
1286 ledger_template_complete(t
);
1287 #endif /* XNU_MONITOR */
1288 task_ledger_template
= t
;
1291 os_refgrp_decl(static, task_refgrp
, "task", NULL
);
1294 task_create_internal(
1296 coalition_t
*parent_coalitions __unused
,
1297 boolean_t inherit_memory
,
1298 __unused boolean_t is_64bit
,
1299 boolean_t is_64bit_data
,
1301 uint32_t t_procflags
,
1302 uint8_t t_returnwaitflags
,
1303 task_t
*child_task
) /* OUT */
1306 vm_shared_region_t shared_region
;
1307 ledger_t ledger
= NULL
;
1309 new_task
= (task_t
) zalloc(task_zone
);
1311 if (new_task
== TASK_NULL
) {
1312 return KERN_RESOURCE_SHORTAGE
;
1315 /* one ref for just being alive; one for our caller */
1316 os_ref_init_count(&new_task
->ref_count
, &task_refgrp
, 2);
1318 /* allocate with active entries */
1319 assert(task_ledger_template
!= NULL
);
1320 if ((ledger
= ledger_instantiate(task_ledger_template
,
1321 LEDGER_CREATE_ACTIVE_ENTRIES
)) == NULL
) {
1322 zfree(task_zone
, new_task
);
1323 return KERN_RESOURCE_SHORTAGE
;
1326 counter_alloc(&(new_task
->faults
));
1328 #if defined(HAS_APPLE_PAC)
1329 ml_task_set_rop_pid(new_task
, parent_task
, inherit_memory
);
1330 ml_task_set_jop_pid(new_task
, parent_task
, inherit_memory
);
1331 ml_task_set_disable_user_jop(new_task
, inherit_memory
? parent_task
->disable_user_jop
: FALSE
);
1335 new_task
->ledger
= ledger
;
1337 #if defined(CONFIG_SCHED_MULTIQ)
1338 new_task
->sched_group
= sched_group_create();
1341 /* if inherit_memory is true, parent_task MUST not be NULL */
1342 if (!(t_flags
& TF_CORPSE_FORK
) && inherit_memory
) {
1343 new_task
->map
= vm_map_fork(ledger
, parent_task
->map
, 0);
1345 unsigned int pmap_flags
= is_64bit
? PMAP_CREATE_64BIT
: 0;
1346 new_task
->map
= vm_map_create(pmap_create_options(ledger
, 0, pmap_flags
),
1347 (vm_map_offset_t
)(VM_MIN_ADDRESS
),
1348 (vm_map_offset_t
)(VM_MAX_ADDRESS
), TRUE
);
1351 /* Inherit memlock limit from parent */
1353 vm_map_set_user_wire_limit(new_task
->map
, (vm_size_t
)parent_task
->map
->user_wire_limit
);
1356 lck_mtx_init(&new_task
->lock
, &task_lck_grp
, &task_lck_attr
);
1357 queue_init(&new_task
->threads
);
1358 new_task
->suspend_count
= 0;
1359 new_task
->thread_count
= 0;
1360 new_task
->active_thread_count
= 0;
1361 new_task
->user_stop_count
= 0;
1362 new_task
->legacy_stop_count
= 0;
1363 new_task
->active
= TRUE
;
1364 new_task
->halting
= FALSE
;
1365 new_task
->priv_flags
= 0;
1366 new_task
->t_flags
= t_flags
;
1367 new_task
->t_procflags
= t_procflags
;
1368 new_task
->t_returnwaitflags
= t_returnwaitflags
;
1369 new_task
->returnwait_inheritor
= current_thread();
1370 new_task
->importance
= 0;
1371 new_task
->crashed_thread_id
= 0;
1372 new_task
->exec_token
= 0;
1373 new_task
->watchports
= NULL
;
1374 new_task
->restartable_ranges
= NULL
;
1375 new_task
->task_exc_guard
= 0;
1377 new_task
->bank_context
= NULL
;
1380 new_task
->bsd_info
= NULL
;
1381 new_task
->corpse_info
= NULL
;
1382 #endif /* MACH_BSD */
1385 new_task
->crash_label
= NULL
;
1387 new_task
->mach_trap_filter_mask
= NULL
;
1388 new_task
->mach_kobj_filter_mask
= NULL
;
1391 #if CONFIG_MEMORYSTATUS
1392 if (max_task_footprint
!= 0) {
1393 ledger_set_limit(ledger
, task_ledgers
.phys_footprint
, max_task_footprint
, PHYS_FOOTPRINT_WARNING_LEVEL
);
1395 #endif /* CONFIG_MEMORYSTATUS */
1397 if (task_wakeups_monitor_rate
!= 0) {
1398 uint32_t flags
= WAKEMON_ENABLE
| WAKEMON_SET_DEFAULTS
;
1399 int32_t rate
; // Ignored because of WAKEMON_SET_DEFAULTS
1400 task_wakeups_monitor_ctl(new_task
, &flags
, &rate
);
1403 #if CONFIG_IO_ACCOUNTING
1404 uint32_t flags
= IOMON_ENABLE
;
1405 task_io_monitor_ctl(new_task
, &flags
);
1406 #endif /* CONFIG_IO_ACCOUNTING */
1408 machine_task_init(new_task
, parent_task
, inherit_memory
);
1410 new_task
->task_debug
= NULL
;
1412 #if DEVELOPMENT || DEBUG
1413 new_task
->task_unnested
= FALSE
;
1414 new_task
->task_disconnected_count
= 0;
1416 queue_init(&new_task
->semaphore_list
);
1417 new_task
->semaphores_owned
= 0;
1419 ipc_task_init(new_task
, parent_task
);
1421 new_task
->vtimers
= 0;
1423 new_task
->shared_region
= NULL
;
1425 new_task
->affinity_space
= NULL
;
1427 new_task
->t_kpc
= 0;
1429 new_task
->pidsuspended
= FALSE
;
1430 new_task
->frozen
= FALSE
;
1431 new_task
->changing_freeze_state
= FALSE
;
1432 new_task
->rusage_cpu_flags
= 0;
1433 new_task
->rusage_cpu_percentage
= 0;
1434 new_task
->rusage_cpu_interval
= 0;
1435 new_task
->rusage_cpu_deadline
= 0;
1436 new_task
->rusage_cpu_callt
= NULL
;
1438 new_task
->suspends_outstanding
= 0;
1442 new_task
->hv_task_target
= NULL
;
1443 #endif /* HYPERVISOR */
1445 #if CONFIG_TASKWATCH
1446 queue_init(&new_task
->task_watchers
);
1447 new_task
->num_taskwatchers
= 0;
1448 new_task
->watchapplying
= 0;
1449 #endif /* CONFIG_TASKWATCH */
1451 new_task
->mem_notify_reserved
= 0;
1452 new_task
->memlimit_attrs_reserved
= 0;
1454 new_task
->requested_policy
= default_task_requested_policy
;
1455 new_task
->effective_policy
= default_task_effective_policy
;
1457 new_task
->task_shared_region_slide
= -1;
1459 task_importance_init_from_parent(new_task
, parent_task
);
1461 if (parent_task
!= TASK_NULL
) {
1462 new_task
->sec_token
= parent_task
->sec_token
;
1463 new_task
->audit_token
= parent_task
->audit_token
;
1465 /* inherit the parent's shared region */
1466 shared_region
= vm_shared_region_get(parent_task
);
1467 vm_shared_region_set(new_task
, shared_region
);
1469 #if __has_feature(ptrauth_calls)
1470 /* use parent's shared_region_id */
1471 char *shared_region_id
= task_get_vm_shared_region_id_and_jop_pid(parent_task
, NULL
);
1472 if (shared_region_id
!= NULL
) {
1473 shared_region_key_alloc(shared_region_id
, FALSE
, 0); /* get a reference */
1475 task_set_shared_region_id(new_task
, shared_region_id
);
1476 #endif /* __has_feature(ptrauth_calls) */
1478 if (task_has_64Bit_addr(parent_task
)) {
1479 task_set_64Bit_addr(new_task
);
1482 if (task_has_64Bit_data(parent_task
)) {
1483 task_set_64Bit_data(new_task
);
1486 new_task
->all_image_info_addr
= parent_task
->all_image_info_addr
;
1487 new_task
->all_image_info_size
= parent_task
->all_image_info_size
;
1488 new_task
->mach_header_vm_address
= 0;
1490 if (inherit_memory
&& parent_task
->affinity_space
) {
1491 task_affinity_create(parent_task
, new_task
);
1494 new_task
->pset_hint
= parent_task
->pset_hint
= task_choose_pset(parent_task
);
1496 if (parent_task
->t_flags
& TF_NO_SMT
) {
1497 new_task
->t_flags
|= TF_NO_SMT
;
1500 if (parent_task
->t_flags
& TF_TECS
) {
1501 new_task
->t_flags
|= TF_TECS
;
1504 if (parent_task
->t_flags
& TF_FILTER_MSG
) {
1505 new_task
->t_flags
|= TF_FILTER_MSG
;
1508 new_task
->priority
= BASEPRI_DEFAULT
;
1509 new_task
->max_priority
= MAXPRI_USER
;
1511 task_policy_create(new_task
, parent_task
);
1513 new_task
->sec_token
= KERNEL_SECURITY_TOKEN
;
1514 new_task
->audit_token
= KERNEL_AUDIT_TOKEN
;
1517 task_set_64Bit_addr(new_task
);
1521 if (is_64bit_data
) {
1522 task_set_64Bit_data(new_task
);
1525 new_task
->all_image_info_addr
= (mach_vm_address_t
)0;
1526 new_task
->all_image_info_size
= (mach_vm_size_t
)0;
1528 new_task
->pset_hint
= PROCESSOR_SET_NULL
;
1530 if (kernel_task
== TASK_NULL
) {
1531 new_task
->priority
= BASEPRI_KERNEL
;
1532 new_task
->max_priority
= MAXPRI_KERNEL
;
1534 new_task
->priority
= BASEPRI_DEFAULT
;
1535 new_task
->max_priority
= MAXPRI_USER
;
1539 bzero(new_task
->coalition
, sizeof(new_task
->coalition
));
1540 for (int i
= 0; i
< COALITION_NUM_TYPES
; i
++) {
1541 queue_chain_init(new_task
->task_coalition
[i
]);
1544 /* Allocate I/O Statistics */
1545 new_task
->task_io_stats
= kheap_alloc(KHEAP_DATA_BUFFERS
,
1546 sizeof(struct io_stat_info
), Z_WAITOK
| Z_ZERO
);
1547 assert(new_task
->task_io_stats
!= NULL
);
1549 bzero(&(new_task
->cpu_time_eqos_stats
), sizeof(new_task
->cpu_time_eqos_stats
));
1550 bzero(&(new_task
->cpu_time_rqos_stats
), sizeof(new_task
->cpu_time_rqos_stats
));
1552 bzero(&new_task
->extmod_statistics
, sizeof(new_task
->extmod_statistics
));
1554 /* Copy resource acc. info from Parent for Corpe Forked task. */
1555 if (parent_task
!= NULL
&& (t_flags
& TF_CORPSE_FORK
)) {
1556 task_rollup_accounting_info(new_task
, parent_task
);
1558 /* Initialize to zero for standard fork/spawn case */
1559 new_task
->total_user_time
= 0;
1560 new_task
->total_system_time
= 0;
1561 new_task
->total_ptime
= 0;
1562 new_task
->total_runnable_time
= 0;
1563 new_task
->pageins
= 0;
1564 new_task
->cow_faults
= 0;
1565 new_task
->messages_sent
= 0;
1566 new_task
->messages_received
= 0;
1567 new_task
->syscalls_mach
= 0;
1568 new_task
->syscalls_unix
= 0;
1569 new_task
->c_switch
= 0;
1570 new_task
->p_switch
= 0;
1571 new_task
->ps_switch
= 0;
1572 new_task
->decompressions
= 0;
1573 new_task
->low_mem_notified_warn
= 0;
1574 new_task
->low_mem_notified_critical
= 0;
1575 new_task
->purged_memory_warn
= 0;
1576 new_task
->purged_memory_critical
= 0;
1577 new_task
->low_mem_privileged_listener
= 0;
1578 new_task
->memlimit_is_active
= 0;
1579 new_task
->memlimit_is_fatal
= 0;
1580 new_task
->memlimit_active_exc_resource
= 0;
1581 new_task
->memlimit_inactive_exc_resource
= 0;
1582 new_task
->task_timer_wakeups_bin_1
= 0;
1583 new_task
->task_timer_wakeups_bin_2
= 0;
1584 new_task
->task_gpu_ns
= 0;
1585 new_task
->task_writes_counters_internal
.task_immediate_writes
= 0;
1586 new_task
->task_writes_counters_internal
.task_deferred_writes
= 0;
1587 new_task
->task_writes_counters_internal
.task_invalidated_writes
= 0;
1588 new_task
->task_writes_counters_internal
.task_metadata_writes
= 0;
1589 new_task
->task_writes_counters_external
.task_immediate_writes
= 0;
1590 new_task
->task_writes_counters_external
.task_deferred_writes
= 0;
1591 new_task
->task_writes_counters_external
.task_invalidated_writes
= 0;
1592 new_task
->task_writes_counters_external
.task_metadata_writes
= 0;
1593 #if CONFIG_PHYS_WRITE_ACCT
1594 new_task
->task_fs_metadata_writes
= 0;
1595 #endif /* CONFIG_PHYS_WRITE_ACCT */
1597 new_task
->task_energy
= 0;
1599 memset(&new_task
->task_monotonic
, 0, sizeof(new_task
->task_monotonic
));
1600 #endif /* MONOTONIC */
1604 #if CONFIG_COALITIONS
1605 if (!(t_flags
& TF_CORPSE_FORK
)) {
1606 /* TODO: there is no graceful failure path here... */
1607 if (parent_coalitions
&& parent_coalitions
[COALITION_TYPE_RESOURCE
]) {
1608 coalitions_adopt_task(parent_coalitions
, new_task
);
1609 } else if (parent_task
&& parent_task
->coalition
[COALITION_TYPE_RESOURCE
]) {
1611 * all tasks at least have a resource coalition, so
1612 * if the parent has one then inherit all coalitions
1613 * the parent is a part of
1615 coalitions_adopt_task(parent_task
->coalition
, new_task
);
1617 /* TODO: assert that new_task will be PID 1 (launchd) */
1618 coalitions_adopt_init_task(new_task
);
1621 * on exec, we need to transfer the coalition roles from the
1622 * parent task to the exec copy task.
1624 if (parent_task
&& (t_procflags
& TPF_EXEC_COPY
)) {
1625 int coal_roles
[COALITION_NUM_TYPES
];
1626 task_coalition_roles(parent_task
, coal_roles
);
1627 (void)coalitions_set_roles(new_task
->coalition
, new_task
, coal_roles
);
1630 coalitions_adopt_corpse_task(new_task
);
1633 if (new_task
->coalition
[COALITION_TYPE_RESOURCE
] == COALITION_NULL
) {
1634 panic("created task is not a member of a resource coalition");
1636 #endif /* CONFIG_COALITIONS */
1638 new_task
->dispatchqueue_offset
= 0;
1639 if (parent_task
!= NULL
) {
1640 new_task
->dispatchqueue_offset
= parent_task
->dispatchqueue_offset
;
1643 new_task
->task_can_transfer_memory_ownership
= FALSE
;
1644 new_task
->task_volatile_objects
= 0;
1645 new_task
->task_nonvolatile_objects
= 0;
1646 new_task
->task_objects_disowning
= FALSE
;
1647 new_task
->task_objects_disowned
= FALSE
;
1648 new_task
->task_owned_objects
= 0;
1649 queue_init(&new_task
->task_objq
);
1652 queue_init(&new_task
->task_frozen_cseg_q
);
1653 #endif /* CONFIG_FREEZE */
1655 task_objq_lock_init(new_task
);
1658 new_task
->task_legacy_footprint
= FALSE
;
1659 new_task
->task_extra_footprint_limit
= FALSE
;
1660 new_task
->task_ios13extended_footprint_limit
= FALSE
;
1661 #endif /* __arm64__ */
1662 new_task
->task_region_footprint
= FALSE
;
1663 new_task
->task_has_crossed_thread_limit
= FALSE
;
1664 new_task
->task_thread_limit
= 0;
1665 #if CONFIG_SECLUDED_MEMORY
1666 new_task
->task_can_use_secluded_mem
= FALSE
;
1667 new_task
->task_could_use_secluded_mem
= FALSE
;
1668 new_task
->task_could_also_use_secluded_mem
= FALSE
;
1669 new_task
->task_suppressed_secluded
= FALSE
;
1670 #endif /* CONFIG_SECLUDED_MEMORY */
1673 * t_flags is set up above. But since we don't
1674 * support darkwake mode being set that way
1675 * currently, we clear it out here explicitly.
1677 new_task
->t_flags
&= ~(TF_DARKWAKE_MODE
);
1679 queue_init(&new_task
->io_user_clients
);
1680 new_task
->loadTag
= 0;
1682 ipc_task_enable(new_task
);
1684 lck_mtx_lock(&tasks_threads_lock
);
1685 queue_enter(&tasks
, new_task
, task_t
, tasks
);
1687 if (tasks_suspend_state
) {
1688 task_suspend_internal(new_task
);
1690 lck_mtx_unlock(&tasks_threads_lock
);
1692 *child_task
= new_task
;
1693 return KERN_SUCCESS
;
1697 * task_rollup_accounting_info
1699 * Roll up accounting stats. Used to rollup stats
1700 * for exec copy task and corpse fork.
1703 task_rollup_accounting_info(task_t to_task
, task_t from_task
)
1705 assert(from_task
!= to_task
);
1707 to_task
->total_user_time
= from_task
->total_user_time
;
1708 to_task
->total_system_time
= from_task
->total_system_time
;
1709 to_task
->total_ptime
= from_task
->total_ptime
;
1710 to_task
->total_runnable_time
= from_task
->total_runnable_time
;
1711 counter_add(&to_task
->faults
, counter_load(&from_task
->faults
));
1712 to_task
->pageins
= from_task
->pageins
;
1713 to_task
->cow_faults
= from_task
->cow_faults
;
1714 to_task
->decompressions
= from_task
->decompressions
;
1715 to_task
->messages_sent
= from_task
->messages_sent
;
1716 to_task
->messages_received
= from_task
->messages_received
;
1717 to_task
->syscalls_mach
= from_task
->syscalls_mach
;
1718 to_task
->syscalls_unix
= from_task
->syscalls_unix
;
1719 to_task
->c_switch
= from_task
->c_switch
;
1720 to_task
->p_switch
= from_task
->p_switch
;
1721 to_task
->ps_switch
= from_task
->ps_switch
;
1722 to_task
->extmod_statistics
= from_task
->extmod_statistics
;
1723 to_task
->low_mem_notified_warn
= from_task
->low_mem_notified_warn
;
1724 to_task
->low_mem_notified_critical
= from_task
->low_mem_notified_critical
;
1725 to_task
->purged_memory_warn
= from_task
->purged_memory_warn
;
1726 to_task
->purged_memory_critical
= from_task
->purged_memory_critical
;
1727 to_task
->low_mem_privileged_listener
= from_task
->low_mem_privileged_listener
;
1728 *to_task
->task_io_stats
= *from_task
->task_io_stats
;
1729 to_task
->cpu_time_eqos_stats
= from_task
->cpu_time_eqos_stats
;
1730 to_task
->cpu_time_rqos_stats
= from_task
->cpu_time_rqos_stats
;
1731 to_task
->task_timer_wakeups_bin_1
= from_task
->task_timer_wakeups_bin_1
;
1732 to_task
->task_timer_wakeups_bin_2
= from_task
->task_timer_wakeups_bin_2
;
1733 to_task
->task_gpu_ns
= from_task
->task_gpu_ns
;
1734 to_task
->task_writes_counters_internal
.task_immediate_writes
= from_task
->task_writes_counters_internal
.task_immediate_writes
;
1735 to_task
->task_writes_counters_internal
.task_deferred_writes
= from_task
->task_writes_counters_internal
.task_deferred_writes
;
1736 to_task
->task_writes_counters_internal
.task_invalidated_writes
= from_task
->task_writes_counters_internal
.task_invalidated_writes
;
1737 to_task
->task_writes_counters_internal
.task_metadata_writes
= from_task
->task_writes_counters_internal
.task_metadata_writes
;
1738 to_task
->task_writes_counters_external
.task_immediate_writes
= from_task
->task_writes_counters_external
.task_immediate_writes
;
1739 to_task
->task_writes_counters_external
.task_deferred_writes
= from_task
->task_writes_counters_external
.task_deferred_writes
;
1740 to_task
->task_writes_counters_external
.task_invalidated_writes
= from_task
->task_writes_counters_external
.task_invalidated_writes
;
1741 to_task
->task_writes_counters_external
.task_metadata_writes
= from_task
->task_writes_counters_external
.task_metadata_writes
;
1742 #if CONFIG_PHYS_WRITE_ACCT
1743 to_task
->task_fs_metadata_writes
= from_task
->task_fs_metadata_writes
;
1744 #endif /* CONFIG_PHYS_WRITE_ACCT */
1745 to_task
->task_energy
= from_task
->task_energy
;
1747 /* Skip ledger roll up for memory accounting entries */
1748 ledger_rollup_entry(to_task
->ledger
, from_task
->ledger
, task_ledgers
.cpu_time
);
1749 ledger_rollup_entry(to_task
->ledger
, from_task
->ledger
, task_ledgers
.platform_idle_wakeups
);
1750 ledger_rollup_entry(to_task
->ledger
, from_task
->ledger
, task_ledgers
.interrupt_wakeups
);
1751 #if CONFIG_SCHED_SFI
1752 for (sfi_class_id_t class_id
= SFI_CLASS_UNSPECIFIED
; class_id
< MAX_SFI_CLASS_ID
; class_id
++) {
1753 ledger_rollup_entry(to_task
->ledger
, from_task
->ledger
, task_ledgers
.sfi_wait_times
[class_id
]);
1756 ledger_rollup_entry(to_task
->ledger
, from_task
->ledger
, task_ledgers
.cpu_time_billed_to_me
);
1757 ledger_rollup_entry(to_task
->ledger
, from_task
->ledger
, task_ledgers
.cpu_time_billed_to_others
);
1758 ledger_rollup_entry(to_task
->ledger
, from_task
->ledger
, task_ledgers
.physical_writes
);
1759 ledger_rollup_entry(to_task
->ledger
, from_task
->ledger
, task_ledgers
.logical_writes
);
1760 ledger_rollup_entry(to_task
->ledger
, from_task
->ledger
, task_ledgers
.energy_billed_to_me
);
1761 ledger_rollup_entry(to_task
->ledger
, from_task
->ledger
, task_ledgers
.energy_billed_to_others
);
1764 int task_dropped_imp_count
= 0;
1769 * Drop a reference on a task.
1775 ledger_amount_t credit
, debit
, interrupt_wakeups
, platform_idle_wakeups
;
1776 os_ref_count_t refs
;
1778 if (task
== TASK_NULL
) {
1782 refs
= task_deallocate_internal(task
);
1784 #if IMPORTANCE_INHERITANCE
1787 * If last ref potentially comes from the task's importance,
1788 * disconnect it. But more task refs may be added before
1789 * that completes, so wait for the reference to go to zero
1790 * naturally (it may happen on a recursive task_deallocate()
1791 * from the ipc_importance_disconnect_task() call).
1793 if (IIT_NULL
!= task
->task_imp_base
) {
1794 ipc_importance_disconnect_task(task
);
1798 #endif /* IMPORTANCE_INHERITANCE */
1805 * The task should be dead at this point. Ensure other resources
1806 * like threads, are gone before we trash the world.
1808 assert(queue_empty(&task
->threads
));
1809 assert(task
->bsd_info
== NULL
);
1810 assert(!is_active(task
->itk_space
));
1811 assert(!task
->active
);
1812 assert(task
->active_thread_count
== 0);
1814 lck_mtx_lock(&tasks_threads_lock
);
1815 assert(terminated_tasks_count
> 0);
1816 queue_remove(&terminated_tasks
, task
, task_t
, tasks
);
1817 terminated_tasks_count
--;
1818 lck_mtx_unlock(&tasks_threads_lock
);
1821 * remove the reference on bank context
1823 task_bank_reset(task
);
1825 if (task
->task_io_stats
) {
1826 kheap_free(KHEAP_DATA_BUFFERS
, task
->task_io_stats
,
1827 sizeof(struct io_stat_info
));
1831 * Give the machine dependent code a chance
1832 * to perform cleanup before ripping apart
1835 machine_task_terminate(task
);
1837 ipc_task_terminate(task
);
1839 /* let iokit know */
1840 iokit_task_terminate(task
);
1842 if (task
->affinity_space
) {
1843 task_affinity_deallocate(task
);
1847 if (task
->ledger
!= NULL
&&
1848 task
->map
!= NULL
&&
1849 task
->map
->pmap
!= NULL
&&
1850 task
->map
->pmap
->ledger
!= NULL
) {
1851 assert(task
->ledger
== task
->map
->pmap
->ledger
);
1853 #endif /* MACH_ASSERT */
1855 vm_owned_objects_disown(task
);
1856 assert(task
->task_objects_disowned
);
1857 if (task
->task_volatile_objects
!= 0 ||
1858 task
->task_nonvolatile_objects
!= 0 ||
1859 task
->task_owned_objects
!= 0) {
1860 panic("task_deallocate(%p): "
1861 "volatile_objects=%d nonvolatile_objects=%d owned=%d\n",
1863 task
->task_volatile_objects
,
1864 task
->task_nonvolatile_objects
,
1865 task
->task_owned_objects
);
1868 vm_map_deallocate(task
->map
);
1869 is_release(task
->itk_space
);
1870 if (task
->restartable_ranges
) {
1871 restartable_ranges_release(task
->restartable_ranges
);
1874 ledger_get_entries(task
->ledger
, task_ledgers
.interrupt_wakeups
,
1875 &interrupt_wakeups
, &debit
);
1876 ledger_get_entries(task
->ledger
, task_ledgers
.platform_idle_wakeups
,
1877 &platform_idle_wakeups
, &debit
);
1879 #if defined(CONFIG_SCHED_MULTIQ)
1880 sched_group_destroy(task
->sched_group
);
1883 /* Accumulate statistics for dead tasks */
1884 lck_spin_lock(&dead_task_statistics_lock
);
1885 dead_task_statistics
.total_user_time
+= task
->total_user_time
;
1886 dead_task_statistics
.total_system_time
+= task
->total_system_time
;
1888 dead_task_statistics
.task_interrupt_wakeups
+= interrupt_wakeups
;
1889 dead_task_statistics
.task_platform_idle_wakeups
+= platform_idle_wakeups
;
1891 dead_task_statistics
.task_timer_wakeups_bin_1
+= task
->task_timer_wakeups_bin_1
;
1892 dead_task_statistics
.task_timer_wakeups_bin_2
+= task
->task_timer_wakeups_bin_2
;
1893 dead_task_statistics
.total_ptime
+= task
->total_ptime
;
1894 dead_task_statistics
.total_pset_switches
+= task
->ps_switch
;
1895 dead_task_statistics
.task_gpu_ns
+= task
->task_gpu_ns
;
1896 dead_task_statistics
.task_energy
+= task
->task_energy
;
1898 lck_spin_unlock(&dead_task_statistics_lock
);
1899 lck_mtx_destroy(&task
->lock
, &task_lck_grp
);
1901 if (!ledger_get_entries(task
->ledger
, task_ledgers
.tkm_private
, &credit
,
1903 OSAddAtomic64(credit
, (int64_t *)&tasks_tkm_private
.alloc
);
1904 OSAddAtomic64(debit
, (int64_t *)&tasks_tkm_private
.free
);
1906 if (!ledger_get_entries(task
->ledger
, task_ledgers
.tkm_shared
, &credit
,
1908 OSAddAtomic64(credit
, (int64_t *)&tasks_tkm_shared
.alloc
);
1909 OSAddAtomic64(debit
, (int64_t *)&tasks_tkm_shared
.free
);
1911 ledger_dereference(task
->ledger
);
1913 #if TASK_REFERENCE_LEAK_DEBUG
1914 btlog_remove_entries_for_element(task_ref_btlog
, task
);
1917 counter_free(&task
->faults
);
1919 #if CONFIG_COALITIONS
1920 task_release_coalitions(task
);
1921 #endif /* CONFIG_COALITIONS */
1923 bzero(task
->coalition
, sizeof(task
->coalition
));
1926 /* clean up collected information since last reference to task is gone */
1927 if (task
->corpse_info
) {
1928 void *corpse_info_kernel
= kcdata_memory_get_begin_addr(task
->corpse_info
);
1929 task_crashinfo_destroy(task
->corpse_info
);
1930 task
->corpse_info
= NULL
;
1931 if (corpse_info_kernel
) {
1932 kheap_free(KHEAP_DATA_BUFFERS
, corpse_info_kernel
,
1933 CORPSEINFO_ALLOCATION_SIZE
);
1939 if (task
->crash_label
) {
1940 mac_exc_free_label(task
->crash_label
);
1941 task
->crash_label
= NULL
;
1945 assert(queue_empty(&task
->task_objq
));
1946 task_objq_lock_destroy(task
);
1948 zfree(task_zone
, task
);
1952 * task_name_deallocate:
1954 * Drop a reference on a task name.
1957 task_name_deallocate(
1958 task_name_t task_name
)
1960 return task_deallocate((task_t
)task_name
);
1964 * task_policy_set_deallocate:
1966 * Drop a reference on a task type.
1969 task_policy_set_deallocate(task_policy_set_t task_policy_set
)
1971 return task_deallocate((task_t
)task_policy_set
);
1975 * task_policy_get_deallocate:
1977 * Drop a reference on a task type.
1980 task_policy_get_deallocate(task_policy_get_t task_policy_get
)
1982 return task_deallocate((task_t
)task_policy_get
);
1986 * task_inspect_deallocate:
1988 * Drop a task inspection reference.
1991 task_inspect_deallocate(
1992 task_inspect_t task_inspect
)
1994 return task_deallocate((task_t
)task_inspect
);
1998 * task_read_deallocate:
2000 * Drop a reference on task read port.
2003 task_read_deallocate(
2004 task_read_t task_read
)
2006 return task_deallocate((task_t
)task_read
);
2010 * task_suspension_token_deallocate:
2012 * Drop a reference on a task suspension token.
2015 task_suspension_token_deallocate(
2016 task_suspension_token_t token
)
2018 return task_deallocate((task_t
)token
);
2023 * task_collect_crash_info:
2025 * collect crash info from bsd and mach based data
2028 task_collect_crash_info(
2031 struct label
*crash_label
,
2035 kern_return_t kr
= KERN_SUCCESS
;
2037 kcdata_descriptor_t crash_data
= NULL
;
2038 kcdata_descriptor_t crash_data_release
= NULL
;
2039 mach_msg_type_number_t size
= CORPSEINFO_ALLOCATION_SIZE
;
2040 mach_vm_offset_t crash_data_ptr
= 0;
2041 void *crash_data_kernel
= NULL
;
2042 void *crash_data_kernel_release
= NULL
;
2044 struct label
*label
, *free_label
;
2047 if (!corpses_enabled()) {
2048 return KERN_NOT_SUPPORTED
;
2052 free_label
= label
= mac_exc_create_label();
2057 assert(is_corpse_fork
|| task
->bsd_info
!= NULL
);
2058 if (task
->corpse_info
== NULL
&& (is_corpse_fork
|| task
->bsd_info
!= NULL
)) {
2060 /* Set the crash label, used by the exception delivery mac hook */
2061 free_label
= task
->crash_label
; // Most likely NULL.
2062 task
->crash_label
= label
;
2063 mac_exc_update_task_crash_label(task
, crash_label
);
2067 crash_data_kernel
= kheap_alloc(KHEAP_DATA_BUFFERS
,
2068 CORPSEINFO_ALLOCATION_SIZE
, Z_WAITOK
| Z_ZERO
);
2069 if (crash_data_kernel
== NULL
) {
2070 kr
= KERN_RESOURCE_SHORTAGE
;
2073 crash_data_ptr
= (mach_vm_offset_t
) crash_data_kernel
;
2075 /* Do not get a corpse ref for corpse fork */
2076 crash_data
= task_crashinfo_alloc_init((mach_vm_address_t
)crash_data_ptr
, size
,
2077 is_corpse_fork
? 0 : CORPSE_CRASHINFO_HAS_REF
,
2078 KCFLAG_USE_MEMCOPY
);
2081 crash_data_release
= task
->corpse_info
;
2082 crash_data_kernel_release
= kcdata_memory_get_begin_addr(crash_data_release
);
2083 task
->corpse_info
= crash_data
;
2088 kheap_free(KHEAP_DATA_BUFFERS
, crash_data_kernel
,
2089 CORPSEINFO_ALLOCATION_SIZE
);
2093 if (crash_data_release
!= NULL
) {
2094 task_crashinfo_destroy(crash_data_release
);
2096 if (crash_data_kernel_release
!= NULL
) {
2097 kheap_free(KHEAP_DATA_BUFFERS
, crash_data_kernel_release
,
2098 CORPSEINFO_ALLOCATION_SIZE
);
2106 if (free_label
!= NULL
) {
2107 mac_exc_free_label(free_label
);
2114 * task_deliver_crash_notification:
2116 * Makes outcall to registered host port for a corpse.
2119 task_deliver_crash_notification(
2122 exception_type_t etype
,
2123 mach_exception_subcode_t subcode
)
2125 kcdata_descriptor_t crash_info
= task
->corpse_info
;
2126 thread_t th_iter
= NULL
;
2127 kern_return_t kr
= KERN_SUCCESS
;
2128 wait_interrupt_t wsave
;
2129 mach_exception_data_type_t code
[EXCEPTION_CODE_MAX
];
2130 ipc_port_t task_port
, old_notify
;
2132 if (crash_info
== NULL
) {
2133 return KERN_FAILURE
;
2137 if (task_is_a_corpse_fork(task
)) {
2138 /* Populate code with EXC_{RESOURCE,GUARD} for corpse fork */
2142 /* Populate code with EXC_CRASH for corpses */
2143 code
[0] = EXC_CRASH
;
2145 /* Update the code[1] if the boot-arg corpse_for_fatal_memkill is set */
2146 if (corpse_for_fatal_memkill
) {
2151 queue_iterate(&task
->threads
, th_iter
, thread_t
, task_threads
)
2153 if (th_iter
->corpse_dup
== FALSE
) {
2154 ipc_thread_reset(th_iter
);
2159 /* Arm the no-sender notification for taskport */
2160 task_reference(task
);
2161 task_port
= convert_task_to_port(task
);
2163 require_ip_active(task_port
);
2164 ipc_port_nsrequest(task_port
, task_port
->ip_mscount
, ipc_port_make_sonce_locked(task_port
), &old_notify
);
2166 assert(IP_NULL
== old_notify
);
2168 wsave
= thread_interrupt_level(THREAD_UNINT
);
2169 kr
= exception_triage_thread(EXC_CORPSE_NOTIFY
, code
, EXCEPTION_CODE_MAX
, thread
);
2170 if (kr
!= KERN_SUCCESS
) {
2171 printf("Failed to send exception EXC_CORPSE_NOTIFY. error code: %d for pid %d\n", kr
, task_pid(task
));
2174 (void)thread_interrupt_level(wsave
);
2177 * Drop the send right on task port, will fire the
2178 * no-sender notification if exception deliver failed.
2180 ipc_port_release_send(task_port
);
2187 * Terminate the specified task. See comments on thread_terminate
2188 * (kern/thread.c) about problems with terminating the "current task."
2195 if (task
== TASK_NULL
) {
2196 return KERN_INVALID_ARGUMENT
;
2199 if (task
->bsd_info
) {
2200 return KERN_FAILURE
;
2203 return task_terminate_internal(task
);
2207 extern int proc_pid(struct proc
*);
2208 extern void proc_name_kdp(task_t t
, char *buf
, int size
);
2209 #endif /* MACH_ASSERT */
2211 #define VM_MAP_PARTIAL_REAP 0x54 /* 0x150 */
2213 __unused
task_partial_reap(task_t task
, __unused
int pid
)
2215 unsigned int reclaimed_resident
= 0;
2216 unsigned int reclaimed_compressed
= 0;
2217 uint64_t task_page_count
;
2219 task_page_count
= (get_task_phys_footprint(task
) / PAGE_SIZE_64
);
2221 KERNEL_DEBUG_CONSTANT((MACHDBG_CODE(DBG_MACH_VM
, VM_MAP_PARTIAL_REAP
) | DBG_FUNC_START
),
2222 pid
, task_page_count
, 0, 0, 0);
2224 vm_map_partial_reap(task
->map
, &reclaimed_resident
, &reclaimed_compressed
);
2226 KERNEL_DEBUG_CONSTANT((MACHDBG_CODE(DBG_MACH_VM
, VM_MAP_PARTIAL_REAP
) | DBG_FUNC_END
),
2227 pid
, reclaimed_resident
, reclaimed_compressed
, 0, 0);
2231 task_mark_corpse(task_t task
)
2233 kern_return_t kr
= KERN_SUCCESS
;
2234 thread_t self_thread
;
2236 wait_interrupt_t wsave
;
2238 struct label
*crash_label
= NULL
;
2241 assert(task
!= kernel_task
);
2242 assert(task
== current_task());
2243 assert(!task_is_a_corpse(task
));
2246 crash_label
= mac_exc_create_label_for_proc((struct proc
*)task
->bsd_info
);
2249 kr
= task_collect_crash_info(task
,
2254 if (kr
!= KERN_SUCCESS
) {
2258 self_thread
= current_thread();
2260 wsave
= thread_interrupt_level(THREAD_UNINT
);
2263 task_set_corpse_pending_report(task
);
2264 task_set_corpse(task
);
2265 task
->crashed_thread_id
= thread_tid(self_thread
);
2267 kr
= task_start_halt_locked(task
, TRUE
);
2268 assert(kr
== KERN_SUCCESS
);
2270 ipc_task_reset(task
);
2271 /* Remove the naked send right for task port, needed to arm no sender notification */
2272 task_set_special_port_internal(task
, TASK_KERNEL_PORT
, IPC_PORT_NULL
);
2273 ipc_task_enable(task
);
2276 /* terminate the ipc space */
2277 ipc_space_terminate(task
->itk_space
);
2279 /* Add it to global corpse task list */
2280 task_add_to_corpse_task_list(task
);
2282 task_start_halt(task
);
2283 thread_terminate_internal(self_thread
, TH_TERMINATE_OPTION_NONE
);
2285 (void) thread_interrupt_level(wsave
);
2286 assert(task
->halting
== TRUE
);
2290 mac_exc_free_label(crash_label
);
2298 * Clears the corpse pending bit on task.
2299 * Removes inspection bit on the threads.
2302 task_clear_corpse(task_t task
)
2304 thread_t th_iter
= NULL
;
2307 queue_iterate(&task
->threads
, th_iter
, thread_t
, task_threads
)
2309 thread_mtx_lock(th_iter
);
2310 th_iter
->inspection
= FALSE
;
2311 ipc_thread_disable(th_iter
);
2312 thread_mtx_unlock(th_iter
);
2315 thread_terminate_crashed_threads();
2316 /* remove the pending corpse report flag */
2317 task_clear_corpse_pending_report(task
);
2325 * Called whenever the Mach port system detects no-senders on
2326 * the task port of a corpse.
2327 * Each notification that comes in should terminate the task (corpse).
2330 task_port_notify(mach_msg_header_t
*msg
)
2332 mach_no_senders_notification_t
*notification
= (void *)msg
;
2333 ipc_port_t port
= notification
->not_header
.msgh_remote_port
;
2336 require_ip_active(port
);
2337 assert(IKOT_TASK_CONTROL
== ip_kotype(port
));
2338 task
= (task_t
) ip_get_kobject(port
);
2340 assert(task_is_a_corpse(task
));
2342 /* Remove the task from global corpse task list */
2343 task_remove_from_corpse_task_list(task
);
2345 task_clear_corpse(task
);
2346 task_terminate_internal(task
);
2350 * task_port_with_flavor_notify
2352 * Called whenever the Mach port system detects no-senders on
2353 * the task inspect or read port. These ports are allocated lazily and
2354 * should be deallocated here when there are no senders remaining.
2357 task_port_with_flavor_notify(mach_msg_header_t
*msg
)
2359 mach_no_senders_notification_t
*notification
= (void *)msg
;
2360 ipc_port_t port
= notification
->not_header
.msgh_remote_port
;
2362 mach_task_flavor_t flavor
;
2363 ipc_kobject_type_t kotype
;
2366 if (port
->ip_srights
> 0) {
2370 task
= (task_t
)ipc_kobject_get(port
);
2371 kotype
= ip_kotype(port
);
2372 if (task
!= TASK_NULL
) {
2373 assert((IKOT_TASK_READ
== kotype
) || (IKOT_TASK_INSPECT
== kotype
));
2374 task_reference_internal(task
);
2378 if (task
== TASK_NULL
) {
2379 /* The task is exiting or disabled; it will eventually deallocate the port */
2383 if (kotype
== IKOT_TASK_READ
) {
2384 flavor
= TASK_FLAVOR_READ
;
2386 flavor
= TASK_FLAVOR_INSPECT
;
2392 * If the port is no longer active, then ipc_task_terminate() ran
2393 * and destroyed the kobject already. Just deallocate the task
2394 * ref we took and go away.
2396 * It is also possible that several nsrequests are in flight,
2397 * only one shall NULL-out the port entry, and this is the one
2398 * that gets to dealloc the port.
2400 * Check for a stale no-senders notification. A call to any function
2401 * that vends out send rights to this port could resurrect it between
2402 * this notification being generated and actually being handled here.
2404 if (!ip_active(port
) ||
2405 task
->itk_task_ports
[flavor
] != port
||
2406 port
->ip_srights
> 0) {
2409 task_deallocate(task
);
2413 assert(task
->itk_task_ports
[flavor
] == port
);
2414 task
->itk_task_ports
[flavor
] = IP_NULL
;
2416 ipc_kobject_set_atomically(port
, IKO_NULL
, IKOT_NONE
);
2419 task_deallocate(task
);
2421 ipc_port_dealloc_kernel(port
);
2425 * task_wait_till_threads_terminate_locked
2427 * Wait till all the threads in the task are terminated.
2428 * Might release the task lock and re-acquire it.
2431 task_wait_till_threads_terminate_locked(task_t task
)
2433 /* wait for all the threads in the task to terminate */
2434 while (task
->active_thread_count
!= 0) {
2435 assert_wait((event_t
)&task
->active_thread_count
, THREAD_UNINT
);
2437 thread_block(THREAD_CONTINUE_NULL
);
2444 * task_duplicate_map_and_threads
2446 * Copy vmmap of source task.
2447 * Copy active threads from source task to destination task.
2448 * Source task would be suspended during the copy.
2451 task_duplicate_map_and_threads(
2455 thread_t
*thread_ret
,
2456 uint64_t **udata_buffer
,
2460 kern_return_t kr
= KERN_SUCCESS
;
2462 thread_t thread
, self
, thread_return
= THREAD_NULL
;
2463 thread_t new_thread
= THREAD_NULL
, first_thread
= THREAD_NULL
;
2464 thread_t
*thread_array
;
2465 uint32_t active_thread_count
= 0, array_count
= 0, i
;
2467 uint64_t *buffer
= NULL
;
2469 int est_knotes
= 0, num_knotes
= 0;
2471 self
= current_thread();
2474 * Suspend the task to copy thread state, use the internal
2475 * variant so that no user-space process can resume
2476 * the task from under us
2478 kr
= task_suspend_internal(task
);
2479 if (kr
!= KERN_SUCCESS
) {
2483 if (task
->map
->disable_vmentry_reuse
== TRUE
) {
2485 * Quite likely GuardMalloc (or some debugging tool)
2486 * is being used on this task. And it has gone through
2487 * its limit. Making a corpse will likely encounter
2488 * a lot of VM entries that will need COW.
2492 #if DEVELOPMENT || DEBUG
2493 memorystatus_abort_vm_map_fork(task
);
2495 task_resume_internal(task
);
2496 return KERN_FAILURE
;
2499 /* Check with VM if vm_map_fork is allowed for this task */
2500 if (memorystatus_allowed_vm_map_fork(task
)) {
2501 /* Setup new task's vmmap, switch from parent task's map to it COW map */
2502 oldmap
= new_task
->map
;
2503 new_task
->map
= vm_map_fork(new_task
->ledger
,
2505 (VM_MAP_FORK_SHARE_IF_INHERIT_NONE
|
2506 VM_MAP_FORK_PRESERVE_PURGEABLE
|
2507 VM_MAP_FORK_CORPSE_FOOTPRINT
));
2508 vm_map_deallocate(oldmap
);
2510 /* copy ledgers that impact the memory footprint */
2511 vm_map_copy_footprint_ledgers(task
, new_task
);
2513 /* Get all the udata pointers from kqueue */
2514 est_knotes
= kevent_proc_copy_uptrs(p
, NULL
, 0);
2515 if (est_knotes
> 0) {
2516 buf_size
= (est_knotes
+ 32) * sizeof(uint64_t);
2517 buffer
= kheap_alloc(KHEAP_DATA_BUFFERS
, buf_size
, Z_WAITOK
);
2518 num_knotes
= kevent_proc_copy_uptrs(p
, buffer
, buf_size
);
2519 if (num_knotes
> est_knotes
+ 32) {
2520 num_knotes
= est_knotes
+ 32;
2525 active_thread_count
= task
->active_thread_count
;
2526 if (active_thread_count
== 0) {
2527 if (buffer
!= NULL
) {
2528 kheap_free(KHEAP_DATA_BUFFERS
, buffer
, buf_size
);
2530 task_resume_internal(task
);
2531 return KERN_FAILURE
;
2534 thread_array
= kheap_alloc(KHEAP_TEMP
,
2535 sizeof(thread_t
) * active_thread_count
, Z_WAITOK
);
2537 /* Iterate all the threads and drop the task lock before calling thread_create_with_continuation */
2539 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
2540 /* Skip inactive threads */
2541 active
= thread
->active
;
2546 if (array_count
>= active_thread_count
) {
2550 thread_array
[array_count
++] = thread
;
2551 thread_reference(thread
);
2555 for (i
= 0; i
< array_count
; i
++) {
2556 kr
= thread_create_with_continuation(new_task
, &new_thread
, (thread_continue_t
)thread_corpse_continue
);
2557 if (kr
!= KERN_SUCCESS
) {
2561 /* Equivalent of current thread in corpse */
2562 if (thread_array
[i
] == self
) {
2563 thread_return
= new_thread
;
2564 new_task
->crashed_thread_id
= thread_tid(new_thread
);
2565 } else if (first_thread
== NULL
) {
2566 first_thread
= new_thread
;
2568 /* drop the extra ref returned by thread_create_with_continuation */
2569 thread_deallocate(new_thread
);
2572 kr
= thread_dup2(thread_array
[i
], new_thread
);
2573 if (kr
!= KERN_SUCCESS
) {
2574 thread_mtx_lock(new_thread
);
2575 new_thread
->corpse_dup
= TRUE
;
2576 thread_mtx_unlock(new_thread
);
2580 /* Copy thread name */
2581 bsd_copythreadname(new_thread
->uthread
, thread_array
[i
]->uthread
);
2582 new_thread
->thread_tag
= thread_array
[i
]->thread_tag
;
2583 thread_copy_resource_info(new_thread
, thread_array
[i
]);
2586 /* return the first thread if we couldn't find the equivalent of current */
2587 if (thread_return
== THREAD_NULL
) {
2588 thread_return
= first_thread
;
2589 } else if (first_thread
!= THREAD_NULL
) {
2590 /* drop the extra ref returned by thread_create_with_continuation */
2591 thread_deallocate(first_thread
);
2594 task_resume_internal(task
);
2596 for (i
= 0; i
< array_count
; i
++) {
2597 thread_deallocate(thread_array
[i
]);
2599 kheap_free(KHEAP_TEMP
, thread_array
, sizeof(thread_t
) * active_thread_count
);
2601 if (kr
== KERN_SUCCESS
) {
2602 *thread_ret
= thread_return
;
2603 *udata_buffer
= buffer
;
2605 *num_udata
= num_knotes
;
2607 if (thread_return
!= THREAD_NULL
) {
2608 thread_deallocate(thread_return
);
2610 if (buffer
!= NULL
) {
2611 kheap_free(KHEAP_DATA_BUFFERS
, buffer
, buf_size
);
2618 #if CONFIG_SECLUDED_MEMORY
2619 extern void task_set_can_use_secluded_mem_locked(
2621 boolean_t can_use_secluded_mem
);
2622 #endif /* CONFIG_SECLUDED_MEMORY */
2625 int debug4k_panic_on_terminate
= 0;
2626 #endif /* MACH_ASSERT */
2628 task_terminate_internal(
2631 thread_t thread
, self
;
2633 boolean_t interrupt_save
;
2636 assert(task
!= kernel_task
);
2638 self
= current_thread();
2639 self_task
= self
->task
;
2642 * Get the task locked and make sure that we are not racing
2643 * with someone else trying to terminate us.
2645 if (task
== self_task
) {
2647 } else if (task
< self_task
) {
2649 task_lock(self_task
);
2651 task_lock(self_task
);
2655 #if CONFIG_SECLUDED_MEMORY
2656 if (task
->task_can_use_secluded_mem
) {
2657 task_set_can_use_secluded_mem_locked(task
, FALSE
);
2659 task
->task_could_use_secluded_mem
= FALSE
;
2660 task
->task_could_also_use_secluded_mem
= FALSE
;
2662 if (task
->task_suppressed_secluded
) {
2663 stop_secluded_suppression(task
);
2665 #endif /* CONFIG_SECLUDED_MEMORY */
2667 if (!task
->active
) {
2669 * Task is already being terminated.
2670 * Just return an error. If we are dying, this will
2671 * just get us to our AST special handler and that
2672 * will get us to finalize the termination of ourselves.
2675 if (self_task
!= task
) {
2676 task_unlock(self_task
);
2679 return KERN_FAILURE
;
2682 if (task_corpse_pending_report(task
)) {
2684 * Task is marked for reporting as corpse.
2685 * Just return an error. This will
2686 * just get us to our AST special handler and that
2687 * will get us to finish the path to death
2690 if (self_task
!= task
) {
2691 task_unlock(self_task
);
2694 return KERN_FAILURE
;
2697 if (self_task
!= task
) {
2698 task_unlock(self_task
);
2702 * Make sure the current thread does not get aborted out of
2703 * the waits inside these operations.
2705 interrupt_save
= thread_interrupt_level(THREAD_UNINT
);
2708 * Indicate that we want all the threads to stop executing
2709 * at user space by holding the task (we would have held
2710 * each thread independently in thread_terminate_internal -
2711 * but this way we may be more likely to already find it
2712 * held there). Mark the task inactive, and prevent
2713 * further task operations via the task port.
2715 task_hold_locked(task
);
2716 task
->active
= FALSE
;
2717 ipc_task_disable(task
);
2719 #if CONFIG_TELEMETRY
2721 * Notify telemetry that this task is going away.
2723 telemetry_task_ctl_locked(task
, TF_TELEMETRY
, 0);
2727 * Terminate each thread in the task.
2729 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
2730 thread_terminate_internal(thread
, TH_TERMINATE_OPTION_NONE
);
2734 if (task
->bsd_info
!= NULL
&& !task_is_exec_copy(task
)) {
2735 pid
= proc_pid(task
->bsd_info
);
2737 #endif /* MACH_BSD */
2741 proc_set_task_policy(task
, TASK_POLICY_ATTRIBUTE
,
2742 TASK_POLICY_TERMINATED
, TASK_POLICY_ENABLE
);
2744 /* Early object reap phase */
2746 // PR-17045188: Revisit implementation
2747 // task_partial_reap(task, pid);
2749 #if CONFIG_TASKWATCH
2751 * remove all task watchers
2753 task_removewatchers(task
);
2755 #endif /* CONFIG_TASKWATCH */
2758 * Destroy all synchronizers owned by the task.
2760 task_synchronizer_destroy_all(task
);
2763 * Clear the watchport boost on the task.
2765 task_remove_turnstile_watchports(task
);
2768 * Destroy the IPC space, leaving just a reference for it.
2770 ipc_space_terminate(task
->itk_space
);
2773 /* if some ledgers go negative on tear-down again... */
2774 ledger_disable_panic_on_negative(task
->map
->pmap
->ledger
,
2775 task_ledgers
.phys_footprint
);
2776 ledger_disable_panic_on_negative(task
->map
->pmap
->ledger
,
2777 task_ledgers
.internal
);
2778 ledger_disable_panic_on_negative(task
->map
->pmap
->ledger
,
2779 task_ledgers
.internal_compressed
);
2780 ledger_disable_panic_on_negative(task
->map
->pmap
->ledger
,
2781 task_ledgers
.iokit_mapped
);
2782 ledger_disable_panic_on_negative(task
->map
->pmap
->ledger
,
2783 task_ledgers
.alternate_accounting
);
2784 ledger_disable_panic_on_negative(task
->map
->pmap
->ledger
,
2785 task_ledgers
.alternate_accounting_compressed
);
2789 * If the current thread is a member of the task
2790 * being terminated, then the last reference to
2791 * the task will not be dropped until the thread
2792 * is finally reaped. To avoid incurring the
2793 * expense of removing the address space regions
2794 * at reap time, we do it explictly here.
2797 vm_map_lock(task
->map
);
2798 vm_map_disable_hole_optimization(task
->map
);
2799 vm_map_unlock(task
->map
);
2803 * Identify the pmap's process, in case the pmap ledgers drift
2804 * and we have to report it.
2807 if (task
->bsd_info
&& !task_is_exec_copy(task
)) {
2808 pid
= proc_pid(task
->bsd_info
);
2809 proc_name_kdp(task
, procname
, sizeof(procname
));
2812 strlcpy(procname
, "<unknown>", sizeof(procname
));
2814 pmap_set_process(task
->map
->pmap
, pid
, procname
);
2815 if (vm_map_page_shift(task
->map
) < (int)PAGE_SHIFT
) {
2816 DEBUG4K_LIFE("map %p procname: %s\n", task
->map
, procname
);
2817 if (debug4k_panic_on_terminate
) {
2818 panic("DEBUG4K: %s:%d %d[%s] map %p\n", __FUNCTION__
, __LINE__
, pid
, procname
, task
->map
);
2821 #endif /* MACH_ASSERT */
2823 vm_map_terminate(task
->map
);
2825 /* release our shared region */
2826 vm_shared_region_set(task
, NULL
);
2828 #if __has_feature(ptrauth_calls)
2829 task_set_shared_region_id(task
, NULL
);
2830 #endif /* __has_feature(ptrauth_calls) */
2832 lck_mtx_lock(&tasks_threads_lock
);
2833 queue_remove(&tasks
, task
, task_t
, tasks
);
2834 queue_enter(&terminated_tasks
, task
, task_t
, tasks
);
2836 terminated_tasks_count
++;
2837 lck_mtx_unlock(&tasks_threads_lock
);
2840 * We no longer need to guard against being aborted, so restore
2841 * the previous interruptible state.
2843 thread_interrupt_level(interrupt_save
);
2846 /* force the task to release all ctrs */
2847 if (task
->t_kpc
& TASK_KPC_FORCED_ALL_CTRS
) {
2848 kpc_force_all_ctrs(task
, 0);
2852 #if CONFIG_COALITIONS
2854 * Leave our coalitions. (drop activation but not reference)
2856 coalitions_remove_task(task
);
2860 extern int vm_compressor_available
;
2861 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
&& vm_compressor_available
) {
2862 task_disown_frozen_csegs(task
);
2863 assert(queue_empty(&task
->task_frozen_cseg_q
));
2865 #endif /* CONFIG_FREEZE */
2868 * Get rid of the task active reference on itself.
2870 task_deallocate(task
);
2872 return KERN_SUCCESS
;
2876 tasks_system_suspend(boolean_t suspend
)
2880 lck_mtx_lock(&tasks_threads_lock
);
2881 assert(tasks_suspend_state
!= suspend
);
2882 tasks_suspend_state
= suspend
;
2883 queue_iterate(&tasks
, task
, task_t
, tasks
) {
2884 if (task
== kernel_task
) {
2887 suspend
? task_suspend_internal(task
) : task_resume_internal(task
);
2889 lck_mtx_unlock(&tasks_threads_lock
);
2895 * Shut the current task down (except for the current thread) in
2896 * preparation for dramatic changes to the task (probably exec).
2897 * We hold the task and mark all other threads in the task for
2901 task_start_halt(task_t task
)
2903 kern_return_t kr
= KERN_SUCCESS
;
2905 kr
= task_start_halt_locked(task
, FALSE
);
2910 static kern_return_t
2911 task_start_halt_locked(task_t task
, boolean_t should_mark_corpse
)
2913 thread_t thread
, self
;
2914 uint64_t dispatchqueue_offset
;
2916 assert(task
!= kernel_task
);
2918 self
= current_thread();
2920 if (task
!= self
->task
&& !task_is_a_corpse_fork(task
)) {
2921 return KERN_INVALID_ARGUMENT
;
2924 if (task
->halting
|| !task
->active
|| !self
->active
) {
2926 * Task or current thread is already being terminated.
2927 * Hurry up and return out of the current kernel context
2928 * so that we run our AST special handler to terminate
2931 return KERN_FAILURE
;
2934 task
->halting
= TRUE
;
2937 * Mark all the threads to keep them from starting any more
2938 * user-level execution. The thread_terminate_internal code
2939 * would do this on a thread by thread basis anyway, but this
2940 * gives us a better chance of not having to wait there.
2942 task_hold_locked(task
);
2943 dispatchqueue_offset
= get_dispatchqueue_offset_from_proc(task
->bsd_info
);
2946 * Terminate all the other threads in the task.
2948 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
)
2950 if (should_mark_corpse
) {
2951 thread_mtx_lock(thread
);
2952 thread
->inspection
= TRUE
;
2953 thread_mtx_unlock(thread
);
2955 if (thread
!= self
) {
2956 thread_terminate_internal(thread
, TH_TERMINATE_OPTION_NONE
);
2959 task
->dispatchqueue_offset
= dispatchqueue_offset
;
2961 task_release_locked(task
);
2963 return KERN_SUCCESS
;
2968 * task_complete_halt:
2970 * Complete task halt by waiting for threads to terminate, then clean
2971 * up task resources (VM, port namespace, etc...) and then let the
2972 * current thread go in the (practically empty) task context.
2974 * Note: task->halting flag is not cleared in order to avoid creation
2975 * of new thread in old exec'ed task.
2978 task_complete_halt(task_t task
)
2981 assert(task
->halting
);
2982 assert(task
== current_task());
2985 * Wait for the other threads to get shut down.
2986 * When the last other thread is reaped, we'll be
2989 if (task
->thread_count
> 1) {
2990 assert_wait((event_t
)&task
->halting
, THREAD_UNINT
);
2992 thread_block(THREAD_CONTINUE_NULL
);
2998 * Give the machine dependent code a chance
2999 * to perform cleanup of task-level resources
3000 * associated with the current thread before
3001 * ripping apart the task.
3003 machine_task_terminate(task
);
3006 * Destroy all synchronizers owned by the task.
3008 task_synchronizer_destroy_all(task
);
3011 * Destroy the contents of the IPC space, leaving just
3012 * a reference for it.
3014 ipc_space_clean(task
->itk_space
);
3017 * Clean out the address space, as we are going to be
3018 * getting a new one.
3020 vm_map_remove(task
->map
, task
->map
->min_offset
,
3021 task
->map
->max_offset
,
3025 * + remove immutable mappings
3026 * + allow gaps in the range
3028 (VM_MAP_REMOVE_NO_UNNESTING
|
3029 VM_MAP_REMOVE_IMMUTABLE
|
3030 VM_MAP_REMOVE_GAPS_OK
));
3033 * Kick out any IOKitUser handles to the task. At best they're stale,
3034 * at worst someone is racing a SUID exec.
3036 iokit_task_terminate(task
);
3042 * Suspend execution of the specified task.
3043 * This is a recursive-style suspension of the task, a count of
3044 * suspends is maintained.
3046 * CONDITIONS: the task is locked and active.
3054 assert(task
->active
);
3056 if (task
->suspend_count
++ > 0) {
3060 if (task
->bsd_info
) {
3061 workq_proc_suspended(task
->bsd_info
);
3065 * Iterate through all the threads and hold them.
3067 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
3068 thread_mtx_lock(thread
);
3069 thread_hold(thread
);
3070 thread_mtx_unlock(thread
);
3077 * Same as the internal routine above, except that is must lock
3078 * and verify that the task is active. This differs from task_suspend
3079 * in that it places a kernel hold on the task rather than just a
3080 * user-level hold. This keeps users from over resuming and setting
3081 * it running out from under the kernel.
3083 * CONDITIONS: the caller holds a reference on the task
3089 if (task
== TASK_NULL
) {
3090 return KERN_INVALID_ARGUMENT
;
3095 if (!task
->active
) {
3098 return KERN_FAILURE
;
3101 task_hold_locked(task
);
3104 return KERN_SUCCESS
;
3110 boolean_t until_not_runnable
)
3112 if (task
== TASK_NULL
) {
3113 return KERN_INVALID_ARGUMENT
;
3118 if (!task
->active
) {
3121 return KERN_FAILURE
;
3124 task_wait_locked(task
, until_not_runnable
);
3127 return KERN_SUCCESS
;
3133 * Wait for all threads in task to stop.
3136 * Called with task locked, active, and held.
3141 boolean_t until_not_runnable
)
3143 thread_t thread
, self
;
3145 assert(task
->active
);
3146 assert(task
->suspend_count
> 0);
3148 self
= current_thread();
3151 * Iterate through all the threads and wait for them to
3152 * stop. Do not wait for the current thread if it is within
3155 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
3156 if (thread
!= self
) {
3157 thread_wait(thread
, until_not_runnable
);
3163 task_is_app_suspended(task_t task
)
3165 return task
->pidsuspended
;
3169 * task_release_locked:
3171 * Release a kernel hold on a task.
3173 * CONDITIONS: the task is locked and active
3176 task_release_locked(
3181 assert(task
->active
);
3182 assert(task
->suspend_count
> 0);
3184 if (--task
->suspend_count
> 0) {
3188 if (task
->bsd_info
) {
3189 workq_proc_resumed(task
->bsd_info
);
3192 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
3193 thread_mtx_lock(thread
);
3194 thread_release(thread
);
3195 thread_mtx_unlock(thread
);
3202 * Same as the internal routine above, except that it must lock
3203 * and verify that the task is active.
3205 * CONDITIONS: The caller holds a reference to the task
3211 if (task
== TASK_NULL
) {
3212 return KERN_INVALID_ARGUMENT
;
3217 if (!task
->active
) {
3220 return KERN_FAILURE
;
3223 task_release_locked(task
);
3226 return KERN_SUCCESS
;
3229 static kern_return_t
3230 task_threads_internal(
3232 thread_act_array_t
*threads_out
,
3233 mach_msg_type_number_t
*count
,
3234 mach_thread_flavor_t flavor
)
3236 mach_msg_type_number_t actual
;
3237 thread_t
*thread_list
;
3239 vm_size_t size
, size_needed
;
3243 size
= 0; addr
= NULL
;
3245 if (task
== TASK_NULL
) {
3246 return KERN_INVALID_ARGUMENT
;
3249 assert(flavor
<= THREAD_FLAVOR_INSPECT
);
3253 if (!task
->active
) {
3260 return KERN_FAILURE
;
3263 actual
= task
->thread_count
;
3265 /* do we have the memory we need? */
3266 size_needed
= actual
* sizeof(mach_port_t
);
3267 if (size_needed
<= size
) {
3271 /* unlock the task and allocate more memory */
3278 assert(size_needed
> 0);
3281 addr
= kalloc(size
);
3283 return KERN_RESOURCE_SHORTAGE
;
3287 /* OK, have memory and the task is locked & active */
3288 thread_list
= (thread_t
*)addr
;
3292 for (thread
= (thread_t
)queue_first(&task
->threads
); i
< actual
;
3293 ++i
, thread
= (thread_t
)queue_next(&thread
->task_threads
)) {
3294 thread_reference_internal(thread
);
3295 thread_list
[j
++] = thread
;
3298 assert(queue_end(&task
->threads
, (queue_entry_t
)thread
));
3301 size_needed
= actual
* sizeof(mach_port_t
);
3303 /* can unlock task now that we've got the thread refs */
3307 /* no threads, so return null pointer and deallocate memory */
3309 *threads_out
= NULL
;
3316 /* if we allocated too much, must copy */
3318 if (size_needed
< size
) {
3321 newaddr
= kalloc(size_needed
);
3323 for (i
= 0; i
< actual
; ++i
) {
3324 thread_deallocate(thread_list
[i
]);
3327 return KERN_RESOURCE_SHORTAGE
;
3330 bcopy(addr
, newaddr
, size_needed
);
3332 thread_list
= (thread_t
*)newaddr
;
3335 *threads_out
= thread_list
;
3338 /* do the conversion that Mig should handle */
3341 case THREAD_FLAVOR_CONTROL
:
3342 if (task
== current_task()) {
3343 for (i
= 0; i
< actual
; ++i
) {
3344 ((ipc_port_t
*) thread_list
)[i
] = convert_thread_to_port_pinned(thread_list
[i
]);
3347 for (i
= 0; i
< actual
; ++i
) {
3348 ((ipc_port_t
*) thread_list
)[i
] = convert_thread_to_port(thread_list
[i
]);
3352 case THREAD_FLAVOR_READ
:
3353 for (i
= 0; i
< actual
; ++i
) {
3354 ((ipc_port_t
*) thread_list
)[i
] = convert_thread_read_to_port(thread_list
[i
]);
3357 case THREAD_FLAVOR_INSPECT
:
3358 for (i
= 0; i
< actual
; ++i
) {
3359 ((ipc_port_t
*) thread_list
)[i
] = convert_thread_inspect_to_port(thread_list
[i
]);
3365 return KERN_SUCCESS
;
3371 thread_act_array_t
*threads_out
,
3372 mach_msg_type_number_t
*count
)
3374 return task_threads_internal(task
, threads_out
, count
, THREAD_FLAVOR_CONTROL
);
3379 task_threads_from_user(
3381 thread_act_array_t
*threads_out
,
3382 mach_msg_type_number_t
*count
)
3384 ipc_kobject_type_t kotype
;
3387 task_t task
= convert_port_to_task_check_type(port
, &kotype
, TASK_FLAVOR_INSPECT
, FALSE
);
3389 if (task
== TASK_NULL
) {
3390 return KERN_INVALID_ARGUMENT
;
3394 case IKOT_TASK_CONTROL
:
3395 kr
= task_threads_internal(task
, threads_out
, count
, THREAD_FLAVOR_CONTROL
);
3397 case IKOT_TASK_READ
:
3398 kr
= task_threads_internal(task
, threads_out
, count
, THREAD_FLAVOR_READ
);
3400 case IKOT_TASK_INSPECT
:
3401 kr
= task_threads_internal(task
, threads_out
, count
, THREAD_FLAVOR_INSPECT
);
3404 panic("strange kobject type");
3408 task_deallocate(task
);
3412 #define TASK_HOLD_NORMAL 0
3413 #define TASK_HOLD_PIDSUSPEND 1
3414 #define TASK_HOLD_LEGACY 2
3415 #define TASK_HOLD_LEGACY_ALL 3
3417 static kern_return_t
3422 if (!task
->active
&& !task_is_a_corpse(task
)) {
3423 return KERN_FAILURE
;
3426 /* Return success for corpse task */
3427 if (task_is_a_corpse(task
)) {
3428 return KERN_SUCCESS
;
3431 KDBG_RELEASE(MACHDBG_CODE(DBG_MACH_IPC
, MACH_TASK_SUSPEND
),
3433 task
->thread_count
> 0 ?((thread_t
)queue_first(&task
->threads
))->thread_id
: 0,
3434 task
->user_stop_count
, task
->user_stop_count
+ 1);
3437 current_task()->suspends_outstanding
++;
3440 if (mode
== TASK_HOLD_LEGACY
) {
3441 task
->legacy_stop_count
++;
3444 if (task
->user_stop_count
++ > 0) {
3446 * If the stop count was positive, the task is
3447 * already stopped and we can exit.
3449 return KERN_SUCCESS
;
3453 * Put a kernel-level hold on the threads in the task (all
3454 * user-level task suspensions added together represent a
3455 * single kernel-level hold). We then wait for the threads
3456 * to stop executing user code.
3458 task_hold_locked(task
);
3459 task_wait_locked(task
, FALSE
);
3461 return KERN_SUCCESS
;
3464 static kern_return_t
3469 boolean_t release
= FALSE
;
3471 if (!task
->active
&& !task_is_a_corpse(task
)) {
3472 return KERN_FAILURE
;
3475 /* Return success for corpse task */
3476 if (task_is_a_corpse(task
)) {
3477 return KERN_SUCCESS
;
3480 if (mode
== TASK_HOLD_PIDSUSPEND
) {
3481 if (task
->pidsuspended
== FALSE
) {
3482 return KERN_FAILURE
;
3484 task
->pidsuspended
= FALSE
;
3487 if (task
->user_stop_count
> (task
->pidsuspended
? 1 : 0)) {
3488 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
3489 MACHDBG_CODE(DBG_MACH_IPC
, MACH_TASK_RESUME
) | DBG_FUNC_NONE
,
3490 task_pid(task
), ((thread_t
)queue_first(&task
->threads
))->thread_id
,
3491 task
->user_stop_count
, mode
, task
->legacy_stop_count
);
3495 * This is obviously not robust; if we suspend one task and then resume a different one,
3496 * we'll fly under the radar. This is only meant to catch the common case of a crashed
3497 * or buggy suspender.
3499 current_task()->suspends_outstanding
--;
3502 if (mode
== TASK_HOLD_LEGACY_ALL
) {
3503 if (task
->legacy_stop_count
>= task
->user_stop_count
) {
3504 task
->user_stop_count
= 0;
3507 task
->user_stop_count
-= task
->legacy_stop_count
;
3509 task
->legacy_stop_count
= 0;
3511 if (mode
== TASK_HOLD_LEGACY
&& task
->legacy_stop_count
> 0) {
3512 task
->legacy_stop_count
--;
3514 if (--task
->user_stop_count
== 0) {
3519 return KERN_FAILURE
;
3523 * Release the task if necessary.
3526 task_release_locked(task
);
3529 return KERN_SUCCESS
;
3533 get_task_suspended(task_t task
)
3535 return 0 != task
->user_stop_count
;
3541 * Implement an (old-fashioned) user-level suspension on a task.
3543 * Because the user isn't expecting to have to manage a suspension
3544 * token, we'll track it for him in the kernel in the form of a naked
3545 * send right to the task's resume port. All such send rights
3546 * account for a single suspension against the task (unlike task_suspend2()
3547 * where each caller gets a unique suspension count represented by a
3548 * unique send-once right).
3551 * The caller holds a reference to the task
3559 mach_port_name_t name
;
3561 if (task
== TASK_NULL
|| task
== kernel_task
) {
3562 return KERN_INVALID_ARGUMENT
;
3568 * place a legacy hold on the task.
3570 kr
= place_task_hold(task
, TASK_HOLD_LEGACY
);
3571 if (kr
!= KERN_SUCCESS
) {
3577 * Claim a send right on the task resume port, and request a no-senders
3578 * notification on that port (if none outstanding).
3580 (void)ipc_kobject_make_send_lazy_alloc_port((ipc_port_t
*) &task
->itk_resume
,
3581 (ipc_kobject_t
)task
, IKOT_TASK_RESUME
, IPC_KOBJECT_ALLOC_NONE
, true,
3582 OS_PTRAUTH_DISCRIMINATOR("task.itk_resume"));
3583 port
= task
->itk_resume
;
3587 * Copyout the send right into the calling task's IPC space. It won't know it is there,
3588 * but we'll look it up when calling a traditional resume. Any IPC operations that
3589 * deallocate the send right will auto-release the suspension.
3591 if (IP_VALID(port
)) {
3592 kr
= ipc_object_copyout(current_space(), ip_to_object(port
),
3593 MACH_MSG_TYPE_MOVE_SEND
, IPC_OBJECT_COPYOUT_FLAGS_NONE
,
3598 if (kr
!= KERN_SUCCESS
) {
3599 printf("warning: %s(%d) failed to copyout suspension "
3600 "token for pid %d with error: %d\n",
3601 proc_name_address(current_task()->bsd_info
),
3602 proc_pid(current_task()->bsd_info
),
3603 task_pid(task
), kr
);
3611 * Release a user hold on a task.
3614 * The caller holds a reference to the task
3621 mach_port_name_t resume_port_name
;
3622 ipc_entry_t resume_port_entry
;
3623 ipc_space_t space
= current_task()->itk_space
;
3625 if (task
== TASK_NULL
|| task
== kernel_task
) {
3626 return KERN_INVALID_ARGUMENT
;
3629 /* release a legacy task hold */
3631 kr
= release_task_hold(task
, TASK_HOLD_LEGACY
);
3634 is_write_lock(space
);
3635 if (is_active(space
) && IP_VALID(task
->itk_resume
) &&
3636 ipc_hash_lookup(space
, ip_to_object(task
->itk_resume
), &resume_port_name
, &resume_port_entry
) == TRUE
) {
3638 * We found a suspension token in the caller's IPC space. Release a send right to indicate that
3639 * we are holding one less legacy hold on the task from this caller. If the release failed,
3640 * go ahead and drop all the rights, as someone either already released our holds or the task
3643 if (kr
== KERN_SUCCESS
) {
3644 ipc_right_dealloc(space
, resume_port_name
, resume_port_entry
);
3646 ipc_right_destroy(space
, resume_port_name
, resume_port_entry
, FALSE
, 0);
3648 /* space unlocked */
3650 is_write_unlock(space
);
3651 if (kr
== KERN_SUCCESS
) {
3652 printf("warning: %s(%d) performed out-of-band resume on pid %d\n",
3653 proc_name_address(current_task()->bsd_info
), proc_pid(current_task()->bsd_info
),
3662 * Suspend the target task.
3663 * Making/holding a token/reference/port is the callers responsibility.
3666 task_suspend_internal(task_t task
)
3670 if (task
== TASK_NULL
|| task
== kernel_task
) {
3671 return KERN_INVALID_ARGUMENT
;
3675 kr
= place_task_hold(task
, TASK_HOLD_NORMAL
);
3681 * Suspend the target task, and return a suspension token. The token
3682 * represents a reference on the suspended task.
3687 task_suspension_token_t
*suspend_token
)
3691 kr
= task_suspend_internal(task
);
3692 if (kr
!= KERN_SUCCESS
) {
3693 *suspend_token
= TASK_NULL
;
3698 * Take a reference on the target task and return that to the caller
3699 * as a "suspension token," which can be converted into an SO right to
3700 * the now-suspended task's resume port.
3702 task_reference_internal(task
);
3703 *suspend_token
= task
;
3705 return KERN_SUCCESS
;
3710 * (reference/token/port management is caller's responsibility).
3713 task_resume_internal(
3714 task_suspension_token_t task
)
3718 if (task
== TASK_NULL
|| task
== kernel_task
) {
3719 return KERN_INVALID_ARGUMENT
;
3723 kr
= release_task_hold(task
, TASK_HOLD_NORMAL
);
3729 * Resume the task using a suspension token. Consumes the token's ref.
3733 task_suspension_token_t task
)
3737 kr
= task_resume_internal(task
);
3738 task_suspension_token_deallocate(task
);
3744 task_suspension_notify(mach_msg_header_t
*request_header
)
3746 ipc_port_t port
= request_header
->msgh_remote_port
;
3747 task_t task
= convert_port_to_task_suspension_token(port
);
3748 mach_msg_type_number_t not_count
;
3750 if (task
== TASK_NULL
|| task
== kernel_task
) {
3751 return TRUE
; /* nothing to do */
3753 switch (request_header
->msgh_id
) {
3754 case MACH_NOTIFY_SEND_ONCE
:
3755 /* release the hold held by this specific send-once right */
3757 release_task_hold(task
, TASK_HOLD_NORMAL
);
3761 case MACH_NOTIFY_NO_SENDERS
:
3762 not_count
= ((mach_no_senders_notification_t
*)request_header
)->not_count
;
3766 if (port
->ip_mscount
== not_count
) {
3767 /* release all the [remaining] outstanding legacy holds */
3768 assert(port
->ip_nsrequest
== IP_NULL
);
3770 release_task_hold(task
, TASK_HOLD_LEGACY_ALL
);
3772 } else if (port
->ip_nsrequest
== IP_NULL
) {
3773 ipc_port_t old_notify
;
3776 /* new send rights, re-arm notification at current make-send count */
3777 ipc_port_nsrequest(port
, port
->ip_mscount
, ipc_port_make_sonce_locked(port
), &old_notify
);
3778 assert(old_notify
== IP_NULL
);
3790 task_suspension_token_deallocate(task
); /* drop token reference */
3794 static kern_return_t
3795 task_pidsuspend_locked(task_t task
)
3799 if (task
->pidsuspended
) {
3804 task
->pidsuspended
= TRUE
;
3806 kr
= place_task_hold(task
, TASK_HOLD_PIDSUSPEND
);
3807 if (kr
!= KERN_SUCCESS
) {
3808 task
->pidsuspended
= FALSE
;
3818 * Suspends a task by placing a hold on its threads.
3821 * The caller holds a reference to the task
3829 if (task
== TASK_NULL
|| task
== kernel_task
) {
3830 return KERN_INVALID_ARGUMENT
;
3835 kr
= task_pidsuspend_locked(task
);
3839 if ((KERN_SUCCESS
== kr
) && task
->message_app_suspended
) {
3840 iokit_task_app_suspended_changed(task
);
3848 * Resumes a previously suspended task.
3851 * The caller holds a reference to the task
3859 if (task
== TASK_NULL
|| task
== kernel_task
) {
3860 return KERN_INVALID_ARGUMENT
;
3867 while (task
->changing_freeze_state
) {
3868 assert_wait((event_t
)&task
->changing_freeze_state
, THREAD_UNINT
);
3870 thread_block(THREAD_CONTINUE_NULL
);
3874 task
->changing_freeze_state
= TRUE
;
3877 kr
= release_task_hold(task
, TASK_HOLD_PIDSUSPEND
);
3881 if ((KERN_SUCCESS
== kr
) && task
->message_app_suspended
) {
3882 iokit_task_app_suspended_changed(task
);
3889 if (kr
== KERN_SUCCESS
) {
3890 task
->frozen
= FALSE
;
3892 task
->changing_freeze_state
= FALSE
;
3893 thread_wakeup(&task
->changing_freeze_state
);
3901 os_refgrp_decl(static, task_watchports_refgrp
, "task_watchports", NULL
);
3904 * task_add_turnstile_watchports:
3905 * Setup watchports to boost the main thread of the task.
3908 * task: task being spawned
3909 * thread: main thread of task
3910 * portwatch_ports: array of watchports
3911 * portwatch_count: number of watchports
3917 task_add_turnstile_watchports(
3920 ipc_port_t
*portwatch_ports
,
3921 uint32_t portwatch_count
)
3923 struct task_watchports
*watchports
= NULL
;
3924 struct task_watchport_elem
*previous_elem_array
[TASK_MAX_WATCHPORT_COUNT
] = {};
3925 os_ref_count_t refs
;
3927 /* Check if the task has terminated */
3928 if (!task
->active
) {
3932 assert(portwatch_count
<= TASK_MAX_WATCHPORT_COUNT
);
3934 watchports
= task_watchports_alloc_init(task
, thread
, portwatch_count
);
3936 /* Lock the ipc space */
3937 is_write_lock(task
->itk_space
);
3939 /* Setup watchports to boost the main thread */
3940 refs
= task_add_turnstile_watchports_locked(task
,
3941 watchports
, previous_elem_array
, portwatch_ports
,
3944 /* Drop the space lock */
3945 is_write_unlock(task
->itk_space
);
3948 task_watchports_deallocate(watchports
);
3951 /* Drop the ref on previous_elem_array */
3952 for (uint32_t i
= 0; i
< portwatch_count
&& previous_elem_array
[i
] != NULL
; i
++) {
3953 task_watchport_elem_deallocate(previous_elem_array
[i
]);
3958 * task_remove_turnstile_watchports:
3959 * Clear all turnstile boost on the task from watchports.
3962 * task: task being terminated
3968 task_remove_turnstile_watchports(
3971 os_ref_count_t refs
= TASK_MAX_WATCHPORT_COUNT
;
3972 struct task_watchports
*watchports
= NULL
;
3973 ipc_port_t port_freelist
[TASK_MAX_WATCHPORT_COUNT
] = {};
3974 uint32_t portwatch_count
;
3976 /* Lock the ipc space */
3977 is_write_lock(task
->itk_space
);
3979 /* Check if watchport boost exist */
3980 if (task
->watchports
== NULL
) {
3981 is_write_unlock(task
->itk_space
);
3984 watchports
= task
->watchports
;
3985 portwatch_count
= watchports
->tw_elem_array_count
;
3987 refs
= task_remove_turnstile_watchports_locked(task
, watchports
,
3990 is_write_unlock(task
->itk_space
);
3992 /* Drop all the port references */
3993 for (uint32_t i
= 0; i
< portwatch_count
&& port_freelist
[i
] != NULL
; i
++) {
3994 ip_release(port_freelist
[i
]);
3997 /* Clear the task and thread references for task_watchport */
3999 task_watchports_deallocate(watchports
);
4004 * task_transfer_turnstile_watchports:
4005 * Transfer all watchport turnstile boost from old task to new task.
4008 * old_task: task calling exec
4009 * new_task: new exec'ed task
4010 * thread: main thread of new task
4016 task_transfer_turnstile_watchports(
4019 thread_t new_thread
)
4021 struct task_watchports
*old_watchports
= NULL
;
4022 struct task_watchports
*new_watchports
= NULL
;
4023 os_ref_count_t old_refs
= TASK_MAX_WATCHPORT_COUNT
;
4024 os_ref_count_t new_refs
= TASK_MAX_WATCHPORT_COUNT
;
4025 uint32_t portwatch_count
;
4027 if (old_task
->watchports
== NULL
|| !new_task
->active
) {
4031 /* Get the watch port count from the old task */
4032 is_write_lock(old_task
->itk_space
);
4033 if (old_task
->watchports
== NULL
) {
4034 is_write_unlock(old_task
->itk_space
);
4038 portwatch_count
= old_task
->watchports
->tw_elem_array_count
;
4039 is_write_unlock(old_task
->itk_space
);
4041 new_watchports
= task_watchports_alloc_init(new_task
, new_thread
, portwatch_count
);
4043 /* Lock the ipc space for old task */
4044 is_write_lock(old_task
->itk_space
);
4046 /* Lock the ipc space for new task */
4047 is_write_lock(new_task
->itk_space
);
4049 /* Check if watchport boost exist */
4050 if (old_task
->watchports
== NULL
|| !new_task
->active
) {
4051 is_write_unlock(new_task
->itk_space
);
4052 is_write_unlock(old_task
->itk_space
);
4053 (void)task_watchports_release(new_watchports
);
4054 task_watchports_deallocate(new_watchports
);
4058 old_watchports
= old_task
->watchports
;
4059 assert(portwatch_count
== old_task
->watchports
->tw_elem_array_count
);
4061 /* Setup new task watchports */
4062 new_task
->watchports
= new_watchports
;
4064 for (uint32_t i
= 0; i
< portwatch_count
; i
++) {
4065 ipc_port_t port
= old_watchports
->tw_elem
[i
].twe_port
;
4068 task_watchport_elem_clear(&new_watchports
->tw_elem
[i
]);
4072 /* Lock the port and check if it has the entry */
4074 imq_lock(&port
->ip_messages
);
4076 task_watchport_elem_init(&new_watchports
->tw_elem
[i
], new_task
, port
);
4078 if (ipc_port_replace_watchport_elem_conditional_locked(port
,
4079 &old_watchports
->tw_elem
[i
], &new_watchports
->tw_elem
[i
]) == KERN_SUCCESS
) {
4080 task_watchport_elem_clear(&old_watchports
->tw_elem
[i
]);
4082 task_watchports_retain(new_watchports
);
4083 old_refs
= task_watchports_release(old_watchports
);
4085 /* Check if all ports are cleaned */
4086 if (old_refs
== 0) {
4087 old_task
->watchports
= NULL
;
4090 task_watchport_elem_clear(&new_watchports
->tw_elem
[i
]);
4092 /* mqueue and port unlocked by ipc_port_replace_watchport_elem_conditional_locked */
4095 /* Drop the reference on new task_watchports struct returned by task_watchports_alloc_init */
4096 new_refs
= task_watchports_release(new_watchports
);
4097 if (new_refs
== 0) {
4098 new_task
->watchports
= NULL
;
4101 is_write_unlock(new_task
->itk_space
);
4102 is_write_unlock(old_task
->itk_space
);
4104 /* Clear the task and thread references for old_watchport */
4105 if (old_refs
== 0) {
4106 task_watchports_deallocate(old_watchports
);
4109 /* Clear the task and thread references for new_watchport */
4110 if (new_refs
== 0) {
4111 task_watchports_deallocate(new_watchports
);
4116 * task_add_turnstile_watchports_locked:
4117 * Setup watchports to boost the main thread of the task.
4120 * task: task to boost
4121 * watchports: watchport structure to be attached to the task
4122 * previous_elem_array: an array of old watchport_elem to be returned to caller
4123 * portwatch_ports: array of watchports
4124 * portwatch_count: number of watchports
4127 * ipc space of the task locked.
4128 * returns array of old watchport_elem in previous_elem_array
4130 static os_ref_count_t
4131 task_add_turnstile_watchports_locked(
4133 struct task_watchports
*watchports
,
4134 struct task_watchport_elem
**previous_elem_array
,
4135 ipc_port_t
*portwatch_ports
,
4136 uint32_t portwatch_count
)
4138 os_ref_count_t refs
= TASK_MAX_WATCHPORT_COUNT
;
4140 /* Check if the task is still active */
4141 if (!task
->active
) {
4142 refs
= task_watchports_release(watchports
);
4146 assert(task
->watchports
== NULL
);
4147 task
->watchports
= watchports
;
4149 for (uint32_t i
= 0, j
= 0; i
< portwatch_count
; i
++) {
4150 ipc_port_t port
= portwatch_ports
[i
];
4152 task_watchport_elem_init(&watchports
->tw_elem
[i
], task
, port
);
4154 task_watchport_elem_clear(&watchports
->tw_elem
[i
]);
4159 imq_lock(&port
->ip_messages
);
4161 /* Check if port is in valid state to be setup as watchport */
4162 if (ipc_port_add_watchport_elem_locked(port
, &watchports
->tw_elem
[i
],
4163 &previous_elem_array
[j
]) != KERN_SUCCESS
) {
4164 task_watchport_elem_clear(&watchports
->tw_elem
[i
]);
4167 /* port and mqueue unlocked on return */
4170 task_watchports_retain(watchports
);
4171 if (previous_elem_array
[j
] != NULL
) {
4176 /* Drop the reference on task_watchport struct returned by os_ref_init */
4177 refs
= task_watchports_release(watchports
);
4179 task
->watchports
= NULL
;
4186 * task_remove_turnstile_watchports_locked:
4187 * Clear all turnstile boost on the task from watchports.
4190 * task: task to remove watchports from
4191 * watchports: watchports structure for the task
4192 * port_freelist: array of ports returned with ref to caller
4196 * ipc space of the task locked.
4197 * array of ports with refs are returned in port_freelist
4199 static os_ref_count_t
4200 task_remove_turnstile_watchports_locked(
4202 struct task_watchports
*watchports
,
4203 ipc_port_t
*port_freelist
)
4205 os_ref_count_t refs
= TASK_MAX_WATCHPORT_COUNT
;
4207 for (uint32_t i
= 0, j
= 0; i
< watchports
->tw_elem_array_count
; i
++) {
4208 ipc_port_t port
= watchports
->tw_elem
[i
].twe_port
;
4213 /* Lock the port and check if it has the entry */
4215 imq_lock(&port
->ip_messages
);
4216 if (ipc_port_clear_watchport_elem_internal_conditional_locked(port
,
4217 &watchports
->tw_elem
[i
]) == KERN_SUCCESS
) {
4218 task_watchport_elem_clear(&watchports
->tw_elem
[i
]);
4219 port_freelist
[j
++] = port
;
4220 refs
= task_watchports_release(watchports
);
4222 /* Check if all ports are cleaned */
4224 task
->watchports
= NULL
;
4228 /* mqueue and port unlocked by ipc_port_clear_watchport_elem_internal_conditional_locked */
4234 * task_watchports_alloc_init:
4235 * Allocate and initialize task watchport struct.
4240 static struct task_watchports
*
4241 task_watchports_alloc_init(
4246 struct task_watchports
*watchports
= kalloc(sizeof(struct task_watchports
) +
4247 count
* sizeof(struct task_watchport_elem
));
4249 task_reference(task
);
4250 thread_reference(thread
);
4251 watchports
->tw_task
= task
;
4252 watchports
->tw_thread
= thread
;
4253 watchports
->tw_elem_array_count
= count
;
4254 os_ref_init(&watchports
->tw_refcount
, &task_watchports_refgrp
);
4260 * task_watchports_deallocate:
4261 * Deallocate task watchport struct.
4267 task_watchports_deallocate(
4268 struct task_watchports
*watchports
)
4270 uint32_t portwatch_count
= watchports
->tw_elem_array_count
;
4272 task_deallocate(watchports
->tw_task
);
4273 thread_deallocate(watchports
->tw_thread
);
4274 kfree(watchports
, sizeof(struct task_watchports
) + portwatch_count
* sizeof(struct task_watchport_elem
));
4278 * task_watchport_elem_deallocate:
4279 * Deallocate task watchport element and release its ref on task_watchport.
4285 task_watchport_elem_deallocate(
4286 struct task_watchport_elem
*watchport_elem
)
4288 os_ref_count_t refs
= TASK_MAX_WATCHPORT_COUNT
;
4289 task_t task
= watchport_elem
->twe_task
;
4290 struct task_watchports
*watchports
= NULL
;
4291 ipc_port_t port
= NULL
;
4293 assert(task
!= NULL
);
4295 /* Take the space lock to modify the elememt */
4296 is_write_lock(task
->itk_space
);
4298 watchports
= task
->watchports
;
4299 assert(watchports
!= NULL
);
4301 port
= watchport_elem
->twe_port
;
4302 assert(port
!= NULL
);
4304 task_watchport_elem_clear(watchport_elem
);
4305 refs
= task_watchports_release(watchports
);
4308 task
->watchports
= NULL
;
4311 is_write_unlock(task
->itk_space
);
4315 task_watchports_deallocate(watchports
);
4320 * task_has_watchports:
4321 * Return TRUE if task has watchport boosts.
4327 task_has_watchports(task_t task
)
4329 return task
->watchports
!= NULL
;
4332 #if DEVELOPMENT || DEBUG
4334 extern void IOSleep(int);
4337 task_disconnect_page_mappings(task_t task
)
4341 if (task
== TASK_NULL
|| task
== kernel_task
) {
4342 return KERN_INVALID_ARGUMENT
;
4346 * this function is used to strip all of the mappings from
4347 * the pmap for the specified task to force the task to
4348 * re-fault all of the pages it is actively using... this
4349 * allows us to approximate the true working set of the
4350 * specified task. We only engage if at least 1 of the
4351 * threads in the task is runnable, but we want to continuously
4352 * sweep (at least for a while - I've arbitrarily set the limit at
4353 * 100 sweeps to be re-looked at as we gain experience) to get a better
4354 * view into what areas within a page are being visited (as opposed to only
4355 * seeing the first fault of a page after the task becomes
4356 * runnable)... in the future I may
4357 * try to block until awakened by a thread in this task
4358 * being made runnable, but for now we'll periodically poll from the
4359 * user level debug tool driving the sysctl
4361 for (n
= 0; n
< 100; n
++) {
4364 boolean_t do_unnest
;
4372 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
4373 if (thread
->state
& TH_RUN
) {
4379 task
->task_disconnected_count
++;
4382 if (task
->task_unnested
== FALSE
) {
4383 if (runnable
== TRUE
) {
4384 task
->task_unnested
= TRUE
;
4390 if (runnable
== FALSE
) {
4394 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
, (MACHDBG_CODE(DBG_MACH_WORKINGSET
, VM_DISCONNECT_TASK_PAGE_MAPPINGS
)) | DBG_FUNC_START
,
4395 task
, do_unnest
, task
->task_disconnected_count
, 0, 0);
4397 page_count
= vm_map_disconnect_page_mappings(task
->map
, do_unnest
);
4399 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
, (MACHDBG_CODE(DBG_MACH_WORKINGSET
, VM_DISCONNECT_TASK_PAGE_MAPPINGS
)) | DBG_FUNC_END
,
4400 task
, page_count
, 0, 0, 0);
4406 return KERN_SUCCESS
;
4420 * The caller holds a reference to the task
4422 extern void vm_wake_compactor_swapper(void);
4423 extern queue_head_t c_swapout_list_head
;
4424 extern struct freezer_context freezer_context_global
;
4429 uint32_t *purgeable_count
,
4430 uint32_t *wired_count
,
4431 uint32_t *clean_count
,
4432 uint32_t *dirty_count
,
4433 uint32_t dirty_budget
,
4434 uint32_t *shared_count
,
4435 int *freezer_error_code
,
4436 boolean_t eval_only
)
4438 kern_return_t kr
= KERN_SUCCESS
;
4440 if (task
== TASK_NULL
|| task
== kernel_task
) {
4441 return KERN_INVALID_ARGUMENT
;
4446 while (task
->changing_freeze_state
) {
4447 assert_wait((event_t
)&task
->changing_freeze_state
, THREAD_UNINT
);
4449 thread_block(THREAD_CONTINUE_NULL
);
4455 return KERN_FAILURE
;
4457 task
->changing_freeze_state
= TRUE
;
4459 freezer_context_global
.freezer_ctx_task
= task
;
4463 kr
= vm_map_freeze(task
,
4475 if ((kr
== KERN_SUCCESS
) && (eval_only
== FALSE
)) {
4476 task
->frozen
= TRUE
;
4478 freezer_context_global
.freezer_ctx_task
= NULL
;
4479 freezer_context_global
.freezer_ctx_uncompressed_pages
= 0;
4481 if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE
) {
4483 * reset the counter tracking the # of swapped compressed pages
4484 * because we are now done with this freeze session and task.
4487 *dirty_count
= (uint32_t) (freezer_context_global
.freezer_ctx_swapped_bytes
/ PAGE_SIZE_64
); /*used to track pageouts*/
4490 freezer_context_global
.freezer_ctx_swapped_bytes
= 0;
4493 task
->changing_freeze_state
= FALSE
;
4494 thread_wakeup(&task
->changing_freeze_state
);
4498 if (VM_CONFIG_COMPRESSOR_IS_PRESENT
&&
4499 (kr
== KERN_SUCCESS
) &&
4500 (eval_only
== FALSE
)) {
4501 vm_wake_compactor_swapper();
4503 * We do an explicit wakeup of the swapout thread here
4504 * because the compact_and_swap routines don't have
4505 * knowledge about these kind of "per-task packed c_segs"
4506 * and so will not be evaluating whether we need to do
4509 thread_wakeup((event_t
)&c_swapout_list_head
);
4518 * Thaw a currently frozen task.
4521 * The caller holds a reference to the task
4527 if (task
== TASK_NULL
|| task
== kernel_task
) {
4528 return KERN_INVALID_ARGUMENT
;
4533 while (task
->changing_freeze_state
) {
4534 assert_wait((event_t
)&task
->changing_freeze_state
, THREAD_UNINT
);
4536 thread_block(THREAD_CONTINUE_NULL
);
4540 if (!task
->frozen
) {
4542 return KERN_FAILURE
;
4544 task
->frozen
= FALSE
;
4548 return KERN_SUCCESS
;
4552 task_update_frozen_to_swap_acct(task_t task
, int64_t amount
, freezer_acct_op_t op
)
4555 * We don't assert that the task lock is held because we call this
4556 * routine from the decompression path and we won't be holding the
4557 * task lock. However, since we are in the context of the task we are
4559 * In the case of the task_freeze path, we call it from behind the task
4560 * lock but we don't need to because we have a reference on the proc
4569 if (op
== CREDIT_TO_SWAP
) {
4570 ledger_credit_nocheck(task
->ledger
, task_ledgers
.frozen_to_swap
, amount
);
4571 } else if (op
== DEBIT_FROM_SWAP
) {
4572 ledger_debit_nocheck(task
->ledger
, task_ledgers
.frozen_to_swap
, amount
);
4574 panic("task_update_frozen_to_swap_acct: Invalid ledger op\n");
4577 #endif /* CONFIG_FREEZE */
4580 host_security_set_task_token(
4581 host_security_t host_security
,
4583 security_token_t sec_token
,
4584 audit_token_t audit_token
,
4585 host_priv_t host_priv
)
4587 ipc_port_t host_port
;
4590 if (task
== TASK_NULL
) {
4591 return KERN_INVALID_ARGUMENT
;
4594 if (host_security
== HOST_NULL
) {
4595 return KERN_INVALID_SECURITY
;
4599 task
->sec_token
= sec_token
;
4600 task
->audit_token
= audit_token
;
4603 if (host_priv
!= HOST_PRIV_NULL
) {
4604 kr
= host_get_host_priv_port(host_priv
, &host_port
);
4606 kr
= host_get_host_port(host_priv_self(), &host_port
);
4608 assert(kr
== KERN_SUCCESS
);
4610 kr
= task_set_special_port_internal(task
, TASK_HOST_PORT
, host_port
);
4615 task_send_trace_memory(
4616 __unused task_t target_task
,
4617 __unused
uint32_t pid
,
4618 __unused
uint64_t uniqueid
)
4620 return KERN_INVALID_ARGUMENT
;
4624 * This routine was added, pretty much exclusively, for registering the
4625 * RPC glue vector for in-kernel short circuited tasks. Rather than
4626 * removing it completely, I have only disabled that feature (which was
4627 * the only feature at the time). It just appears that we are going to
4628 * want to add some user data to tasks in the future (i.e. bsd info,
4629 * task names, etc...), so I left it in the formal task interface.
4634 task_flavor_t flavor
,
4635 __unused task_info_t task_info_in
, /* pointer to IN array */
4636 __unused mach_msg_type_number_t task_info_count
)
4638 if (task
== TASK_NULL
) {
4639 return KERN_INVALID_ARGUMENT
;
4643 case TASK_TRACE_MEMORY_INFO
:
4644 return KERN_NOT_SUPPORTED
;
4645 #endif // CONFIG_ATM
4647 return KERN_INVALID_ARGUMENT
;
4651 int radar_20146450
= 1;
4655 task_flavor_t flavor
,
4656 task_info_t task_info_out
,
4657 mach_msg_type_number_t
*task_info_count
)
4659 kern_return_t error
= KERN_SUCCESS
;
4660 mach_msg_type_number_t original_task_info_count
;
4661 bool is_kernel_task
= (task
== kernel_task
);
4663 if (task
== TASK_NULL
) {
4664 return KERN_INVALID_ARGUMENT
;
4667 original_task_info_count
= *task_info_count
;
4670 if ((task
!= current_task()) && (!task
->active
)) {
4672 return KERN_INVALID_ARGUMENT
;
4677 case TASK_BASIC_INFO_32
:
4678 case TASK_BASIC2_INFO_32
:
4679 #if defined(__arm__) || defined(__arm64__)
4680 case TASK_BASIC_INFO_64
:
4683 task_basic_info_32_t basic_info
;
4688 if (*task_info_count
< TASK_BASIC_INFO_32_COUNT
) {
4689 error
= KERN_INVALID_ARGUMENT
;
4693 basic_info
= (task_basic_info_32_t
)task_info_out
;
4695 map
= (task
== kernel_task
)? kernel_map
: task
->map
;
4696 basic_info
->virtual_size
= (typeof(basic_info
->virtual_size
))vm_map_adjusted_size(map
);
4697 if (flavor
== TASK_BASIC2_INFO_32
) {
4699 * The "BASIC2" flavor gets the maximum resident
4700 * size instead of the current resident size...
4702 basic_info
->resident_size
= pmap_resident_max(map
->pmap
);
4704 basic_info
->resident_size
= pmap_resident_count(map
->pmap
);
4706 basic_info
->resident_size
*= PAGE_SIZE
;
4708 basic_info
->policy
= ((task
!= kernel_task
)?
4709 POLICY_TIMESHARE
: POLICY_RR
);
4710 basic_info
->suspend_count
= task
->user_stop_count
;
4712 absolutetime_to_microtime(task
->total_user_time
, &secs
, &usecs
);
4713 basic_info
->user_time
.seconds
=
4714 (typeof(basic_info
->user_time
.seconds
))secs
;
4715 basic_info
->user_time
.microseconds
= usecs
;
4717 absolutetime_to_microtime(task
->total_system_time
, &secs
, &usecs
);
4718 basic_info
->system_time
.seconds
=
4719 (typeof(basic_info
->system_time
.seconds
))secs
;
4720 basic_info
->system_time
.microseconds
= usecs
;
4722 *task_info_count
= TASK_BASIC_INFO_32_COUNT
;
4726 #if defined(__arm__) || defined(__arm64__)
4727 case TASK_BASIC_INFO_64_2
:
4729 task_basic_info_64_2_t basic_info
;
4734 if (*task_info_count
< TASK_BASIC_INFO_64_2_COUNT
) {
4735 error
= KERN_INVALID_ARGUMENT
;
4739 basic_info
= (task_basic_info_64_2_t
)task_info_out
;
4741 map
= (task
== kernel_task
)? kernel_map
: task
->map
;
4742 basic_info
->virtual_size
= vm_map_adjusted_size(map
);
4743 basic_info
->resident_size
=
4744 (mach_vm_size_t
)(pmap_resident_count(map
->pmap
))
4747 basic_info
->policy
= ((task
!= kernel_task
)?
4748 POLICY_TIMESHARE
: POLICY_RR
);
4749 basic_info
->suspend_count
= task
->user_stop_count
;
4751 absolutetime_to_microtime(task
->total_user_time
, &secs
, &usecs
);
4752 basic_info
->user_time
.seconds
=
4753 (typeof(basic_info
->user_time
.seconds
))secs
;
4754 basic_info
->user_time
.microseconds
= usecs
;
4756 absolutetime_to_microtime(task
->total_system_time
, &secs
, &usecs
);
4757 basic_info
->system_time
.seconds
=
4758 (typeof(basic_info
->system_time
.seconds
))secs
;
4759 basic_info
->system_time
.microseconds
= usecs
;
4761 *task_info_count
= TASK_BASIC_INFO_64_2_COUNT
;
4765 #else /* defined(__arm__) || defined(__arm64__) */
4766 case TASK_BASIC_INFO_64
:
4768 task_basic_info_64_t basic_info
;
4773 if (*task_info_count
< TASK_BASIC_INFO_64_COUNT
) {
4774 error
= KERN_INVALID_ARGUMENT
;
4778 basic_info
= (task_basic_info_64_t
)task_info_out
;
4780 map
= (task
== kernel_task
)? kernel_map
: task
->map
;
4781 basic_info
->virtual_size
= vm_map_adjusted_size(map
);
4782 basic_info
->resident_size
=
4783 (mach_vm_size_t
)(pmap_resident_count(map
->pmap
))
4786 basic_info
->policy
= ((task
!= kernel_task
)?
4787 POLICY_TIMESHARE
: POLICY_RR
);
4788 basic_info
->suspend_count
= task
->user_stop_count
;
4790 absolutetime_to_microtime(task
->total_user_time
, &secs
, &usecs
);
4791 basic_info
->user_time
.seconds
=
4792 (typeof(basic_info
->user_time
.seconds
))secs
;
4793 basic_info
->user_time
.microseconds
= usecs
;
4795 absolutetime_to_microtime(task
->total_system_time
, &secs
, &usecs
);
4796 basic_info
->system_time
.seconds
=
4797 (typeof(basic_info
->system_time
.seconds
))secs
;
4798 basic_info
->system_time
.microseconds
= usecs
;
4800 *task_info_count
= TASK_BASIC_INFO_64_COUNT
;
4803 #endif /* defined(__arm__) || defined(__arm64__) */
4805 case MACH_TASK_BASIC_INFO
:
4807 mach_task_basic_info_t basic_info
;
4812 if (*task_info_count
< MACH_TASK_BASIC_INFO_COUNT
) {
4813 error
= KERN_INVALID_ARGUMENT
;
4817 basic_info
= (mach_task_basic_info_t
)task_info_out
;
4819 map
= (task
== kernel_task
) ? kernel_map
: task
->map
;
4821 basic_info
->virtual_size
= vm_map_adjusted_size(map
);
4823 basic_info
->resident_size
=
4824 (mach_vm_size_t
)(pmap_resident_count(map
->pmap
));
4825 basic_info
->resident_size
*= PAGE_SIZE_64
;
4827 basic_info
->resident_size_max
=
4828 (mach_vm_size_t
)(pmap_resident_max(map
->pmap
));
4829 basic_info
->resident_size_max
*= PAGE_SIZE_64
;
4831 basic_info
->policy
= ((task
!= kernel_task
) ?
4832 POLICY_TIMESHARE
: POLICY_RR
);
4834 basic_info
->suspend_count
= task
->user_stop_count
;
4836 absolutetime_to_microtime(task
->total_user_time
, &secs
, &usecs
);
4837 basic_info
->user_time
.seconds
=
4838 (typeof(basic_info
->user_time
.seconds
))secs
;
4839 basic_info
->user_time
.microseconds
= usecs
;
4841 absolutetime_to_microtime(task
->total_system_time
, &secs
, &usecs
);
4842 basic_info
->system_time
.seconds
=
4843 (typeof(basic_info
->system_time
.seconds
))secs
;
4844 basic_info
->system_time
.microseconds
= usecs
;
4846 *task_info_count
= MACH_TASK_BASIC_INFO_COUNT
;
4850 case TASK_THREAD_TIMES_INFO
:
4852 task_thread_times_info_t times_info
;
4855 if (*task_info_count
< TASK_THREAD_TIMES_INFO_COUNT
) {
4856 error
= KERN_INVALID_ARGUMENT
;
4860 times_info
= (task_thread_times_info_t
) task_info_out
;
4861 times_info
->user_time
.seconds
= 0;
4862 times_info
->user_time
.microseconds
= 0;
4863 times_info
->system_time
.seconds
= 0;
4864 times_info
->system_time
.microseconds
= 0;
4867 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
4868 time_value_t user_time
, system_time
;
4870 if (thread
->options
& TH_OPT_IDLE_THREAD
) {
4874 thread_read_times(thread
, &user_time
, &system_time
, NULL
);
4876 time_value_add(×_info
->user_time
, &user_time
);
4877 time_value_add(×_info
->system_time
, &system_time
);
4880 *task_info_count
= TASK_THREAD_TIMES_INFO_COUNT
;
4884 case TASK_ABSOLUTETIME_INFO
:
4886 task_absolutetime_info_t info
;
4889 if (*task_info_count
< TASK_ABSOLUTETIME_INFO_COUNT
) {
4890 error
= KERN_INVALID_ARGUMENT
;
4894 info
= (task_absolutetime_info_t
)task_info_out
;
4895 info
->threads_user
= info
->threads_system
= 0;
4898 info
->total_user
= task
->total_user_time
;
4899 info
->total_system
= task
->total_system_time
;
4901 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
4905 if (thread
->options
& TH_OPT_IDLE_THREAD
) {
4910 thread_lock(thread
);
4912 tval
= timer_grab(&thread
->user_timer
);
4913 info
->threads_user
+= tval
;
4914 info
->total_user
+= tval
;
4916 tval
= timer_grab(&thread
->system_timer
);
4917 if (thread
->precise_user_kernel_time
) {
4918 info
->threads_system
+= tval
;
4919 info
->total_system
+= tval
;
4921 /* system_timer may represent either sys or user */
4922 info
->threads_user
+= tval
;
4923 info
->total_user
+= tval
;
4926 thread_unlock(thread
);
4931 *task_info_count
= TASK_ABSOLUTETIME_INFO_COUNT
;
4935 case TASK_DYLD_INFO
:
4937 task_dyld_info_t info
;
4940 * We added the format field to TASK_DYLD_INFO output. For
4941 * temporary backward compatibility, accept the fact that
4942 * clients may ask for the old version - distinquished by the
4943 * size of the expected result structure.
4945 #define TASK_LEGACY_DYLD_INFO_COUNT \
4946 offsetof(struct task_dyld_info, all_image_info_format)/sizeof(natural_t)
4948 if (*task_info_count
< TASK_LEGACY_DYLD_INFO_COUNT
) {
4949 error
= KERN_INVALID_ARGUMENT
;
4953 info
= (task_dyld_info_t
)task_info_out
;
4954 info
->all_image_info_addr
= task
->all_image_info_addr
;
4955 info
->all_image_info_size
= task
->all_image_info_size
;
4957 /* only set format on output for those expecting it */
4958 if (*task_info_count
>= TASK_DYLD_INFO_COUNT
) {
4959 info
->all_image_info_format
= task_has_64Bit_addr(task
) ?
4960 TASK_DYLD_ALL_IMAGE_INFO_64
:
4961 TASK_DYLD_ALL_IMAGE_INFO_32
;
4962 *task_info_count
= TASK_DYLD_INFO_COUNT
;
4964 *task_info_count
= TASK_LEGACY_DYLD_INFO_COUNT
;
4969 case TASK_EXTMOD_INFO
:
4971 task_extmod_info_t info
;
4974 if (*task_info_count
< TASK_EXTMOD_INFO_COUNT
) {
4975 error
= KERN_INVALID_ARGUMENT
;
4979 info
= (task_extmod_info_t
)task_info_out
;
4981 p
= get_bsdtask_info(task
);
4983 proc_getexecutableuuid(p
, info
->task_uuid
, sizeof(info
->task_uuid
));
4985 bzero(info
->task_uuid
, sizeof(info
->task_uuid
));
4987 info
->extmod_statistics
= task
->extmod_statistics
;
4988 *task_info_count
= TASK_EXTMOD_INFO_COUNT
;
4993 case TASK_KERNELMEMORY_INFO
:
4995 task_kernelmemory_info_t tkm_info
;
4996 ledger_amount_t credit
, debit
;
4998 if (*task_info_count
< TASK_KERNELMEMORY_INFO_COUNT
) {
4999 error
= KERN_INVALID_ARGUMENT
;
5003 tkm_info
= (task_kernelmemory_info_t
) task_info_out
;
5004 tkm_info
->total_palloc
= 0;
5005 tkm_info
->total_pfree
= 0;
5006 tkm_info
->total_salloc
= 0;
5007 tkm_info
->total_sfree
= 0;
5009 if (task
== kernel_task
) {
5011 * All shared allocs/frees from other tasks count against
5012 * the kernel private memory usage. If we are looking up
5013 * info for the kernel task, gather from everywhere.
5017 /* start by accounting for all the terminated tasks against the kernel */
5018 tkm_info
->total_palloc
= tasks_tkm_private
.alloc
+ tasks_tkm_shared
.alloc
;
5019 tkm_info
->total_pfree
= tasks_tkm_private
.free
+ tasks_tkm_shared
.free
;
5021 /* count all other task/thread shared alloc/free against the kernel */
5022 lck_mtx_lock(&tasks_threads_lock
);
5024 /* XXX this really shouldn't be using the function parameter 'task' as a local var! */
5025 queue_iterate(&tasks
, task
, task_t
, tasks
) {
5026 if (task
== kernel_task
) {
5027 if (ledger_get_entries(task
->ledger
,
5028 task_ledgers
.tkm_private
, &credit
,
5029 &debit
) == KERN_SUCCESS
) {
5030 tkm_info
->total_palloc
+= credit
;
5031 tkm_info
->total_pfree
+= debit
;
5034 if (!ledger_get_entries(task
->ledger
,
5035 task_ledgers
.tkm_shared
, &credit
, &debit
)) {
5036 tkm_info
->total_palloc
+= credit
;
5037 tkm_info
->total_pfree
+= debit
;
5040 lck_mtx_unlock(&tasks_threads_lock
);
5042 if (!ledger_get_entries(task
->ledger
,
5043 task_ledgers
.tkm_private
, &credit
, &debit
)) {
5044 tkm_info
->total_palloc
= credit
;
5045 tkm_info
->total_pfree
= debit
;
5047 if (!ledger_get_entries(task
->ledger
,
5048 task_ledgers
.tkm_shared
, &credit
, &debit
)) {
5049 tkm_info
->total_salloc
= credit
;
5050 tkm_info
->total_sfree
= debit
;
5055 *task_info_count
= TASK_KERNELMEMORY_INFO_COUNT
;
5056 return KERN_SUCCESS
;
5060 case TASK_SCHED_FIFO_INFO
:
5062 if (*task_info_count
< POLICY_FIFO_BASE_COUNT
) {
5063 error
= KERN_INVALID_ARGUMENT
;
5067 error
= KERN_INVALID_POLICY
;
5072 case TASK_SCHED_RR_INFO
:
5074 policy_rr_base_t rr_base
;
5075 uint32_t quantum_time
;
5076 uint64_t quantum_ns
;
5078 if (*task_info_count
< POLICY_RR_BASE_COUNT
) {
5079 error
= KERN_INVALID_ARGUMENT
;
5083 rr_base
= (policy_rr_base_t
) task_info_out
;
5085 if (task
!= kernel_task
) {
5086 error
= KERN_INVALID_POLICY
;
5090 rr_base
->base_priority
= task
->priority
;
5092 quantum_time
= SCHED(initial_quantum_size
)(THREAD_NULL
);
5093 absolutetime_to_nanoseconds(quantum_time
, &quantum_ns
);
5095 rr_base
->quantum
= (uint32_t)(quantum_ns
/ 1000 / 1000);
5097 *task_info_count
= POLICY_RR_BASE_COUNT
;
5102 case TASK_SCHED_TIMESHARE_INFO
:
5104 policy_timeshare_base_t ts_base
;
5106 if (*task_info_count
< POLICY_TIMESHARE_BASE_COUNT
) {
5107 error
= KERN_INVALID_ARGUMENT
;
5111 ts_base
= (policy_timeshare_base_t
) task_info_out
;
5113 if (task
== kernel_task
) {
5114 error
= KERN_INVALID_POLICY
;
5118 ts_base
->base_priority
= task
->priority
;
5120 *task_info_count
= POLICY_TIMESHARE_BASE_COUNT
;
5124 case TASK_SECURITY_TOKEN
:
5126 security_token_t
*sec_token_p
;
5128 if (*task_info_count
< TASK_SECURITY_TOKEN_COUNT
) {
5129 error
= KERN_INVALID_ARGUMENT
;
5133 sec_token_p
= (security_token_t
*) task_info_out
;
5135 *sec_token_p
= task
->sec_token
;
5137 *task_info_count
= TASK_SECURITY_TOKEN_COUNT
;
5141 case TASK_AUDIT_TOKEN
:
5143 audit_token_t
*audit_token_p
;
5145 if (*task_info_count
< TASK_AUDIT_TOKEN_COUNT
) {
5146 error
= KERN_INVALID_ARGUMENT
;
5150 audit_token_p
= (audit_token_t
*) task_info_out
;
5152 *audit_token_p
= task
->audit_token
;
5154 *task_info_count
= TASK_AUDIT_TOKEN_COUNT
;
5158 case TASK_SCHED_INFO
:
5159 error
= KERN_INVALID_ARGUMENT
;
5162 case TASK_EVENTS_INFO
:
5164 task_events_info_t events_info
;
5167 if (*task_info_count
< TASK_EVENTS_INFO_COUNT
) {
5168 error
= KERN_INVALID_ARGUMENT
;
5172 events_info
= (task_events_info_t
) task_info_out
;
5175 events_info
->faults
= (int32_t) MIN(counter_load(&task
->faults
), INT32_MAX
);
5176 events_info
->pageins
= task
->pageins
;
5177 events_info
->cow_faults
= task
->cow_faults
;
5178 events_info
->messages_sent
= task
->messages_sent
;
5179 events_info
->messages_received
= task
->messages_received
;
5180 events_info
->syscalls_mach
= task
->syscalls_mach
;
5181 events_info
->syscalls_unix
= task
->syscalls_unix
;
5183 events_info
->csw
= task
->c_switch
;
5185 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
5186 events_info
->csw
+= thread
->c_switch
;
5187 events_info
->syscalls_mach
+= thread
->syscalls_mach
;
5188 events_info
->syscalls_unix
+= thread
->syscalls_unix
;
5192 *task_info_count
= TASK_EVENTS_INFO_COUNT
;
5195 case TASK_AFFINITY_TAG_INFO
:
5197 if (*task_info_count
< TASK_AFFINITY_TAG_INFO_COUNT
) {
5198 error
= KERN_INVALID_ARGUMENT
;
5202 error
= task_affinity_info(task
, task_info_out
, task_info_count
);
5205 case TASK_POWER_INFO
:
5207 if (*task_info_count
< TASK_POWER_INFO_COUNT
) {
5208 error
= KERN_INVALID_ARGUMENT
;
5212 task_power_info_locked(task
, (task_power_info_t
)task_info_out
, NULL
, NULL
, NULL
);
5216 case TASK_POWER_INFO_V2
:
5218 if (*task_info_count
< TASK_POWER_INFO_V2_COUNT_OLD
) {
5219 error
= KERN_INVALID_ARGUMENT
;
5222 task_power_info_v2_t tpiv2
= (task_power_info_v2_t
) task_info_out
;
5223 task_power_info_locked(task
, &tpiv2
->cpu_energy
, &tpiv2
->gpu_energy
, tpiv2
, NULL
);
5228 case TASK_VM_INFO_PURGEABLE
:
5230 task_vm_info_t vm_info
;
5235 uint32_t platform
, sdk
;
5237 platform
= proc_platform(p
);
5238 sdk
= proc_min_sdk(p
);
5239 if (original_task_info_count
> TASK_VM_INFO_REV2_COUNT
&&
5240 platform
== PLATFORM_IOS
&&
5242 (sdk
>> 16) <= 12) {
5244 * Some iOS apps pass an incorrect value for
5245 * task_info_count, expressed in number of bytes
5246 * instead of number of "natural_t" elements.
5247 * For the sake of backwards binary compatibility
5248 * for apps built with an iOS12 or older SDK and using
5249 * the "rev2" data structure, let's fix task_info_count
5250 * for them, to avoid stomping past the actual end
5253 #if DEVELOPMENT || DEBUG
5254 printf("%s:%d %d[%s] rdar://49484582 task_info_count %d -> %d platform %d sdk %d.%d.%d\n", __FUNCTION__
, __LINE__
, proc_pid(p
), proc_name_address(p
), original_task_info_count
, TASK_VM_INFO_REV2_COUNT
, platform
, (sdk
>> 16), ((sdk
>> 8) & 0xff), (sdk
& 0xff));
5255 #endif /* DEVELOPMENT || DEBUG */
5256 DTRACE_VM4(workaround_task_vm_info_count
,
5257 mach_msg_type_number_t
, original_task_info_count
,
5258 mach_msg_type_number_t
, TASK_VM_INFO_REV2_COUNT
,
5261 original_task_info_count
= TASK_VM_INFO_REV2_COUNT
;
5262 *task_info_count
= original_task_info_count
;
5264 #endif /* __arm64__ */
5266 if (*task_info_count
< TASK_VM_INFO_REV0_COUNT
) {
5267 error
= KERN_INVALID_ARGUMENT
;
5271 vm_info
= (task_vm_info_t
)task_info_out
;
5274 * Do not hold both the task and map locks,
5275 * so convert the task lock into a map reference,
5276 * drop the task lock, then lock the map.
5278 if (is_kernel_task
) {
5281 /* no lock, no reference */
5284 vm_map_reference(map
);
5286 vm_map_lock_read(map
);
5289 vm_info
->virtual_size
= (typeof(vm_info
->virtual_size
))vm_map_adjusted_size(map
);
5290 vm_info
->region_count
= map
->hdr
.nentries
;
5291 vm_info
->page_size
= vm_map_page_size(map
);
5293 vm_info
->resident_size
= pmap_resident_count(map
->pmap
);
5294 vm_info
->resident_size
*= PAGE_SIZE
;
5295 vm_info
->resident_size_peak
= pmap_resident_max(map
->pmap
);
5296 vm_info
->resident_size_peak
*= PAGE_SIZE
;
5298 #define _VM_INFO(_name) \
5299 vm_info->_name = ((mach_vm_size_t) map->pmap->stats._name) * PAGE_SIZE
5302 _VM_INFO(device_peak
);
5304 _VM_INFO(external_peak
);
5306 _VM_INFO(internal_peak
);
5308 _VM_INFO(reusable_peak
);
5309 _VM_INFO(compressed
);
5310 _VM_INFO(compressed_peak
);
5311 _VM_INFO(compressed_lifetime
);
5313 vm_info
->purgeable_volatile_pmap
= 0;
5314 vm_info
->purgeable_volatile_resident
= 0;
5315 vm_info
->purgeable_volatile_virtual
= 0;
5316 if (is_kernel_task
) {
5318 * We do not maintain the detailed stats for the
5319 * kernel_pmap, so just count everything as
5322 vm_info
->internal
= vm_info
->resident_size
;
5324 * ... but since the memory held by the VM compressor
5325 * in the kernel address space ought to be attributed
5326 * to user-space tasks, we subtract it from "internal"
5327 * to give memory reporting tools a more accurate idea
5328 * of what the kernel itself is actually using, instead
5329 * of making it look like the kernel is leaking memory
5330 * when the system is under memory pressure.
5332 vm_info
->internal
-= (VM_PAGE_COMPRESSOR_COUNT
*
5335 mach_vm_size_t volatile_virtual_size
;
5336 mach_vm_size_t volatile_resident_size
;
5337 mach_vm_size_t volatile_compressed_size
;
5338 mach_vm_size_t volatile_pmap_size
;
5339 mach_vm_size_t volatile_compressed_pmap_size
;
5342 if (flavor
== TASK_VM_INFO_PURGEABLE
) {
5343 kr
= vm_map_query_volatile(
5345 &volatile_virtual_size
,
5346 &volatile_resident_size
,
5347 &volatile_compressed_size
,
5348 &volatile_pmap_size
,
5349 &volatile_compressed_pmap_size
);
5350 if (kr
== KERN_SUCCESS
) {
5351 vm_info
->purgeable_volatile_pmap
=
5353 if (radar_20146450
) {
5354 vm_info
->compressed
-=
5355 volatile_compressed_pmap_size
;
5357 vm_info
->purgeable_volatile_resident
=
5358 volatile_resident_size
;
5359 vm_info
->purgeable_volatile_virtual
=
5360 volatile_virtual_size
;
5364 *task_info_count
= TASK_VM_INFO_REV0_COUNT
;
5366 if (original_task_info_count
>= TASK_VM_INFO_REV2_COUNT
) {
5367 /* must be captured while we still have the map lock */
5368 vm_info
->min_address
= map
->min_offset
;
5369 vm_info
->max_address
= map
->max_offset
;
5373 * Done with vm map things, can drop the map lock and reference,
5374 * and take the task lock back.
5376 * Re-validate that the task didn't die on us.
5378 if (!is_kernel_task
) {
5379 vm_map_unlock_read(map
);
5380 vm_map_deallocate(map
);
5386 if ((task
!= current_task()) && (!task
->active
)) {
5387 error
= KERN_INVALID_ARGUMENT
;
5391 if (original_task_info_count
>= TASK_VM_INFO_REV1_COUNT
) {
5392 vm_info
->phys_footprint
=
5393 (mach_vm_size_t
) get_task_phys_footprint(task
);
5394 *task_info_count
= TASK_VM_INFO_REV1_COUNT
;
5396 if (original_task_info_count
>= TASK_VM_INFO_REV2_COUNT
) {
5397 /* data was captured above */
5398 *task_info_count
= TASK_VM_INFO_REV2_COUNT
;
5401 if (original_task_info_count
>= TASK_VM_INFO_REV3_COUNT
) {
5402 ledger_get_lifetime_max(task
->ledger
,
5403 task_ledgers
.phys_footprint
,
5404 &vm_info
->ledger_phys_footprint_peak
);
5405 ledger_get_balance(task
->ledger
,
5406 task_ledgers
.purgeable_nonvolatile
,
5407 &vm_info
->ledger_purgeable_nonvolatile
);
5408 ledger_get_balance(task
->ledger
,
5409 task_ledgers
.purgeable_nonvolatile_compressed
,
5410 &vm_info
->ledger_purgeable_novolatile_compressed
);
5411 ledger_get_balance(task
->ledger
,
5412 task_ledgers
.purgeable_volatile
,
5413 &vm_info
->ledger_purgeable_volatile
);
5414 ledger_get_balance(task
->ledger
,
5415 task_ledgers
.purgeable_volatile_compressed
,
5416 &vm_info
->ledger_purgeable_volatile_compressed
);
5417 ledger_get_balance(task
->ledger
,
5418 task_ledgers
.network_nonvolatile
,
5419 &vm_info
->ledger_tag_network_nonvolatile
);
5420 ledger_get_balance(task
->ledger
,
5421 task_ledgers
.network_nonvolatile_compressed
,
5422 &vm_info
->ledger_tag_network_nonvolatile_compressed
);
5423 ledger_get_balance(task
->ledger
,
5424 task_ledgers
.network_volatile
,
5425 &vm_info
->ledger_tag_network_volatile
);
5426 ledger_get_balance(task
->ledger
,
5427 task_ledgers
.network_volatile_compressed
,
5428 &vm_info
->ledger_tag_network_volatile_compressed
);
5429 ledger_get_balance(task
->ledger
,
5430 task_ledgers
.media_footprint
,
5431 &vm_info
->ledger_tag_media_footprint
);
5432 ledger_get_balance(task
->ledger
,
5433 task_ledgers
.media_footprint_compressed
,
5434 &vm_info
->ledger_tag_media_footprint_compressed
);
5435 ledger_get_balance(task
->ledger
,
5436 task_ledgers
.media_nofootprint
,
5437 &vm_info
->ledger_tag_media_nofootprint
);
5438 ledger_get_balance(task
->ledger
,
5439 task_ledgers
.media_nofootprint_compressed
,
5440 &vm_info
->ledger_tag_media_nofootprint_compressed
);
5441 ledger_get_balance(task
->ledger
,
5442 task_ledgers
.graphics_footprint
,
5443 &vm_info
->ledger_tag_graphics_footprint
);
5444 ledger_get_balance(task
->ledger
,
5445 task_ledgers
.graphics_footprint_compressed
,
5446 &vm_info
->ledger_tag_graphics_footprint_compressed
);
5447 ledger_get_balance(task
->ledger
,
5448 task_ledgers
.graphics_nofootprint
,
5449 &vm_info
->ledger_tag_graphics_nofootprint
);
5450 ledger_get_balance(task
->ledger
,
5451 task_ledgers
.graphics_nofootprint_compressed
,
5452 &vm_info
->ledger_tag_graphics_nofootprint_compressed
);
5453 ledger_get_balance(task
->ledger
,
5454 task_ledgers
.neural_footprint
,
5455 &vm_info
->ledger_tag_neural_footprint
);
5456 ledger_get_balance(task
->ledger
,
5457 task_ledgers
.neural_footprint_compressed
,
5458 &vm_info
->ledger_tag_neural_footprint_compressed
);
5459 ledger_get_balance(task
->ledger
,
5460 task_ledgers
.neural_nofootprint
,
5461 &vm_info
->ledger_tag_neural_nofootprint
);
5462 ledger_get_balance(task
->ledger
,
5463 task_ledgers
.neural_nofootprint_compressed
,
5464 &vm_info
->ledger_tag_neural_nofootprint_compressed
);
5465 *task_info_count
= TASK_VM_INFO_REV3_COUNT
;
5467 if (original_task_info_count
>= TASK_VM_INFO_REV4_COUNT
) {
5468 if (task
->bsd_info
) {
5469 vm_info
->limit_bytes_remaining
=
5470 memorystatus_available_memory_internal(task
->bsd_info
);
5472 vm_info
->limit_bytes_remaining
= 0;
5474 *task_info_count
= TASK_VM_INFO_REV4_COUNT
;
5476 if (original_task_info_count
>= TASK_VM_INFO_REV5_COUNT
) {
5478 integer_t total
= task
->decompressions
;
5479 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
5480 total
+= thread
->decompressions
;
5482 vm_info
->decompressions
= total
;
5483 *task_info_count
= TASK_VM_INFO_REV5_COUNT
;
5489 case TASK_WAIT_STATE_INFO
:
5492 * Deprecated flavor. Currently allowing some results until all users
5493 * stop calling it. The results may not be accurate.
5495 task_wait_state_info_t wait_state_info
;
5496 uint64_t total_sfi_ledger_val
= 0;
5498 if (*task_info_count
< TASK_WAIT_STATE_INFO_COUNT
) {
5499 error
= KERN_INVALID_ARGUMENT
;
5503 wait_state_info
= (task_wait_state_info_t
) task_info_out
;
5505 wait_state_info
->total_wait_state_time
= 0;
5506 bzero(wait_state_info
->_reserved
, sizeof(wait_state_info
->_reserved
));
5508 #if CONFIG_SCHED_SFI
5509 int i
, prev_lentry
= -1;
5510 int64_t val_credit
, val_debit
;
5512 for (i
= 0; i
< MAX_SFI_CLASS_ID
; i
++) {
5515 * checking with prev_lentry != entry ensures adjacent classes
5516 * which share the same ledger do not add wait times twice.
5517 * Note: Use ledger() call to get data for each individual sfi class.
5519 if (prev_lentry
!= task_ledgers
.sfi_wait_times
[i
] &&
5520 KERN_SUCCESS
== ledger_get_entries(task
->ledger
,
5521 task_ledgers
.sfi_wait_times
[i
], &val_credit
, &val_debit
)) {
5522 total_sfi_ledger_val
+= val_credit
;
5524 prev_lentry
= task_ledgers
.sfi_wait_times
[i
];
5527 #endif /* CONFIG_SCHED_SFI */
5528 wait_state_info
->total_wait_sfi_state_time
= total_sfi_ledger_val
;
5529 *task_info_count
= TASK_WAIT_STATE_INFO_COUNT
;
5533 case TASK_VM_INFO_PURGEABLE_ACCOUNT
:
5535 #if DEVELOPMENT || DEBUG
5536 pvm_account_info_t acnt_info
;
5538 if (*task_info_count
< PVM_ACCOUNT_INFO_COUNT
) {
5539 error
= KERN_INVALID_ARGUMENT
;
5543 if (task_info_out
== NULL
) {
5544 error
= KERN_INVALID_ARGUMENT
;
5548 acnt_info
= (pvm_account_info_t
) task_info_out
;
5550 error
= vm_purgeable_account(task
, acnt_info
);
5552 *task_info_count
= PVM_ACCOUNT_INFO_COUNT
;
5555 #else /* DEVELOPMENT || DEBUG */
5556 error
= KERN_NOT_SUPPORTED
;
5558 #endif /* DEVELOPMENT || DEBUG */
5560 case TASK_FLAGS_INFO
:
5562 task_flags_info_t flags_info
;
5564 if (*task_info_count
< TASK_FLAGS_INFO_COUNT
) {
5565 error
= KERN_INVALID_ARGUMENT
;
5569 flags_info
= (task_flags_info_t
)task_info_out
;
5571 /* only publish the 64-bit flag of the task */
5572 flags_info
->flags
= task
->t_flags
& (TF_64B_ADDR
| TF_64B_DATA
);
5574 *task_info_count
= TASK_FLAGS_INFO_COUNT
;
5578 case TASK_DEBUG_INFO_INTERNAL
:
5580 #if DEVELOPMENT || DEBUG
5581 task_debug_info_internal_t dbg_info
;
5582 ipc_space_t space
= task
->itk_space
;
5583 if (*task_info_count
< TASK_DEBUG_INFO_INTERNAL_COUNT
) {
5584 error
= KERN_NOT_SUPPORTED
;
5588 if (task_info_out
== NULL
) {
5589 error
= KERN_INVALID_ARGUMENT
;
5592 dbg_info
= (task_debug_info_internal_t
) task_info_out
;
5593 dbg_info
->ipc_space_size
= 0;
5596 is_read_lock(space
);
5597 dbg_info
->ipc_space_size
= space
->is_table_size
;
5598 is_read_unlock(space
);
5601 dbg_info
->suspend_count
= task
->suspend_count
;
5603 error
= KERN_SUCCESS
;
5604 *task_info_count
= TASK_DEBUG_INFO_INTERNAL_COUNT
;
5606 #else /* DEVELOPMENT || DEBUG */
5607 error
= KERN_NOT_SUPPORTED
;
5609 #endif /* DEVELOPMENT || DEBUG */
5612 error
= KERN_INVALID_ARGUMENT
;
5620 * task_info_from_user
5622 * When calling task_info from user space,
5623 * this function will be executed as mig server side
5624 * instead of calling directly into task_info.
5625 * This gives the possibility to perform more security
5626 * checks on task_port.
5628 * In the case of TASK_DYLD_INFO, we require the more
5629 * privileged task_read_port not the less-privileged task_name_port.
5633 task_info_from_user(
5634 mach_port_t task_port
,
5635 task_flavor_t flavor
,
5636 task_info_t task_info_out
,
5637 mach_msg_type_number_t
*task_info_count
)
5642 if (flavor
== TASK_DYLD_INFO
) {
5643 task
= convert_port_to_task_read(task_port
);
5645 task
= convert_port_to_task_name(task_port
);
5648 ret
= task_info(task
, flavor
, task_info_out
, task_info_count
);
5650 task_deallocate(task
);
5656 * Routine: task_dyld_process_info_update_helper
5658 * Release send rights in release_ports.
5660 * If no active ports found in task's dyld notifier array, unset the magic value
5661 * in user space to indicate so.
5664 * task's itk_lock is locked, and is unlocked upon return.
5665 * Global g_dyldinfo_mtx is locked, and is unlocked upon return.
5668 task_dyld_process_info_update_helper(
5670 size_t active_count
,
5671 vm_map_address_t magic_addr
, /* a userspace address */
5672 ipc_port_t
*release_ports
,
5673 size_t release_count
)
5675 void *notifiers_ptr
= NULL
;
5677 assert(release_count
<= DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT
);
5679 if (active_count
== 0) {
5680 assert(task
->itk_dyld_notify
!= NULL
);
5681 notifiers_ptr
= task
->itk_dyld_notify
;
5682 task
->itk_dyld_notify
= NULL
;
5685 kfree(notifiers_ptr
, (vm_size_t
)sizeof(ipc_port_t
) * DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT
);
5686 (void)copyoutmap_atomic32(task
->map
, MACH_PORT_NULL
, magic_addr
); /* unset magic */
5689 (void)copyoutmap_atomic32(task
->map
, (mach_port_name_t
)DYLD_PROCESS_INFO_NOTIFY_MAGIC
,
5690 magic_addr
); /* reset magic */
5693 lck_mtx_unlock(&g_dyldinfo_mtx
);
5695 for (size_t i
= 0; i
< release_count
; i
++) {
5696 ipc_port_release_send(release_ports
[i
]);
5701 * Routine: task_dyld_process_info_notify_register
5703 * Insert a send right to target task's itk_dyld_notify array. Allocate kernel
5704 * memory for the array if it's the first port to be registered. Also cleanup
5705 * any dead rights found in the array.
5707 * Consumes sright if returns KERN_SUCCESS, otherwise MIG will destroy it.
5710 * task: Target task for the registration.
5711 * sright: A send right.
5714 * KERN_SUCCESS: Registration succeeded.
5715 * KERN_INVALID_TASK: task is invalid.
5716 * KERN_INVALID_RIGHT: sright is invalid.
5717 * KERN_DENIED: Security policy denied this call.
5718 * KERN_RESOURCE_SHORTAGE: Kernel memory allocation failed.
5719 * KERN_NO_SPACE: No available notifier port slot left for this task.
5720 * KERN_RIGHT_EXISTS: The notifier port is already registered and active.
5722 * Other error code see task_info().
5725 * task_dyld_process_info_notify_get_trap() in mach_kernelrpc.c
5728 task_dyld_process_info_notify_register(
5732 struct task_dyld_info dyld_info
;
5733 mach_msg_type_number_t info_count
= TASK_DYLD_INFO_COUNT
;
5734 ipc_port_t release_ports
[DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT
];
5735 uint32_t release_count
= 0, active_count
= 0;
5736 mach_vm_address_t ports_addr
; /* a user space address */
5738 boolean_t right_exists
= false;
5739 ipc_port_t
*notifiers_ptr
= NULL
;
5742 if (task
== TASK_NULL
|| task
== kernel_task
) {
5743 return KERN_INVALID_TASK
;
5746 if (!IP_VALID(sright
)) {
5747 return KERN_INVALID_RIGHT
;
5751 if (mac_task_check_dyld_process_info_notify_register()) {
5756 kr
= task_info(task
, TASK_DYLD_INFO
, (task_info_t
)&dyld_info
, &info_count
);
5761 if (dyld_info
.all_image_info_format
== TASK_DYLD_ALL_IMAGE_INFO_32
) {
5762 ports_addr
= (mach_vm_address_t
)(dyld_info
.all_image_info_addr
+
5763 offsetof(struct user32_dyld_all_image_infos
, notifyMachPorts
));
5765 ports_addr
= (mach_vm_address_t
)(dyld_info
.all_image_info_addr
+
5766 offsetof(struct user64_dyld_all_image_infos
, notifyMachPorts
));
5769 if (task
->itk_dyld_notify
== NULL
) {
5770 notifiers_ptr
= (ipc_port_t
*)
5771 kalloc_flags(sizeof(ipc_port_t
) * DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT
, Z_ZERO
);
5772 if (!notifiers_ptr
) {
5773 return KERN_RESOURCE_SHORTAGE
;
5777 lck_mtx_lock(&g_dyldinfo_mtx
);
5780 if (task
->itk_dyld_notify
== NULL
) {
5781 task
->itk_dyld_notify
= notifiers_ptr
;
5782 notifiers_ptr
= NULL
;
5785 assert(task
->itk_dyld_notify
!= NULL
);
5786 /* First pass: clear dead names and check for duplicate registration */
5787 for (int slot
= 0; slot
< DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT
; slot
++) {
5788 portp
= &task
->itk_dyld_notify
[slot
];
5789 if (*portp
!= IPC_PORT_NULL
&& !ip_active(*portp
)) {
5790 release_ports
[release_count
++] = *portp
;
5791 *portp
= IPC_PORT_NULL
;
5792 } else if (*portp
== sright
) {
5793 /* the port is already registered and is active */
5794 right_exists
= true;
5797 if (*portp
!= IPC_PORT_NULL
) {
5803 /* skip second pass */
5804 kr
= KERN_RIGHT_EXISTS
;
5808 /* Second pass: register the port */
5810 for (int slot
= 0; slot
< DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT
; slot
++) {
5811 portp
= &task
->itk_dyld_notify
[slot
];
5812 if (*portp
== IPC_PORT_NULL
) {
5821 assert(active_count
> 0);
5823 task_dyld_process_info_update_helper(task
, active_count
,
5824 (vm_map_address_t
)ports_addr
, release_ports
, release_count
);
5825 /* itk_lock, g_dyldinfo_mtx are unlocked upon return */
5827 if (notifiers_ptr
) {
5828 kfree(notifiers_ptr
, sizeof(ipc_port_t
) * DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT
);
5835 * Routine: task_dyld_process_info_notify_deregister
5837 * Remove a send right in target task's itk_dyld_notify array matching the receive
5838 * right name passed in. Deallocate kernel memory for the array if it's the last port to
5839 * be deregistered, or all ports have died. Also cleanup any dead rights found in the array.
5841 * Does not consume any reference.
5844 * task: Target task for the deregistration.
5845 * rcv_name: The name denoting the receive right in caller's space.
5848 * KERN_SUCCESS: A matching entry found and degistration succeeded.
5849 * KERN_INVALID_TASK: task is invalid.
5850 * KERN_INVALID_NAME: name is invalid.
5851 * KERN_DENIED: Security policy denied this call.
5852 * KERN_FAILURE: A matching entry is not found.
5853 * KERN_INVALID_RIGHT: The name passed in does not represent a valid rcv right.
5855 * Other error code see task_info().
5858 * task_dyld_process_info_notify_get_trap() in mach_kernelrpc.c
5861 task_dyld_process_info_notify_deregister(
5863 mach_port_name_t rcv_name
)
5865 struct task_dyld_info dyld_info
;
5866 mach_msg_type_number_t info_count
= TASK_DYLD_INFO_COUNT
;
5867 ipc_port_t release_ports
[DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT
];
5868 uint32_t release_count
= 0, active_count
= 0;
5869 boolean_t port_found
= false;
5870 mach_vm_address_t ports_addr
; /* a user space address */
5875 if (task
== TASK_NULL
|| task
== kernel_task
) {
5876 return KERN_INVALID_TASK
;
5879 if (!MACH_PORT_VALID(rcv_name
)) {
5880 return KERN_INVALID_NAME
;
5884 if (mac_task_check_dyld_process_info_notify_register()) {
5889 kr
= task_info(task
, TASK_DYLD_INFO
, (task_info_t
)&dyld_info
, &info_count
);
5894 if (dyld_info
.all_image_info_format
== TASK_DYLD_ALL_IMAGE_INFO_32
) {
5895 ports_addr
= (mach_vm_address_t
)(dyld_info
.all_image_info_addr
+
5896 offsetof(struct user32_dyld_all_image_infos
, notifyMachPorts
));
5898 ports_addr
= (mach_vm_address_t
)(dyld_info
.all_image_info_addr
+
5899 offsetof(struct user64_dyld_all_image_infos
, notifyMachPorts
));
5902 kr
= ipc_port_translate_receive(current_space(), rcv_name
, &sright
); /* does not produce port ref */
5904 return KERN_INVALID_RIGHT
;
5907 ip_reference(sright
);
5910 assert(sright
!= IPC_PORT_NULL
);
5912 lck_mtx_lock(&g_dyldinfo_mtx
);
5915 if (task
->itk_dyld_notify
== NULL
) {
5917 lck_mtx_unlock(&g_dyldinfo_mtx
);
5919 return KERN_FAILURE
;
5922 for (int slot
= 0; slot
< DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT
; slot
++) {
5923 portp
= &task
->itk_dyld_notify
[slot
];
5924 if (*portp
== sright
) {
5925 release_ports
[release_count
++] = *portp
;
5926 *portp
= IPC_PORT_NULL
;
5928 } else if ((*portp
!= IPC_PORT_NULL
&& !ip_active(*portp
))) {
5929 release_ports
[release_count
++] = *portp
;
5930 *portp
= IPC_PORT_NULL
;
5933 if (*portp
!= IPC_PORT_NULL
) {
5938 task_dyld_process_info_update_helper(task
, active_count
,
5939 (vm_map_address_t
)ports_addr
, release_ports
, release_count
);
5940 /* itk_lock, g_dyldinfo_mtx are unlocked upon return */
5944 return port_found
? KERN_SUCCESS
: KERN_FAILURE
;
5950 * Returns power stats for the task.
5951 * Note: Called with task locked.
5954 task_power_info_locked(
5956 task_power_info_t info
,
5957 gpu_energy_data_t ginfo
,
5958 task_power_info_v2_t infov2
,
5959 uint64_t *runnable_time
)
5962 ledger_amount_t tmp
;
5964 uint64_t runnable_time_sum
= 0;
5966 task_lock_assert_owned(task
);
5968 ledger_get_entries(task
->ledger
, task_ledgers
.interrupt_wakeups
,
5969 (ledger_amount_t
*)&info
->task_interrupt_wakeups
, &tmp
);
5970 ledger_get_entries(task
->ledger
, task_ledgers
.platform_idle_wakeups
,
5971 (ledger_amount_t
*)&info
->task_platform_idle_wakeups
, &tmp
);
5973 info
->task_timer_wakeups_bin_1
= task
->task_timer_wakeups_bin_1
;
5974 info
->task_timer_wakeups_bin_2
= task
->task_timer_wakeups_bin_2
;
5976 info
->total_user
= task
->total_user_time
;
5977 info
->total_system
= task
->total_system_time
;
5978 runnable_time_sum
= task
->total_runnable_time
;
5980 #if defined(__arm__) || defined(__arm64__)
5982 infov2
->task_energy
= task
->task_energy
;
5984 #endif /* defined(__arm__) || defined(__arm64__) */
5987 ginfo
->task_gpu_utilisation
= task
->task_gpu_ns
;
5991 infov2
->task_ptime
= task
->total_ptime
;
5992 infov2
->task_pset_switches
= task
->ps_switch
;
5995 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
5999 if (thread
->options
& TH_OPT_IDLE_THREAD
) {
6004 thread_lock(thread
);
6006 info
->task_timer_wakeups_bin_1
+= thread
->thread_timer_wakeups_bin_1
;
6007 info
->task_timer_wakeups_bin_2
+= thread
->thread_timer_wakeups_bin_2
;
6009 #if defined(__arm__) || defined(__arm64__)
6011 infov2
->task_energy
+= ml_energy_stat(thread
);
6013 #endif /* defined(__arm__) || defined(__arm64__) */
6015 tval
= timer_grab(&thread
->user_timer
);
6016 info
->total_user
+= tval
;
6019 tval
= timer_grab(&thread
->ptime
);
6020 infov2
->task_ptime
+= tval
;
6021 infov2
->task_pset_switches
+= thread
->ps_switch
;
6024 tval
= timer_grab(&thread
->system_timer
);
6025 if (thread
->precise_user_kernel_time
) {
6026 info
->total_system
+= tval
;
6028 /* system_timer may represent either sys or user */
6029 info
->total_user
+= tval
;
6032 tval
= timer_grab(&thread
->runnable_timer
);
6034 runnable_time_sum
+= tval
;
6037 ginfo
->task_gpu_utilisation
+= ml_gpu_stat(thread
);
6039 thread_unlock(thread
);
6043 if (runnable_time
) {
6044 *runnable_time
= runnable_time_sum
;
6049 * task_gpu_utilisation
6051 * Returns the total gpu time used by the all the threads of the task
6052 * (both dead and alive)
6055 task_gpu_utilisation(
6058 uint64_t gpu_time
= 0;
6059 #if defined(__x86_64__)
6063 gpu_time
+= task
->task_gpu_ns
;
6065 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
6068 thread_lock(thread
);
6069 gpu_time
+= ml_gpu_stat(thread
);
6070 thread_unlock(thread
);
6075 #else /* defined(__x86_64__) */
6076 /* silence compiler warning */
6078 #endif /* defined(__x86_64__) */
6085 * Returns the total energy used by the all the threads of the task
6086 * (both dead and alive)
6092 uint64_t energy
= 0;
6096 energy
+= task
->task_energy
;
6098 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
6101 thread_lock(thread
);
6102 energy
+= ml_energy_stat(thread
);
6103 thread_unlock(thread
);
6117 uint64_t cpu_ptime
= 0;
6121 cpu_ptime
+= task
->total_ptime
;
6123 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
6124 cpu_ptime
+= timer_grab(&thread
->ptime
);
6135 __unused task_t task
)
6140 #endif /* __AMP__ */
6142 /* This function updates the cpu time in the arrays for each
6143 * effective and requested QoS class
6146 task_update_cpu_time_qos_stats(
6148 uint64_t *eqos_stats
,
6149 uint64_t *rqos_stats
)
6151 if (!eqos_stats
&& !rqos_stats
) {
6157 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
6158 if (thread
->options
& TH_OPT_IDLE_THREAD
) {
6162 thread_update_qos_cpu_time(thread
);
6166 eqos_stats
[THREAD_QOS_DEFAULT
] += task
->cpu_time_eqos_stats
.cpu_time_qos_default
;
6167 eqos_stats
[THREAD_QOS_MAINTENANCE
] += task
->cpu_time_eqos_stats
.cpu_time_qos_maintenance
;
6168 eqos_stats
[THREAD_QOS_BACKGROUND
] += task
->cpu_time_eqos_stats
.cpu_time_qos_background
;
6169 eqos_stats
[THREAD_QOS_UTILITY
] += task
->cpu_time_eqos_stats
.cpu_time_qos_utility
;
6170 eqos_stats
[THREAD_QOS_LEGACY
] += task
->cpu_time_eqos_stats
.cpu_time_qos_legacy
;
6171 eqos_stats
[THREAD_QOS_USER_INITIATED
] += task
->cpu_time_eqos_stats
.cpu_time_qos_user_initiated
;
6172 eqos_stats
[THREAD_QOS_USER_INTERACTIVE
] += task
->cpu_time_eqos_stats
.cpu_time_qos_user_interactive
;
6176 rqos_stats
[THREAD_QOS_DEFAULT
] += task
->cpu_time_rqos_stats
.cpu_time_qos_default
;
6177 rqos_stats
[THREAD_QOS_MAINTENANCE
] += task
->cpu_time_rqos_stats
.cpu_time_qos_maintenance
;
6178 rqos_stats
[THREAD_QOS_BACKGROUND
] += task
->cpu_time_rqos_stats
.cpu_time_qos_background
;
6179 rqos_stats
[THREAD_QOS_UTILITY
] += task
->cpu_time_rqos_stats
.cpu_time_qos_utility
;
6180 rqos_stats
[THREAD_QOS_LEGACY
] += task
->cpu_time_rqos_stats
.cpu_time_qos_legacy
;
6181 rqos_stats
[THREAD_QOS_USER_INITIATED
] += task
->cpu_time_rqos_stats
.cpu_time_qos_user_initiated
;
6182 rqos_stats
[THREAD_QOS_USER_INTERACTIVE
] += task
->cpu_time_rqos_stats
.cpu_time_qos_user_interactive
;
6191 task_purgable_info_t
*stats
)
6193 if (task
== TASK_NULL
|| stats
== NULL
) {
6194 return KERN_INVALID_ARGUMENT
;
6196 /* Take task reference */
6197 task_reference(task
);
6198 vm_purgeable_stats((vm_purgeable_info_t
)stats
, task
);
6199 /* Drop task reference */
6200 task_deallocate(task
);
6201 return KERN_SUCCESS
;
6214 task
->vtimers
|= which
;
6217 case TASK_VTIMER_USER
:
6218 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
6220 thread_lock(thread
);
6221 if (thread
->precise_user_kernel_time
) {
6222 thread
->vtimer_user_save
= timer_grab(&thread
->user_timer
);
6224 thread
->vtimer_user_save
= timer_grab(&thread
->system_timer
);
6226 thread_unlock(thread
);
6231 case TASK_VTIMER_PROF
:
6232 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
6234 thread_lock(thread
);
6235 thread
->vtimer_prof_save
= timer_grab(&thread
->user_timer
);
6236 thread
->vtimer_prof_save
+= timer_grab(&thread
->system_timer
);
6237 thread_unlock(thread
);
6242 case TASK_VTIMER_RLIM
:
6243 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
6245 thread_lock(thread
);
6246 thread
->vtimer_rlim_save
= timer_grab(&thread
->user_timer
);
6247 thread
->vtimer_rlim_save
+= timer_grab(&thread
->system_timer
);
6248 thread_unlock(thread
);
6262 assert(task
== current_task());
6266 task
->vtimers
&= ~which
;
6276 uint32_t *microsecs
)
6278 thread_t thread
= current_thread();
6280 clock_sec_t secs
= 0;
6283 assert(task
== current_task());
6285 spl_t s
= splsched();
6286 thread_lock(thread
);
6288 if ((task
->vtimers
& which
) != (uint32_t)which
) {
6289 thread_unlock(thread
);
6295 case TASK_VTIMER_USER
:
6296 if (thread
->precise_user_kernel_time
) {
6297 tdelt
= (uint32_t)timer_delta(&thread
->user_timer
,
6298 &thread
->vtimer_user_save
);
6300 tdelt
= (uint32_t)timer_delta(&thread
->system_timer
,
6301 &thread
->vtimer_user_save
);
6303 absolutetime_to_microtime(tdelt
, &secs
, microsecs
);
6306 case TASK_VTIMER_PROF
:
6307 tsum
= timer_grab(&thread
->user_timer
);
6308 tsum
+= timer_grab(&thread
->system_timer
);
6309 tdelt
= (uint32_t)(tsum
- thread
->vtimer_prof_save
);
6310 absolutetime_to_microtime(tdelt
, &secs
, microsecs
);
6311 /* if the time delta is smaller than a usec, ignore */
6312 if (*microsecs
!= 0) {
6313 thread
->vtimer_prof_save
= tsum
;
6317 case TASK_VTIMER_RLIM
:
6318 tsum
= timer_grab(&thread
->user_timer
);
6319 tsum
+= timer_grab(&thread
->system_timer
);
6320 tdelt
= (uint32_t)(tsum
- thread
->vtimer_rlim_save
);
6321 thread
->vtimer_rlim_save
= tsum
;
6322 absolutetime_to_microtime(tdelt
, &secs
, microsecs
);
6326 thread_unlock(thread
);
6333 * Change the assigned processor set for the task
6337 __unused task_t task
,
6338 __unused processor_set_t new_pset
,
6339 __unused boolean_t assign_threads
)
6341 return KERN_FAILURE
;
6345 * task_assign_default:
6347 * Version of task_assign to assign to default processor set.
6350 task_assign_default(
6352 boolean_t assign_threads
)
6354 return task_assign(task
, &pset0
, assign_threads
);
6358 * task_get_assignment
6360 * Return name of processor set that task is assigned to.
6363 task_get_assignment(
6365 processor_set_t
*pset
)
6367 if (!task
|| !task
->active
) {
6368 return KERN_FAILURE
;
6373 return KERN_SUCCESS
;
6377 get_task_dispatchqueue_offset(
6380 return task
->dispatchqueue_offset
;
6386 * Set scheduling policy and parameters, both base and limit, for
6387 * the given task. Policy must be a policy which is enabled for the
6388 * processor set. Change contained threads if requested.
6392 __unused task_t task
,
6393 __unused policy_t policy_id
,
6394 __unused policy_base_t base
,
6395 __unused mach_msg_type_number_t count
,
6396 __unused boolean_t set_limit
,
6397 __unused boolean_t change
)
6399 return KERN_FAILURE
;
6405 * Set scheduling policy and parameters, both base and limit, for
6406 * the given task. Policy can be any policy implemented by the
6407 * processor set, whether enabled or not. Change contained threads
6412 __unused task_t task
,
6413 __unused processor_set_t pset
,
6414 __unused policy_t policy_id
,
6415 __unused policy_base_t base
,
6416 __unused mach_msg_type_number_t base_count
,
6417 __unused policy_limit_t limit
,
6418 __unused mach_msg_type_number_t limit_count
,
6419 __unused boolean_t change
)
6421 return KERN_FAILURE
;
6426 __unused task_t task
,
6427 __unused vm_offset_t pc
,
6428 __unused vm_offset_t endpc
)
6430 return KERN_FAILURE
;
6434 task_synchronizer_destroy_all(task_t task
)
6437 * Destroy owned semaphores
6439 semaphore_destroy_all(task
);
6443 * Install default (machine-dependent) initial thread state
6444 * on the task. Subsequent thread creation will have this initial
6445 * state set on the thread by machine_thread_inherit_taskwide().
6446 * Flavors and structures are exactly the same as those to thread_set_state()
6452 thread_state_t state
,
6453 mach_msg_type_number_t state_count
)
6457 if (task
== TASK_NULL
) {
6458 return KERN_INVALID_ARGUMENT
;
6463 if (!task
->active
) {
6465 return KERN_FAILURE
;
6468 ret
= machine_task_set_state(task
, flavor
, state
, state_count
);
6475 * Examine the default (machine-dependent) initial thread state
6476 * on the task, as set by task_set_state(). Flavors and structures
6477 * are exactly the same as those passed to thread_get_state().
6483 thread_state_t state
,
6484 mach_msg_type_number_t
*state_count
)
6488 if (task
== TASK_NULL
) {
6489 return KERN_INVALID_ARGUMENT
;
6494 if (!task
->active
) {
6496 return KERN_FAILURE
;
6499 ret
= machine_task_get_state(task
, flavor
, state
, state_count
);
6506 static kern_return_t
__attribute__((noinline
, not_tail_called
))
6507 PROC_VIOLATED_GUARD__SEND_EXC_GUARD_AND_SUSPEND(
6508 mach_exception_code_t code
,
6509 mach_exception_subcode_t subcode
,
6513 if (1 == proc_selfpid()) {
6514 return KERN_NOT_SUPPORTED
; // initproc is immune
6517 mach_exception_data_type_t codes
[EXCEPTION_CODE_MAX
] = {
6521 task_t task
= current_task();
6524 /* (See jetsam-related comments below) */
6526 proc_memstat_terminated(task
->bsd_info
, TRUE
);
6527 kr
= task_enqueue_exception_with_corpse(task
, EXC_GUARD
, codes
, 2, reason
);
6528 proc_memstat_terminated(task
->bsd_info
, FALSE
);
6533 task_violated_guard(
6534 mach_exception_code_t code
,
6535 mach_exception_subcode_t subcode
,
6538 return PROC_VIOLATED_GUARD__SEND_EXC_GUARD_AND_SUSPEND(code
, subcode
, reason
);
6542 #if CONFIG_MEMORYSTATUS
6545 task_get_memlimit_is_active(task_t task
)
6547 assert(task
!= NULL
);
6549 if (task
->memlimit_is_active
== 1) {
6557 task_set_memlimit_is_active(task_t task
, boolean_t memlimit_is_active
)
6559 assert(task
!= NULL
);
6561 if (memlimit_is_active
) {
6562 task
->memlimit_is_active
= 1;
6564 task
->memlimit_is_active
= 0;
6569 task_get_memlimit_is_fatal(task_t task
)
6571 assert(task
!= NULL
);
6573 if (task
->memlimit_is_fatal
== 1) {
6581 task_set_memlimit_is_fatal(task_t task
, boolean_t memlimit_is_fatal
)
6583 assert(task
!= NULL
);
6585 if (memlimit_is_fatal
) {
6586 task
->memlimit_is_fatal
= 1;
6588 task
->memlimit_is_fatal
= 0;
6593 task_has_triggered_exc_resource(task_t task
, boolean_t memlimit_is_active
)
6595 boolean_t triggered
= FALSE
;
6597 assert(task
== current_task());
6600 * Returns true, if task has already triggered an exc_resource exception.
6603 if (memlimit_is_active
) {
6604 triggered
= (task
->memlimit_active_exc_resource
? TRUE
: FALSE
);
6606 triggered
= (task
->memlimit_inactive_exc_resource
? TRUE
: FALSE
);
6613 task_mark_has_triggered_exc_resource(task_t task
, boolean_t memlimit_is_active
)
6615 assert(task
== current_task());
6618 * We allow one exc_resource per process per active/inactive limit.
6619 * The limit's fatal attribute does not come into play.
6622 if (memlimit_is_active
) {
6623 task
->memlimit_active_exc_resource
= 1;
6625 task
->memlimit_inactive_exc_resource
= 1;
6629 #define HWM_USERCORE_MINSPACE 250 // free space (in MB) required *after* core file creation
6631 void __attribute__((noinline
))
6632 PROC_CROSSED_HIGH_WATERMARK__SEND_EXC_RESOURCE_AND_SUSPEND(int max_footprint_mb
, boolean_t is_fatal
)
6634 task_t task
= current_task();
6636 const char *procname
= "unknown";
6637 mach_exception_data_type_t code
[EXCEPTION_CODE_MAX
];
6638 boolean_t send_sync_exc_resource
= FALSE
;
6641 pid
= proc_selfpid();
6645 * Cannot have ReportCrash analyzing
6646 * a suspended initproc.
6651 if (task
->bsd_info
!= NULL
) {
6652 procname
= proc_name_address(current_task()->bsd_info
);
6653 send_sync_exc_resource
= proc_send_synchronous_EXC_RESOURCE(current_task()->bsd_info
);
6657 if (hwm_user_cores
) {
6659 uint64_t starttime
, end
;
6660 clock_sec_t secs
= 0;
6661 uint32_t microsecs
= 0;
6663 starttime
= mach_absolute_time();
6665 * Trigger a coredump of this process. Don't proceed unless we know we won't
6666 * be filling up the disk; and ignore the core size resource limit for this
6669 if ((error
= coredump(current_task()->bsd_info
, HWM_USERCORE_MINSPACE
, COREDUMP_IGNORE_ULIMIT
)) != 0) {
6670 printf("couldn't take coredump of %s[%d]: %d\n", procname
, pid
, error
);
6673 * coredump() leaves the task suspended.
6675 task_resume_internal(current_task());
6677 end
= mach_absolute_time();
6678 absolutetime_to_microtime(end
- starttime
, &secs
, µsecs
);
6679 printf("coredump of %s[%d] taken in %d secs %d microsecs\n",
6680 proc_name_address(current_task()->bsd_info
), pid
, (int)secs
, microsecs
);
6682 #endif /* CONFIG_COREDUMP */
6684 if (disable_exc_resource
) {
6685 printf("process %s[%d] crossed memory high watermark (%d MB); EXC_RESOURCE "
6686 "supressed by a boot-arg.\n", procname
, pid
, max_footprint_mb
);
6691 * A task that has triggered an EXC_RESOURCE, should not be
6692 * jetsammed when the device is under memory pressure. Here
6693 * we set the P_MEMSTAT_TERMINATED flag so that the process
6694 * will be skipped if the memorystatus_thread wakes up.
6696 proc_memstat_terminated(current_task()->bsd_info
, TRUE
);
6698 code
[0] = code
[1] = 0;
6699 EXC_RESOURCE_ENCODE_TYPE(code
[0], RESOURCE_TYPE_MEMORY
);
6700 EXC_RESOURCE_ENCODE_FLAVOR(code
[0], FLAVOR_HIGH_WATERMARK
);
6701 EXC_RESOURCE_HWM_ENCODE_LIMIT(code
[0], max_footprint_mb
);
6704 * Do not generate a corpse fork if the violation is a fatal one
6705 * or the process wants synchronous EXC_RESOURCE exceptions.
6707 if (is_fatal
|| send_sync_exc_resource
|| exc_via_corpse_forking
== 0) {
6708 /* Do not send a EXC_RESOURCE if corpse_for_fatal_memkill is set */
6709 if (send_sync_exc_resource
|| corpse_for_fatal_memkill
== 0) {
6711 * Use the _internal_ variant so that no user-space
6712 * process can resume our task from under us.
6714 task_suspend_internal(task
);
6715 exception_triage(EXC_RESOURCE
, code
, EXCEPTION_CODE_MAX
);
6716 task_resume_internal(task
);
6720 printf("process %s[%d] crossed memory high watermark (%d MB); EXC_RESOURCE "
6721 "supressed due to audio playback.\n", procname
, pid
, max_footprint_mb
);
6723 task_enqueue_exception_with_corpse(task
, EXC_RESOURCE
,
6724 code
, EXCEPTION_CODE_MAX
, NULL
);
6729 * After the EXC_RESOURCE has been handled, we must clear the
6730 * P_MEMSTAT_TERMINATED flag so that the process can again be
6731 * considered for jetsam if the memorystatus_thread wakes up.
6733 proc_memstat_terminated(current_task()->bsd_info
, FALSE
); /* clear the flag */
6737 * Callback invoked when a task exceeds its physical footprint limit.
6740 task_footprint_exceeded(int warning
, __unused
const void *param0
, __unused
const void *param1
)
6742 ledger_amount_t max_footprint
, max_footprint_mb
;
6744 boolean_t is_warning
;
6745 boolean_t memlimit_is_active
;
6746 boolean_t memlimit_is_fatal
;
6748 if (warning
== LEDGER_WARNING_DIPPED_BELOW
) {
6750 * Task memory limits only provide a warning on the way up.
6753 } else if (warning
== LEDGER_WARNING_ROSE_ABOVE
) {
6755 * This task is in danger of violating a memory limit,
6756 * It has exceeded a percentage level of the limit.
6761 * The task has exceeded the physical footprint limit.
6762 * This is not a warning but a true limit violation.
6767 task
= current_task();
6769 ledger_get_limit(task
->ledger
, task_ledgers
.phys_footprint
, &max_footprint
);
6770 max_footprint_mb
= max_footprint
>> 20;
6772 memlimit_is_active
= task_get_memlimit_is_active(task
);
6773 memlimit_is_fatal
= task_get_memlimit_is_fatal(task
);
6776 * If this is an actual violation (not a warning), then generate EXC_RESOURCE exception.
6777 * We only generate the exception once per process per memlimit (active/inactive limit).
6778 * To enforce this, we monitor state based on the memlimit's active/inactive attribute
6779 * and we disable it by marking that memlimit as exception triggered.
6781 if ((is_warning
== FALSE
) && (!task_has_triggered_exc_resource(task
, memlimit_is_active
))) {
6782 PROC_CROSSED_HIGH_WATERMARK__SEND_EXC_RESOURCE_AND_SUSPEND((int)max_footprint_mb
, memlimit_is_fatal
);
6783 memorystatus_log_exception((int)max_footprint_mb
, memlimit_is_active
, memlimit_is_fatal
);
6784 task_mark_has_triggered_exc_resource(task
, memlimit_is_active
);
6787 memorystatus_on_ledger_footprint_exceeded(is_warning
, memlimit_is_active
, memlimit_is_fatal
);
6790 extern int proc_check_footprint_priv(void);
6793 task_set_phys_footprint_limit(
6798 kern_return_t error
;
6800 boolean_t memlimit_is_active
;
6801 boolean_t memlimit_is_fatal
;
6803 if ((error
= proc_check_footprint_priv())) {
6804 return KERN_NO_ACCESS
;
6808 * This call should probably be obsoleted.
6809 * But for now, we default to current state.
6811 memlimit_is_active
= task_get_memlimit_is_active(task
);
6812 memlimit_is_fatal
= task_get_memlimit_is_fatal(task
);
6814 return task_set_phys_footprint_limit_internal(task
, new_limit_mb
, old_limit_mb
, memlimit_is_active
, memlimit_is_fatal
);
6818 task_convert_phys_footprint_limit(
6820 int *converted_limit_mb
)
6822 if (limit_mb
== -1) {
6826 if (max_task_footprint
!= 0) {
6827 *converted_limit_mb
= (int)(max_task_footprint
/ 1024 / 1024); /* bytes to MB */
6829 *converted_limit_mb
= (int)(LEDGER_LIMIT_INFINITY
>> 20);
6832 /* nothing to convert */
6833 *converted_limit_mb
= limit_mb
;
6835 return KERN_SUCCESS
;
6840 task_set_phys_footprint_limit_internal(
6844 boolean_t memlimit_is_active
,
6845 boolean_t memlimit_is_fatal
)
6847 ledger_amount_t old
;
6850 ret
= ledger_get_limit(task
->ledger
, task_ledgers
.phys_footprint
, &old
);
6852 if (ret
!= KERN_SUCCESS
) {
6857 * Check that limit >> 20 will not give an "unexpected" 32-bit
6858 * result. There are, however, implicit assumptions that -1 mb limit
6859 * equates to LEDGER_LIMIT_INFINITY.
6861 assert(((old
& 0xFFF0000000000000LL
) == 0) || (old
== LEDGER_LIMIT_INFINITY
));
6864 *old_limit_mb
= (int)(old
>> 20);
6867 if (new_limit_mb
== -1) {
6869 * Caller wishes to remove the limit.
6871 ledger_set_limit(task
->ledger
, task_ledgers
.phys_footprint
,
6872 max_task_footprint
? max_task_footprint
: LEDGER_LIMIT_INFINITY
,
6873 max_task_footprint
? (uint8_t)max_task_footprint_warning_level
: 0);
6876 task_set_memlimit_is_active(task
, memlimit_is_active
);
6877 task_set_memlimit_is_fatal(task
, memlimit_is_fatal
);
6880 return KERN_SUCCESS
;
6883 #ifdef CONFIG_NOMONITORS
6884 return KERN_SUCCESS
;
6885 #endif /* CONFIG_NOMONITORS */
6889 if ((memlimit_is_active
== task_get_memlimit_is_active(task
)) &&
6890 (memlimit_is_fatal
== task_get_memlimit_is_fatal(task
)) &&
6891 (((ledger_amount_t
)new_limit_mb
<< 20) == old
)) {
6893 * memlimit state is not changing
6896 return KERN_SUCCESS
;
6899 task_set_memlimit_is_active(task
, memlimit_is_active
);
6900 task_set_memlimit_is_fatal(task
, memlimit_is_fatal
);
6902 ledger_set_limit(task
->ledger
, task_ledgers
.phys_footprint
,
6903 (ledger_amount_t
)new_limit_mb
<< 20, PHYS_FOOTPRINT_WARNING_LEVEL
);
6905 if (task
== current_task()) {
6906 ledger_check_new_balance(current_thread(), task
->ledger
,
6907 task_ledgers
.phys_footprint
);
6912 return KERN_SUCCESS
;
6916 task_get_phys_footprint_limit(
6920 ledger_amount_t limit
;
6923 ret
= ledger_get_limit(task
->ledger
, task_ledgers
.phys_footprint
, &limit
);
6924 if (ret
!= KERN_SUCCESS
) {
6929 * Check that limit >> 20 will not give an "unexpected" signed, 32-bit
6930 * result. There are, however, implicit assumptions that -1 mb limit
6931 * equates to LEDGER_LIMIT_INFINITY.
6933 assert(((limit
& 0xFFF0000000000000LL
) == 0) || (limit
== LEDGER_LIMIT_INFINITY
));
6934 *limit_mb
= (int)(limit
>> 20);
6936 return KERN_SUCCESS
;
6938 #else /* CONFIG_MEMORYSTATUS */
6940 task_set_phys_footprint_limit(
6941 __unused task_t task
,
6942 __unused
int new_limit_mb
,
6943 __unused
int *old_limit_mb
)
6945 return KERN_FAILURE
;
6949 task_get_phys_footprint_limit(
6950 __unused task_t task
,
6951 __unused
int *limit_mb
)
6953 return KERN_FAILURE
;
6955 #endif /* CONFIG_MEMORYSTATUS */
6958 task_set_thread_limit(task_t task
, uint16_t thread_limit
)
6960 assert(task
!= kernel_task
);
6961 if (thread_limit
<= TASK_MAX_THREAD_LIMIT
) {
6963 task
->task_thread_limit
= thread_limit
;
6968 #if XNU_TARGET_OS_OSX
6970 task_has_system_version_compat_enabled(task_t task
)
6972 boolean_t enabled
= FALSE
;
6975 enabled
= (task
->t_flags
& TF_SYS_VERSION_COMPAT
);
6982 task_set_system_version_compat_enabled(task_t task
, boolean_t enable_system_version_compat
)
6984 assert(task
== current_task());
6985 assert(task
!= kernel_task
);
6988 if (enable_system_version_compat
) {
6989 task
->t_flags
|= TF_SYS_VERSION_COMPAT
;
6991 task
->t_flags
&= ~TF_SYS_VERSION_COMPAT
;
6995 #endif /* XNU_TARGET_OS_OSX */
6998 * We need to export some functions to other components that
6999 * are currently implemented in macros within the osfmk
7000 * component. Just export them as functions of the same name.
7003 is_kerneltask(task_t t
)
7005 if (t
== kernel_task
) {
7013 is_corpsetask(task_t t
)
7015 return task_is_a_corpse(t
);
7019 task_t
current_task(void);
7023 return current_task_fast();
7026 #undef task_reference
7027 void task_reference(task_t task
);
7032 if (task
!= TASK_NULL
) {
7033 task_reference_internal(task
);
7037 /* defined in bsd/kern/kern_prot.c */
7038 extern int get_audit_token_pid(audit_token_t
*audit_token
);
7041 task_pid(task_t task
)
7044 return get_audit_token_pid(&task
->audit_token
);
7049 #if __has_feature(ptrauth_calls)
7051 * Get the shared region id and jop signing key for the task.
7052 * The function will allocate a kalloc buffer and return
7053 * it to caller, the caller needs to free it. This is used
7054 * for getting the information via task port.
7057 task_get_vm_shared_region_id_and_jop_pid(task_t task
, uint64_t *jop_pid
)
7060 char *shared_region_id
= NULL
;
7063 if (task
->shared_region_id
== NULL
) {
7067 len
= strlen(task
->shared_region_id
) + 1;
7069 /* don't hold task lock while allocating */
7071 shared_region_id
= kheap_alloc(KHEAP_DATA_BUFFERS
, len
, Z_WAITOK
);
7074 if (task
->shared_region_id
== NULL
) {
7076 kheap_free(KHEAP_DATA_BUFFERS
, shared_region_id
, len
);
7079 assert(len
== strlen(task
->shared_region_id
) + 1); /* should never change */
7080 strlcpy(shared_region_id
, task
->shared_region_id
, len
);
7083 /* find key from its auth pager */
7084 if (jop_pid
!= NULL
) {
7085 *jop_pid
= shared_region_find_key(shared_region_id
);
7088 return shared_region_id
;
7092 * set the shared region id for a task
7095 task_set_shared_region_id(task_t task
, char *id
)
7100 old_id
= task
->shared_region_id
;
7101 task
->shared_region_id
= id
;
7102 task
->shared_region_auth_remapped
= FALSE
;
7105 /* free any pre-existing shared region id */
7106 if (old_id
!= NULL
) {
7107 shared_region_key_dealloc(old_id
);
7108 kheap_free(KHEAP_DATA_BUFFERS
, old_id
, strlen(old_id
) + 1);
7111 #endif /* __has_feature(ptrauth_calls) */
7114 * This routine finds a thread in a task by its unique id
7115 * Returns a referenced thread or THREAD_NULL if the thread was not found
7117 * TODO: This is super inefficient - it's an O(threads in task) list walk!
7118 * We should make a tid hash, or transition all tid clients to thread ports
7120 * Precondition: No locks held (will take task lock)
7123 task_findtid(task_t task
, uint64_t tid
)
7125 thread_t self
= current_thread();
7126 thread_t found_thread
= THREAD_NULL
;
7127 thread_t iter_thread
= THREAD_NULL
;
7129 /* Short-circuit the lookup if we're looking up ourselves */
7130 if (tid
== self
->thread_id
|| tid
== TID_NULL
) {
7131 assert(self
->task
== task
);
7133 thread_reference(self
);
7140 queue_iterate(&task
->threads
, iter_thread
, thread_t
, task_threads
) {
7141 if (iter_thread
->thread_id
== tid
) {
7142 found_thread
= iter_thread
;
7143 thread_reference(found_thread
);
7150 return found_thread
;
7154 pid_from_task(task_t task
)
7158 if (task
->bsd_info
) {
7159 pid
= proc_pid(task
->bsd_info
);
7161 pid
= task_pid(task
);
7168 * Control the CPU usage monitor for a task.
7171 task_cpu_usage_monitor_ctl(task_t task
, uint32_t *flags
)
7173 int error
= KERN_SUCCESS
;
7175 if (*flags
& CPUMON_MAKE_FATAL
) {
7176 task
->rusage_cpu_flags
|= TASK_RUSECPU_FLAGS_FATAL_CPUMON
;
7178 error
= KERN_INVALID_ARGUMENT
;
7185 * Control the wakeups monitor for a task.
7188 task_wakeups_monitor_ctl(task_t task
, uint32_t *flags
, int32_t *rate_hz
)
7190 ledger_t ledger
= task
->ledger
;
7193 if (*flags
& WAKEMON_GET_PARAMS
) {
7194 ledger_amount_t limit
;
7197 ledger_get_limit(ledger
, task_ledgers
.interrupt_wakeups
, &limit
);
7198 ledger_get_period(ledger
, task_ledgers
.interrupt_wakeups
, &period
);
7200 if (limit
!= LEDGER_LIMIT_INFINITY
) {
7202 * An active limit means the wakeups monitor is enabled.
7204 *rate_hz
= (int32_t)(limit
/ (int64_t)(period
/ NSEC_PER_SEC
));
7205 *flags
= WAKEMON_ENABLE
;
7206 if (task
->rusage_cpu_flags
& TASK_RUSECPU_FLAGS_FATAL_WAKEUPSMON
) {
7207 *flags
|= WAKEMON_MAKE_FATAL
;
7210 *flags
= WAKEMON_DISABLE
;
7215 * If WAKEMON_GET_PARAMS is present in flags, all other flags are ignored.
7218 return KERN_SUCCESS
;
7221 if (*flags
& WAKEMON_ENABLE
) {
7222 if (*flags
& WAKEMON_SET_DEFAULTS
) {
7223 *rate_hz
= task_wakeups_monitor_rate
;
7226 #ifndef CONFIG_NOMONITORS
7227 if (*flags
& WAKEMON_MAKE_FATAL
) {
7228 task
->rusage_cpu_flags
|= TASK_RUSECPU_FLAGS_FATAL_WAKEUPSMON
;
7230 #endif /* CONFIG_NOMONITORS */
7232 if (*rate_hz
<= 0) {
7234 return KERN_INVALID_ARGUMENT
;
7237 #ifndef CONFIG_NOMONITORS
7238 ledger_set_limit(ledger
, task_ledgers
.interrupt_wakeups
, *rate_hz
* task_wakeups_monitor_interval
,
7239 (uint8_t)task_wakeups_monitor_ustackshots_trigger_pct
);
7240 ledger_set_period(ledger
, task_ledgers
.interrupt_wakeups
, task_wakeups_monitor_interval
* NSEC_PER_SEC
);
7241 ledger_enable_callback(ledger
, task_ledgers
.interrupt_wakeups
);
7242 #endif /* CONFIG_NOMONITORS */
7243 } else if (*flags
& WAKEMON_DISABLE
) {
7245 * Caller wishes to disable wakeups monitor on the task.
7247 * Disable telemetry if it was triggered by the wakeups monitor, and
7248 * remove the limit & callback on the wakeups ledger entry.
7250 #if CONFIG_TELEMETRY
7251 telemetry_task_ctl_locked(task
, TF_WAKEMON_WARNING
, 0);
7253 ledger_disable_refill(ledger
, task_ledgers
.interrupt_wakeups
);
7254 ledger_disable_callback(ledger
, task_ledgers
.interrupt_wakeups
);
7258 return KERN_SUCCESS
;
7262 task_wakeups_rate_exceeded(int warning
, __unused
const void *param0
, __unused
const void *param1
)
7264 if (warning
== LEDGER_WARNING_ROSE_ABOVE
) {
7265 #if CONFIG_TELEMETRY
7267 * This task is in danger of violating the wakeups monitor. Enable telemetry on this task
7268 * so there are micro-stackshots available if and when EXC_RESOURCE is triggered.
7270 telemetry_task_ctl(current_task(), TF_WAKEMON_WARNING
, 1);
7275 #if CONFIG_TELEMETRY
7277 * If the balance has dipped below the warning level (LEDGER_WARNING_DIPPED_BELOW) or
7278 * exceeded the limit, turn telemetry off for the task.
7280 telemetry_task_ctl(current_task(), TF_WAKEMON_WARNING
, 0);
7284 SENDING_NOTIFICATION__THIS_PROCESS_IS_CAUSING_TOO_MANY_WAKEUPS();
7288 void __attribute__((noinline
))
7289 SENDING_NOTIFICATION__THIS_PROCESS_IS_CAUSING_TOO_MANY_WAKEUPS(void)
7291 task_t task
= current_task();
7293 const char *procname
= "unknown";
7296 #ifdef EXC_RESOURCE_MONITORS
7297 mach_exception_data_type_t code
[EXCEPTION_CODE_MAX
];
7298 #endif /* EXC_RESOURCE_MONITORS */
7299 struct ledger_entry_info lei
;
7302 pid
= proc_selfpid();
7303 if (task
->bsd_info
!= NULL
) {
7304 procname
= proc_name_address(current_task()->bsd_info
);
7308 ledger_get_entry_info(task
->ledger
, task_ledgers
.interrupt_wakeups
, &lei
);
7311 * Disable the exception notification so we don't overwhelm
7312 * the listener with an endless stream of redundant exceptions.
7313 * TODO: detect whether another thread is already reporting the violation.
7315 uint32_t flags
= WAKEMON_DISABLE
;
7316 task_wakeups_monitor_ctl(task
, &flags
, NULL
);
7318 fatal
= task
->rusage_cpu_flags
& TASK_RUSECPU_FLAGS_FATAL_WAKEUPSMON
;
7319 trace_resource_violation(RMON_CPUWAKES_VIOLATED
, &lei
);
7320 os_log(OS_LOG_DEFAULT
, "process %s[%d] caught waking the CPU %llu times "
7321 "over ~%llu seconds, averaging %llu wakes / second and "
7322 "violating a %slimit of %llu wakes over %llu seconds.\n",
7324 lei
.lei_balance
, lei
.lei_last_refill
/ NSEC_PER_SEC
,
7325 lei
.lei_last_refill
== 0 ? 0 :
7326 (NSEC_PER_SEC
* lei
.lei_balance
/ lei
.lei_last_refill
),
7327 fatal
? "FATAL " : "",
7328 lei
.lei_limit
, lei
.lei_refill_period
/ NSEC_PER_SEC
);
7330 kr
= send_resource_violation(send_cpu_wakes_violation
, task
, &lei
,
7331 fatal
? kRNFatalLimitFlag
: 0);
7333 printf("send_resource_violation(CPU wakes, ...): error %#x\n", kr
);
7336 #ifdef EXC_RESOURCE_MONITORS
7337 if (disable_exc_resource
) {
7338 printf("process %s[%d] caught causing excessive wakeups. EXC_RESOURCE "
7339 "supressed by a boot-arg\n", procname
, pid
);
7343 os_log(OS_LOG_DEFAULT
, "process %s[%d] caught causing excessive wakeups. EXC_RESOURCE "
7344 "supressed due to audio playback\n", procname
, pid
);
7347 if (lei
.lei_last_refill
== 0) {
7348 os_log(OS_LOG_DEFAULT
, "process %s[%d] caught causing excessive wakeups. EXC_RESOURCE "
7349 "supressed due to lei.lei_last_refill = 0 \n", procname
, pid
);
7352 code
[0] = code
[1] = 0;
7353 EXC_RESOURCE_ENCODE_TYPE(code
[0], RESOURCE_TYPE_WAKEUPS
);
7354 EXC_RESOURCE_ENCODE_FLAVOR(code
[0], FLAVOR_WAKEUPS_MONITOR
);
7355 EXC_RESOURCE_CPUMONITOR_ENCODE_WAKEUPS_PERMITTED(code
[0],
7356 NSEC_PER_SEC
* lei
.lei_limit
/ lei
.lei_refill_period
);
7357 EXC_RESOURCE_CPUMONITOR_ENCODE_OBSERVATION_INTERVAL(code
[0],
7358 lei
.lei_last_refill
);
7359 EXC_RESOURCE_CPUMONITOR_ENCODE_WAKEUPS_OBSERVED(code
[1],
7360 NSEC_PER_SEC
* lei
.lei_balance
/ lei
.lei_last_refill
);
7361 exception_triage(EXC_RESOURCE
, code
, EXCEPTION_CODE_MAX
);
7362 #endif /* EXC_RESOURCE_MONITORS */
7365 task_terminate_internal(task
);
7370 global_update_logical_writes(int64_t io_delta
, int64_t *global_write_count
)
7372 int64_t old_count
, new_count
;
7373 boolean_t needs_telemetry
;
7376 new_count
= old_count
= *global_write_count
;
7377 new_count
+= io_delta
;
7378 if (new_count
>= io_telemetry_limit
) {
7380 needs_telemetry
= TRUE
;
7382 needs_telemetry
= FALSE
;
7384 } while (!OSCompareAndSwap64(old_count
, new_count
, global_write_count
));
7385 return needs_telemetry
;
7389 task_update_physical_writes(__unused task_t task
, __unused task_physical_write_flavor_t flavor
, __unused
uint64_t io_size
, __unused task_balance_flags_t flags
)
7391 #if CONFIG_PHYS_WRITE_ACCT
7397 * task == NULL means that we have to update kernel_task ledgers
7403 KERNEL_DEBUG_CONSTANT((MACHDBG_CODE(DBG_MACH_VM
, VM_PHYS_WRITE_ACCT
)) | DBG_FUNC_NONE
,
7404 task_pid(task
), flavor
, io_size
, flags
, 0);
7405 DTRACE_IO4(physical_writes
, struct task
*, task
, task_physical_write_flavor_t
, flavor
, uint64_t, io_size
, task_balance_flags_t
, flags
);
7407 if (flags
& TASK_BALANCE_CREDIT
) {
7408 if (flavor
== TASK_PHYSICAL_WRITE_METADATA
) {
7409 OSAddAtomic64(io_size
, (SInt64
*)&(task
->task_fs_metadata_writes
));
7410 ledger_credit_nocheck(task
->ledger
, task_ledgers
.fs_metadata_writes
, io_size
);
7412 } else if (flags
& TASK_BALANCE_DEBIT
) {
7413 if (flavor
== TASK_PHYSICAL_WRITE_METADATA
) {
7414 OSAddAtomic64(-1 * io_size
, (SInt64
*)&(task
->task_fs_metadata_writes
));
7415 ledger_debit_nocheck(task
->ledger
, task_ledgers
.fs_metadata_writes
, io_size
);
7418 #endif /* CONFIG_PHYS_WRITE_ACCT */
7422 task_update_logical_writes(task_t task
, uint32_t io_size
, int flags
, void *vp
)
7424 int64_t io_delta
= 0;
7425 int64_t * global_counter_to_update
;
7426 boolean_t needs_telemetry
= FALSE
;
7427 boolean_t is_external_device
= FALSE
;
7428 int ledger_to_update
= 0;
7429 struct task_writes_counters
* writes_counters_to_update
;
7431 if ((!task
) || (!io_size
) || (!vp
)) {
7435 KERNEL_DEBUG_CONSTANT((MACHDBG_CODE(DBG_MACH_VM
, VM_DATA_WRITE
)) | DBG_FUNC_NONE
,
7436 task_pid(task
), io_size
, flags
, (uintptr_t)VM_KERNEL_ADDRPERM(vp
), 0);
7437 DTRACE_IO4(logical_writes
, struct task
*, task
, uint32_t, io_size
, int, flags
, vnode
*, vp
);
7439 // Is the drive backing this vnode internal or external to the system?
7440 if (vnode_isonexternalstorage(vp
) == false) {
7441 global_counter_to_update
= &global_logical_writes_count
;
7442 ledger_to_update
= task_ledgers
.logical_writes
;
7443 writes_counters_to_update
= &task
->task_writes_counters_internal
;
7444 is_external_device
= FALSE
;
7446 global_counter_to_update
= &global_logical_writes_to_external_count
;
7447 ledger_to_update
= task_ledgers
.logical_writes_to_external
;
7448 writes_counters_to_update
= &task
->task_writes_counters_external
;
7449 is_external_device
= TRUE
;
7453 case TASK_WRITE_IMMEDIATE
:
7454 OSAddAtomic64(io_size
, (SInt64
*)&(writes_counters_to_update
->task_immediate_writes
));
7455 ledger_credit(task
->ledger
, ledger_to_update
, io_size
);
7456 if (!is_external_device
) {
7457 coalition_io_ledger_update(task
, FLAVOR_IO_LOGICAL_WRITES
, TRUE
, io_size
);
7460 case TASK_WRITE_DEFERRED
:
7461 OSAddAtomic64(io_size
, (SInt64
*)&(writes_counters_to_update
->task_deferred_writes
));
7462 ledger_credit(task
->ledger
, ledger_to_update
, io_size
);
7463 if (!is_external_device
) {
7464 coalition_io_ledger_update(task
, FLAVOR_IO_LOGICAL_WRITES
, TRUE
, io_size
);
7467 case TASK_WRITE_INVALIDATED
:
7468 OSAddAtomic64(io_size
, (SInt64
*)&(writes_counters_to_update
->task_invalidated_writes
));
7469 ledger_debit(task
->ledger
, ledger_to_update
, io_size
);
7470 if (!is_external_device
) {
7471 coalition_io_ledger_update(task
, FLAVOR_IO_LOGICAL_WRITES
, FALSE
, io_size
);
7474 case TASK_WRITE_METADATA
:
7475 OSAddAtomic64(io_size
, (SInt64
*)&(writes_counters_to_update
->task_metadata_writes
));
7476 ledger_credit(task
->ledger
, ledger_to_update
, io_size
);
7477 if (!is_external_device
) {
7478 coalition_io_ledger_update(task
, FLAVOR_IO_LOGICAL_WRITES
, TRUE
, io_size
);
7483 io_delta
= (flags
== TASK_WRITE_INVALIDATED
) ? ((int64_t)io_size
* -1ll) : ((int64_t)io_size
);
7484 if (io_telemetry_limit
!= 0) {
7485 /* If io_telemetry_limit is 0, disable global updates and I/O telemetry */
7486 needs_telemetry
= global_update_logical_writes(io_delta
, global_counter_to_update
);
7487 if (needs_telemetry
&& !is_external_device
) {
7488 act_set_io_telemetry_ast(current_thread());
7494 * Control the I/O monitor for a task.
7497 task_io_monitor_ctl(task_t task
, uint32_t *flags
)
7499 ledger_t ledger
= task
->ledger
;
7502 if (*flags
& IOMON_ENABLE
) {
7503 /* Configure the physical I/O ledger */
7504 ledger_set_limit(ledger
, task_ledgers
.physical_writes
, (task_iomon_limit_mb
* 1024 * 1024), 0);
7505 ledger_set_period(ledger
, task_ledgers
.physical_writes
, (task_iomon_interval_secs
* NSEC_PER_SEC
));
7506 } else if (*flags
& IOMON_DISABLE
) {
7508 * Caller wishes to disable I/O monitor on the task.
7510 ledger_disable_refill(ledger
, task_ledgers
.physical_writes
);
7511 ledger_disable_callback(ledger
, task_ledgers
.physical_writes
);
7515 return KERN_SUCCESS
;
7519 task_io_rate_exceeded(int warning
, const void *param0
, __unused
const void *param1
)
7522 SENDING_NOTIFICATION__THIS_PROCESS_IS_CAUSING_TOO_MUCH_IO((int)param0
);
7526 void __attribute__((noinline
))
7527 SENDING_NOTIFICATION__THIS_PROCESS_IS_CAUSING_TOO_MUCH_IO(int flavor
)
7530 task_t task
= current_task();
7531 #ifdef EXC_RESOURCE_MONITORS
7532 mach_exception_data_type_t code
[EXCEPTION_CODE_MAX
];
7533 #endif /* EXC_RESOURCE_MONITORS */
7534 struct ledger_entry_info lei
;
7538 pid
= proc_selfpid();
7541 * Get the ledger entry info. We need to do this before disabling the exception
7542 * to get correct values for all fields.
7545 case FLAVOR_IO_PHYSICAL_WRITES
:
7546 ledger_get_entry_info(task
->ledger
, task_ledgers
.physical_writes
, &lei
);
7552 * Disable the exception notification so we don't overwhelm
7553 * the listener with an endless stream of redundant exceptions.
7554 * TODO: detect whether another thread is already reporting the violation.
7556 uint32_t flags
= IOMON_DISABLE
;
7557 task_io_monitor_ctl(task
, &flags
);
7559 if (flavor
== FLAVOR_IO_LOGICAL_WRITES
) {
7560 trace_resource_violation(RMON_LOGWRITES_VIOLATED
, &lei
);
7562 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",
7563 pid
, flavor
, (lei
.lei_balance
/ (1024 * 1024)), (lei
.lei_limit
/ (1024 * 1024)), (lei
.lei_refill_period
/ NSEC_PER_SEC
));
7565 kr
= send_resource_violation(send_disk_writes_violation
, task
, &lei
, kRNFlagsNone
);
7567 printf("send_resource_violation(disk_writes, ...): error %#x\n", kr
);
7570 #ifdef EXC_RESOURCE_MONITORS
7571 code
[0] = code
[1] = 0;
7572 EXC_RESOURCE_ENCODE_TYPE(code
[0], RESOURCE_TYPE_IO
);
7573 EXC_RESOURCE_ENCODE_FLAVOR(code
[0], flavor
);
7574 EXC_RESOURCE_IO_ENCODE_INTERVAL(code
[0], (lei
.lei_refill_period
/ NSEC_PER_SEC
));
7575 EXC_RESOURCE_IO_ENCODE_LIMIT(code
[0], (lei
.lei_limit
/ (1024 * 1024)));
7576 EXC_RESOURCE_IO_ENCODE_OBSERVED(code
[1], (lei
.lei_balance
/ (1024 * 1024)));
7577 exception_triage(EXC_RESOURCE
, code
, EXCEPTION_CODE_MAX
);
7578 #endif /* EXC_RESOURCE_MONITORS */
7581 /* Placeholders for the task set/get voucher interfaces */
7583 task_get_mach_voucher(
7585 mach_voucher_selector_t __unused which
,
7586 ipc_voucher_t
*voucher
)
7588 if (TASK_NULL
== task
) {
7589 return KERN_INVALID_TASK
;
7593 return KERN_SUCCESS
;
7597 task_set_mach_voucher(
7599 ipc_voucher_t __unused voucher
)
7601 if (TASK_NULL
== task
) {
7602 return KERN_INVALID_TASK
;
7605 return KERN_SUCCESS
;
7609 task_swap_mach_voucher(
7610 __unused task_t task
,
7611 __unused ipc_voucher_t new_voucher
,
7612 ipc_voucher_t
*in_out_old_voucher
)
7615 * Currently this function is only called from a MIG generated
7616 * routine which doesn't release the reference on the voucher
7617 * addressed by in_out_old_voucher. To avoid leaking this reference,
7618 * a call to release it has been added here.
7620 ipc_voucher_release(*in_out_old_voucher
);
7621 return KERN_NOT_SUPPORTED
;
7625 task_set_gpu_denied(task_t task
, boolean_t denied
)
7630 task
->t_flags
|= TF_GPU_DENIED
;
7632 task
->t_flags
&= ~TF_GPU_DENIED
;
7639 task_is_gpu_denied(task_t task
)
7641 /* We don't need the lock to read this flag */
7642 return (task
->t_flags
& TF_GPU_DENIED
) ? TRUE
: FALSE
;
7647 get_task_memory_region_count(task_t task
)
7650 map
= (task
== kernel_task
) ? kernel_map
: task
->map
;
7651 return (uint64_t)get_map_nentries(map
);
7655 kdebug_trace_dyld_internal(uint32_t base_code
,
7656 struct dyld_kernel_image_info
*info
)
7658 static_assert(sizeof(info
->uuid
) >= 16);
7660 #if defined(__LP64__)
7661 uint64_t *uuid
= (uint64_t *)&(info
->uuid
);
7663 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
7664 KDBG_EVENTID(DBG_DYLD
, DBG_DYLD_UUID
, base_code
), uuid
[0],
7665 uuid
[1], info
->load_addr
,
7666 (uint64_t)info
->fsid
.val
[0] | ((uint64_t)info
->fsid
.val
[1] << 32),
7668 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
7669 KDBG_EVENTID(DBG_DYLD
, DBG_DYLD_UUID
, base_code
+ 1),
7670 (uint64_t)info
->fsobjid
.fid_objno
|
7671 ((uint64_t)info
->fsobjid
.fid_generation
<< 32),
7673 #else /* defined(__LP64__) */
7674 uint32_t *uuid
= (uint32_t *)&(info
->uuid
);
7676 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
7677 KDBG_EVENTID(DBG_DYLD
, DBG_DYLD_UUID
, base_code
+ 2), uuid
[0],
7678 uuid
[1], uuid
[2], uuid
[3], 0);
7679 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
7680 KDBG_EVENTID(DBG_DYLD
, DBG_DYLD_UUID
, base_code
+ 3),
7681 (uint32_t)info
->load_addr
, info
->fsid
.val
[0], info
->fsid
.val
[1],
7682 info
->fsobjid
.fid_objno
, 0);
7683 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
7684 KDBG_EVENTID(DBG_DYLD
, DBG_DYLD_UUID
, base_code
+ 4),
7685 info
->fsobjid
.fid_generation
, 0, 0, 0, 0);
7686 #endif /* !defined(__LP64__) */
7689 static kern_return_t
7690 kdebug_trace_dyld(task_t task
, uint32_t base_code
,
7691 vm_map_copy_t infos_copy
, mach_msg_type_number_t infos_len
)
7694 dyld_kernel_image_info_array_t infos
;
7695 vm_map_offset_t map_data
;
7699 return KERN_INVALID_ADDRESS
;
7702 if (!kdebug_enable
||
7703 !kdebug_debugid_enabled(KDBG_EVENTID(DBG_DYLD
, DBG_DYLD_UUID
, 0))) {
7704 vm_map_copy_discard(infos_copy
);
7705 return KERN_SUCCESS
;
7708 if (task
== NULL
|| task
!= current_task()) {
7709 return KERN_INVALID_TASK
;
7712 kr
= vm_map_copyout(ipc_kernel_map
, &map_data
, (vm_map_copy_t
)infos_copy
);
7713 if (kr
!= KERN_SUCCESS
) {
7717 infos
= CAST_DOWN(dyld_kernel_image_info_array_t
, map_data
);
7719 for (mach_msg_type_number_t i
= 0; i
< infos_len
; i
++) {
7720 kdebug_trace_dyld_internal(base_code
, &(infos
[i
]));
7723 data
= CAST_DOWN(vm_offset_t
, map_data
);
7724 mach_vm_deallocate(ipc_kernel_map
, data
, infos_len
* sizeof(infos
[0]));
7725 return KERN_SUCCESS
;
7729 task_register_dyld_image_infos(task_t task
,
7730 dyld_kernel_image_info_array_t infos_copy
,
7731 mach_msg_type_number_t infos_len
)
7733 return kdebug_trace_dyld(task
, DBG_DYLD_UUID_MAP_A
,
7734 (vm_map_copy_t
)infos_copy
, infos_len
);
7738 task_unregister_dyld_image_infos(task_t task
,
7739 dyld_kernel_image_info_array_t infos_copy
,
7740 mach_msg_type_number_t infos_len
)
7742 return kdebug_trace_dyld(task
, DBG_DYLD_UUID_UNMAP_A
,
7743 (vm_map_copy_t
)infos_copy
, infos_len
);
7747 task_get_dyld_image_infos(__unused task_t task
,
7748 __unused dyld_kernel_image_info_array_t
* dyld_images
,
7749 __unused mach_msg_type_number_t
* dyld_imagesCnt
)
7751 return KERN_NOT_SUPPORTED
;
7755 task_register_dyld_shared_cache_image_info(task_t task
,
7756 dyld_kernel_image_info_t cache_img
,
7757 __unused boolean_t no_cache
,
7758 __unused boolean_t private_cache
)
7760 if (task
== NULL
|| task
!= current_task()) {
7761 return KERN_INVALID_TASK
;
7764 kdebug_trace_dyld_internal(DBG_DYLD_UUID_SHARED_CACHE_A
, &cache_img
);
7765 return KERN_SUCCESS
;
7769 task_register_dyld_set_dyld_state(__unused task_t task
,
7770 __unused
uint8_t dyld_state
)
7772 return KERN_NOT_SUPPORTED
;
7776 task_register_dyld_get_process_state(__unused task_t task
,
7777 __unused dyld_kernel_process_info_t
* dyld_process_state
)
7779 return KERN_NOT_SUPPORTED
;
7783 task_inspect(task_inspect_t task_insp
, task_inspect_flavor_t flavor
,
7784 task_inspect_info_t info_out
, mach_msg_type_number_t
*size_in_out
)
7787 task_t task
= (task_t
)task_insp
;
7788 kern_return_t kr
= KERN_SUCCESS
;
7789 mach_msg_type_number_t size
;
7791 if (task
== TASK_NULL
) {
7792 return KERN_INVALID_ARGUMENT
;
7795 size
= *size_in_out
;
7798 case TASK_INSPECT_BASIC_COUNTS
: {
7799 struct task_inspect_basic_counts
*bc
;
7800 uint64_t task_counts
[MT_CORE_NFIXED
] = { 0 };
7802 if (size
< TASK_INSPECT_BASIC_COUNTS_COUNT
) {
7803 kr
= KERN_INVALID_ARGUMENT
;
7807 mt_fixed_task_counts(task
, task_counts
);
7808 bc
= (struct task_inspect_basic_counts
*)info_out
;
7809 #ifdef MT_CORE_INSTRS
7810 bc
->instructions
= task_counts
[MT_CORE_INSTRS
];
7811 #else /* defined(MT_CORE_INSTRS) */
7812 bc
->instructions
= 0;
7813 #endif /* !defined(MT_CORE_INSTRS) */
7814 bc
->cycles
= task_counts
[MT_CORE_CYCLES
];
7815 size
= TASK_INSPECT_BASIC_COUNTS_COUNT
;
7819 kr
= KERN_INVALID_ARGUMENT
;
7823 if (kr
== KERN_SUCCESS
) {
7824 *size_in_out
= size
;
7827 #else /* MONOTONIC */
7828 #pragma unused(task_insp, flavor, info_out, size_in_out)
7829 return KERN_NOT_SUPPORTED
;
7830 #endif /* !MONOTONIC */
7833 #if CONFIG_SECLUDED_MEMORY
7834 int num_tasks_can_use_secluded_mem
= 0;
7837 task_set_can_use_secluded_mem(
7839 boolean_t can_use_secluded_mem
)
7841 if (!task
->task_could_use_secluded_mem
) {
7845 task_set_can_use_secluded_mem_locked(task
, can_use_secluded_mem
);
7850 task_set_can_use_secluded_mem_locked(
7852 boolean_t can_use_secluded_mem
)
7854 assert(task
->task_could_use_secluded_mem
);
7855 if (can_use_secluded_mem
&&
7856 secluded_for_apps
&& /* global boot-arg */
7857 !task
->task_can_use_secluded_mem
) {
7858 assert(num_tasks_can_use_secluded_mem
>= 0);
7860 (volatile SInt32
*)&num_tasks_can_use_secluded_mem
);
7861 task
->task_can_use_secluded_mem
= TRUE
;
7862 } else if (!can_use_secluded_mem
&&
7863 task
->task_can_use_secluded_mem
) {
7864 assert(num_tasks_can_use_secluded_mem
> 0);
7866 (volatile SInt32
*)&num_tasks_can_use_secluded_mem
);
7867 task
->task_can_use_secluded_mem
= FALSE
;
7872 task_set_could_use_secluded_mem(
7874 boolean_t could_use_secluded_mem
)
7876 task
->task_could_use_secluded_mem
= !!could_use_secluded_mem
;
7880 task_set_could_also_use_secluded_mem(
7882 boolean_t could_also_use_secluded_mem
)
7884 task
->task_could_also_use_secluded_mem
= !!could_also_use_secluded_mem
;
7888 task_can_use_secluded_mem(
7892 if (task
->task_can_use_secluded_mem
) {
7893 assert(task
->task_could_use_secluded_mem
);
7894 assert(num_tasks_can_use_secluded_mem
> 0);
7897 if (task
->task_could_also_use_secluded_mem
&&
7898 num_tasks_can_use_secluded_mem
> 0) {
7899 assert(num_tasks_can_use_secluded_mem
> 0);
7904 * If a single task is using more than some large amount of
7905 * memory (i.e. secluded_shutoff_trigger) and is approaching
7906 * its task limit, allow it to dip into secluded and begin
7907 * suppression of rebuilding secluded memory until that task exits.
7909 if (is_alloc
&& secluded_shutoff_trigger
!= 0) {
7910 uint64_t phys_used
= get_task_phys_footprint(task
);
7911 uint64_t limit
= get_task_phys_footprint_limit(task
);
7912 if (phys_used
> secluded_shutoff_trigger
&&
7913 limit
> secluded_shutoff_trigger
&&
7914 phys_used
> limit
- secluded_shutoff_headroom
) {
7915 start_secluded_suppression(task
);
7924 task_could_use_secluded_mem(
7927 return task
->task_could_use_secluded_mem
;
7931 task_could_also_use_secluded_mem(
7934 return task
->task_could_also_use_secluded_mem
;
7936 #endif /* CONFIG_SECLUDED_MEMORY */
7939 task_io_user_clients(task_t task
)
7941 return &task
->io_user_clients
;
7945 task_set_message_app_suspended(task_t task
, boolean_t enable
)
7947 task
->message_app_suspended
= enable
;
7951 task_copy_fields_for_exec(task_t dst_task
, task_t src_task
)
7953 dst_task
->vtimers
= src_task
->vtimers
;
7956 #if DEVELOPMENT || DEBUG
7957 int vm_region_footprint
= 0;
7958 #endif /* DEVELOPMENT || DEBUG */
7961 task_self_region_footprint(void)
7963 #if DEVELOPMENT || DEBUG
7964 if (vm_region_footprint
) {
7965 /* system-wide override */
7968 #endif /* DEVELOPMENT || DEBUG */
7969 return current_task()->task_region_footprint
;
7973 task_self_region_footprint_set(
7978 curtask
= current_task();
7981 curtask
->task_region_footprint
= TRUE
;
7983 curtask
->task_region_footprint
= FALSE
;
7985 task_unlock(curtask
);
7989 task_set_darkwake_mode(task_t task
, boolean_t set_mode
)
7996 task
->t_flags
|= TF_DARKWAKE_MODE
;
7998 task
->t_flags
&= ~(TF_DARKWAKE_MODE
);
8005 task_get_darkwake_mode(task_t task
)
8008 return (task
->t_flags
& TF_DARKWAKE_MODE
) != 0;
8012 task_get_exc_guard_behavior(
8014 task_exc_guard_behavior_t
*behaviorp
)
8016 if (task
== TASK_NULL
) {
8017 return KERN_INVALID_TASK
;
8019 *behaviorp
= task
->task_exc_guard
;
8020 return KERN_SUCCESS
;
8023 #ifndef TASK_EXC_GUARD_ALL
8024 /* Temporary define until two branches are merged */
8025 #define TASK_EXC_GUARD_ALL (TASK_EXC_GUARD_VM_ALL | 0xf0)
8029 task_set_exc_guard_behavior(
8031 task_exc_guard_behavior_t behavior
)
8033 if (task
== TASK_NULL
) {
8034 return KERN_INVALID_TASK
;
8036 if (behavior
& ~TASK_EXC_GUARD_ALL
) {
8037 return KERN_INVALID_VALUE
;
8039 task
->task_exc_guard
= behavior
;
8040 return KERN_SUCCESS
;
8044 extern int legacy_footprint_entitlement_mode
;
8045 extern void memorystatus_act_on_legacy_footprint_entitlement(struct proc
*, boolean_t
);
8046 extern void memorystatus_act_on_ios13extended_footprint_entitlement(struct proc
*);
8050 task_set_legacy_footprint(
8054 task
->task_legacy_footprint
= TRUE
;
8059 task_set_extra_footprint_limit(
8062 if (task
->task_extra_footprint_limit
) {
8066 if (task
->task_extra_footprint_limit
) {
8070 task
->task_extra_footprint_limit
= TRUE
;
8072 memorystatus_act_on_legacy_footprint_entitlement(task
->bsd_info
, TRUE
);
8076 task_set_ios13extended_footprint_limit(
8079 if (task
->task_ios13extended_footprint_limit
) {
8083 if (task
->task_ios13extended_footprint_limit
) {
8087 task
->task_ios13extended_footprint_limit
= TRUE
;
8089 memorystatus_act_on_ios13extended_footprint_entitlement(task
->bsd_info
);
8091 #endif /* __arm64__ */
8093 static inline ledger_amount_t
8094 task_ledger_get_balance(
8098 ledger_amount_t amount
;
8100 ledger_get_balance(ledger
, ledger_idx
, &amount
);
8105 * Gather the amount of memory counted in a task's footprint due to
8106 * being in a specific set of ledgers.
8109 task_ledgers_footprint(
8111 ledger_amount_t
*ledger_resident
,
8112 ledger_amount_t
*ledger_compressed
)
8114 *ledger_resident
= 0;
8115 *ledger_compressed
= 0;
8117 /* purgeable non-volatile memory */
8118 *ledger_resident
+= task_ledger_get_balance(ledger
, task_ledgers
.purgeable_nonvolatile
);
8119 *ledger_compressed
+= task_ledger_get_balance(ledger
, task_ledgers
.purgeable_nonvolatile_compressed
);
8121 /* "default" tagged memory */
8122 *ledger_resident
+= task_ledger_get_balance(ledger
, task_ledgers
.tagged_footprint
);
8123 *ledger_compressed
+= task_ledger_get_balance(ledger
, task_ledgers
.tagged_footprint_compressed
);
8125 /* "network" currently never counts in the footprint... */
8127 /* "media" tagged memory */
8128 *ledger_resident
+= task_ledger_get_balance(ledger
, task_ledgers
.media_footprint
);
8129 *ledger_compressed
+= task_ledger_get_balance(ledger
, task_ledgers
.media_footprint_compressed
);
8131 /* "graphics" tagged memory */
8132 *ledger_resident
+= task_ledger_get_balance(ledger
, task_ledgers
.graphics_footprint
);
8133 *ledger_compressed
+= task_ledger_get_balance(ledger
, task_ledgers
.graphics_footprint_compressed
);
8135 /* "neural" tagged memory */
8136 *ledger_resident
+= task_ledger_get_balance(ledger
, task_ledgers
.neural_footprint
);
8137 *ledger_compressed
+= task_ledger_get_balance(ledger
, task_ledgers
.neural_footprint_compressed
);
8141 task_set_memory_ownership_transfer(
8146 task
->task_can_transfer_memory_ownership
= !!value
;
8151 task_copy_vmobjects(task_t task
, vm_object_query_t query
, size_t len
, size_t *num
)
8153 vm_object_t find_vmo
;
8156 task_objq_lock(task
);
8157 if (query
!= NULL
) {
8158 queue_iterate(&task
->task_objq
, find_vmo
, vm_object_t
, task_objq
)
8160 vm_object_query_t p
= &query
[size
++];
8162 /* make sure to not overrun */
8163 if (size
* sizeof(vm_object_query_data_t
) > len
) {
8168 bzero(p
, sizeof(*p
));
8169 p
->object_id
= (vm_object_id_t
) VM_KERNEL_ADDRPERM(find_vmo
);
8170 p
->virtual_size
= find_vmo
->internal
? find_vmo
->vo_size
: 0;
8171 p
->resident_size
= find_vmo
->resident_page_count
* PAGE_SIZE
;
8172 p
->wired_size
= find_vmo
->wired_page_count
* PAGE_SIZE
;
8173 p
->reusable_size
= find_vmo
->reusable_page_count
* PAGE_SIZE
;
8174 p
->vo_no_footprint
= find_vmo
->vo_no_footprint
;
8175 p
->vo_ledger_tag
= find_vmo
->vo_ledger_tag
;
8176 p
->purgable
= find_vmo
->purgable
;
8178 if (find_vmo
->internal
&& find_vmo
->pager_created
&& find_vmo
->pager
!= NULL
) {
8179 p
->compressed_size
= vm_compressor_pager_get_count(find_vmo
->pager
) * PAGE_SIZE
;
8181 p
->compressed_size
= 0;
8185 size
= (size_t)task
->task_owned_objects
;
8187 task_objq_unlock(task
);
8193 task_set_filter_msg_flag(
8197 assert(task
!= TASK_NULL
);
8201 task
->t_flags
|= TF_FILTER_MSG
;
8203 task
->t_flags
&= ~TF_FILTER_MSG
;
8209 task_get_filter_msg_flag(
8218 flags
= os_atomic_load(&task
->t_flags
, relaxed
);
8219 return (flags
& TF_FILTER_MSG
) ? TRUE
: FALSE
;
8225 if (task
== TASK_NULL
) {
8228 return vm_map_is_exotic(get_task_map(task
));
8235 if (task
== TASK_NULL
) {
8238 return vm_map_is_alien(get_task_map(task
));
8244 /* Set the filter mask for Mach traps. */
8246 mac_task_set_mach_filter_mask(task_t task
, uint8_t *maskptr
)
8250 task
->mach_trap_filter_mask
= maskptr
;
8253 /* Set the filter mask for kobject msgs. */
8255 mac_task_set_kobj_filter_mask(task_t task
, uint8_t *maskptr
)
8259 task
->mach_kobj_filter_mask
= maskptr
;
8262 /* Hook for mach trap/sc filter evaluation policy. */
8263 mac_task_mach_filter_cbfunc_t mac_task_mach_trap_evaluate
= NULL
;
8265 /* Hook for kobj message filter evaluation policy. */
8266 mac_task_kobj_filter_cbfunc_t mac_task_kobj_msg_evaluate
= NULL
;
8268 /* Set the callback hooks for the filtering policy. */
8270 mac_task_register_filter_callbacks(
8271 const mac_task_mach_filter_cbfunc_t mach_cbfunc
,
8272 const mac_task_kobj_filter_cbfunc_t kobj_cbfunc
)
8274 if (mach_cbfunc
!= NULL
) {
8275 if (mac_task_mach_trap_evaluate
!= NULL
) {
8276 return KERN_FAILURE
;
8278 mac_task_mach_trap_evaluate
= mach_cbfunc
;
8280 if (kobj_cbfunc
!= NULL
) {
8281 if (mac_task_kobj_msg_evaluate
!= NULL
) {
8282 return KERN_FAILURE
;
8284 mac_task_kobj_msg_evaluate
= kobj_cbfunc
;
8287 return KERN_SUCCESS
;
8289 #endif /* CONFIG_MACF */
8292 task_transfer_mach_filter_bits(
8297 /* Copy mach trap and kernel object mask pointers to new task. */
8298 new_task
->mach_trap_filter_mask
= old_task
->mach_trap_filter_mask
;
8299 new_task
->mach_kobj_filter_mask
= old_task
->mach_kobj_filter_mask
;
8301 /* If filter message flag is set then set it in the new task. */
8302 if (task_get_filter_msg_flag(old_task
)) {
8303 new_task
->t_flags
|= TF_FILTER_MSG
;
8308 #if __has_feature(ptrauth_calls)
8310 #define PAC_EXCEPTION_ENTITLEMENT "com.apple.private.pac.exception"
8313 task_set_pac_exception_fatal_flag(
8316 assert(task
!= TASK_NULL
);
8318 if (!IOTaskHasEntitlement(task
, PAC_EXCEPTION_ENTITLEMENT
)) {
8323 task
->t_flags
|= TF_PAC_EXC_FATAL
;
8328 task_is_pac_exception_fatal(
8333 assert(task
!= TASK_NULL
);
8335 flags
= os_atomic_load(&task
->t_flags
, relaxed
);
8336 return (bool)(flags
& TF_PAC_EXC_FATAL
);
8338 #endif /* __has_feature(ptrauth_calls) */
8341 task_set_tecs(task_t task
)
8343 if (task
== TASK_NULL
) {
8344 task
= current_task();
8347 if (!machine_csv(CPUVN_CI
)) {
8351 LCK_MTX_ASSERT(&task
->lock
, LCK_MTX_ASSERT_NOTOWNED
);
8355 task
->t_flags
|= TF_TECS
;
8358 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
8359 machine_tecs(thread
);