2 * Copyright (c) 2000-2010, 2015 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_special_ports.h>
99 #include <ipc/ipc_importance.h>
100 #include <ipc/ipc_types.h>
101 #include <ipc/ipc_space.h>
102 #include <ipc/ipc_entry.h>
103 #include <ipc/ipc_hash.h>
105 #include <kern/kern_types.h>
106 #include <kern/mach_param.h>
107 #include <kern/misc_protos.h>
108 #include <kern/task.h>
109 #include <kern/thread.h>
110 #include <kern/coalition.h>
111 #include <kern/zalloc.h>
112 #include <kern/kalloc.h>
113 #include <kern/kern_cdata.h>
114 #include <kern/processor.h>
115 #include <kern/sched_prim.h> /* for thread_wakeup */
116 #include <kern/ipc_tt.h>
117 #include <kern/host.h>
118 #include <kern/clock.h>
119 #include <kern/timer.h>
120 #include <kern/assert.h>
121 #include <kern/sync_lock.h>
122 #include <kern/affinity.h>
123 #include <kern/exc_resource.h>
124 #include <kern/machine.h>
125 #include <corpses/task_corpse.h>
127 #include <kern/telemetry.h>
131 #include <vm/vm_map.h>
132 #include <vm/vm_kern.h> /* for kernel_map, ipc_kernel_map */
133 #include <vm/vm_pageout.h>
134 #include <vm/vm_protos.h>
135 #include <vm/vm_purgeable_internal.h>
137 #include <sys/resource.h>
138 #include <sys/signalvar.h> /* for coredump */
141 * Exported interfaces
144 #include <mach/task_server.h>
145 #include <mach/mach_host_server.h>
146 #include <mach/host_security_server.h>
147 #include <mach/mach_port_server.h>
149 #include <vm/vm_shared_region.h>
151 #include <libkern/OSDebug.h>
152 #include <libkern/OSAtomic.h>
155 #include <atm/atm_internal.h>
158 #include <kern/sfi.h>
161 extern int kpc_force_all_ctrs(task_t
, int);
164 uint32_t qos_override_mode
;
168 lck_attr_t task_lck_attr
;
169 lck_grp_t task_lck_grp
;
170 lck_grp_attr_t task_lck_grp_attr
;
172 /* Flag set by core audio when audio is playing. Used to stifle EXC_RESOURCE generation when active. */
173 int audio_active
= 0;
175 zinfo_usage_store_t tasks_tkm_private
;
176 zinfo_usage_store_t tasks_tkm_shared
;
178 /* A container to accumulate statistics for expired tasks */
179 expired_task_statistics_t dead_task_statistics
;
180 lck_spin_t dead_task_statistics_lock
;
182 ledger_template_t task_ledger_template
= NULL
;
184 struct _task_ledger_indices task_ledgers
__attribute__((used
)) =
185 {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
186 { 0 /* initialized at runtime */},
192 /* System sleep state */
193 boolean_t tasks_suspend_state
;
196 void init_task_ledgers(void);
197 void task_footprint_exceeded(int warning
, __unused
const void *param0
, __unused
const void *param1
);
198 void task_wakeups_rate_exceeded(int warning
, __unused
const void *param0
, __unused
const void *param1
);
199 void __attribute__((noinline
)) THIS_PROCESS_IS_CAUSING_TOO_MANY_WAKEUPS__SENDING_EXC_RESOURCE(void);
200 void __attribute__((noinline
)) PROC_CROSSED_HIGH_WATERMARK__SEND_EXC_RESOURCE_AND_SUSPEND(int max_footprint_mb
);
202 kern_return_t
task_suspend_internal(task_t
);
203 kern_return_t
task_resume_internal(task_t
);
204 static kern_return_t
task_start_halt_locked(task_t task
, boolean_t should_mark_corpse
);
207 void proc_init_cpumon_params(void);
208 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
*);
210 // Warn tasks when they hit 80% of their memory limit.
211 #define PHYS_FOOTPRINT_WARNING_LEVEL 80
213 #define TASK_WAKEUPS_MONITOR_DEFAULT_LIMIT 150 /* wakeups per second */
214 #define TASK_WAKEUPS_MONITOR_DEFAULT_INTERVAL 300 /* in seconds. */
217 * Level (in terms of percentage of the limit) at which the wakeups monitor triggers telemetry.
219 * (ie when the task's wakeups rate exceeds 70% of the limit, start taking user
220 * stacktraces, aka micro-stackshots)
222 #define TASK_WAKEUPS_MONITOR_DEFAULT_USTACKSHOTS_TRIGGER 70
224 int task_wakeups_monitor_interval
; /* In seconds. Time period over which wakeups rate is observed */
225 int task_wakeups_monitor_rate
; /* In hz. Maximum allowable wakeups per task before EXC_RESOURCE is sent */
227 int task_wakeups_monitor_ustackshots_trigger_pct
; /* Percentage. Level at which we start gathering telemetry. */
229 int disable_exc_resource
; /* Global override to supress EXC_RESOURCE for resource monitor violations. */
231 ledger_amount_t max_task_footprint
= 0; /* Per-task limit on physical memory consumption in bytes */
232 int max_task_footprint_mb
= 0; /* Per-task limit on physical memory consumption in megabytes */
235 int pmap_ledgers_panic
= 1;
236 #endif /* MACH_ASSERT */
238 int task_max
= CONFIG_TASK_MAX
; /* Max number of tasks */
240 int hwm_user_cores
= 0; /* high watermark violations generate user core files */
243 extern void proc_getexecutableuuid(void *, unsigned char *, unsigned long);
244 extern int proc_pid(struct proc
*p
);
245 extern int proc_selfpid(void);
246 extern char *proc_name_address(struct proc
*p
);
247 extern uint64_t get_dispatchqueue_offset_from_proc(void *);
249 extern void proc_memstat_terminated(struct proc
* p
, boolean_t set
);
250 extern void memorystatus_on_ledger_footprint_exceeded(int warning
, const int max_footprint_mb
);
254 extern int pmap_ledgers_panic
;
255 #endif /* MACH_ASSERT */
259 void task_hold_locked(
261 void task_wait_locked(
263 boolean_t until_not_runnable
);
264 void task_release_locked(
268 void task_synchronizer_destroy_all(
271 int check_for_tasksuspend(
275 task_backing_store_privileged(
279 task
->priv_flags
|= VM_BACKING_STORE_PRIV
;
290 #if defined(__i386__) || defined(__x86_64__) || defined(__arm64__)
292 #endif /* defined(__i386__) || defined(__x86_64__) || defined(__arm64__) */
297 if (task_has_64BitAddr(task
))
299 task_set_64BitAddr(task
);
301 if ( !task_has_64BitAddr(task
))
303 task_clear_64BitAddr(task
);
305 /* FIXME: On x86, the thread save state flavor can diverge from the
306 * task's 64-bit feature flag due to the 32-bit/64-bit register save
307 * state dichotomy. Since we can be pre-empted in this interval,
308 * certain routines may observe the thread as being in an inconsistent
309 * state with respect to its task's 64-bitness.
312 #if defined(__i386__) || defined(__x86_64__) || defined(__arm64__)
313 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
314 thread_mtx_lock(thread
);
315 machine_thread_switch_addrmode(thread
);
316 thread_mtx_unlock(thread
);
318 #endif /* defined(__i386__) || defined(__x86_64__) || defined(__arm64__) */
326 task_set_dyld_info(task_t task
, mach_vm_address_t addr
, mach_vm_size_t size
)
329 task
->all_image_info_addr
= addr
;
330 task
->all_image_info_size
= size
;
335 task_atm_reset(__unused task_t task
) {
338 if (task
->atm_context
!= NULL
) {
339 atm_task_descriptor_destroy(task
->atm_context
);
340 task
->atm_context
= NULL
;
346 #if TASK_REFERENCE_LEAK_DEBUG
347 #include <kern/btlog.h>
349 decl_simple_lock_data(static,task_ref_lock
);
350 static btlog_t
*task_ref_btlog
;
351 #define TASK_REF_OP_INCR 0x1
352 #define TASK_REF_OP_DECR 0x2
354 #define TASK_REF_BTDEPTH 7
357 task_ref_lock_lock(void *context
)
359 simple_lock((simple_lock_t
)context
);
362 task_ref_lock_unlock(void *context
)
364 simple_unlock((simple_lock_t
)context
);
368 task_reference_internal(task_t task
)
370 void * bt
[TASK_REF_BTDEPTH
];
373 numsaved
= OSBacktrace(bt
, TASK_REF_BTDEPTH
);
375 (void)hw_atomic_add(&(task
)->ref_count
, 1);
376 btlog_add_entry(task_ref_btlog
, task
, TASK_REF_OP_INCR
,
381 task_deallocate_internal(task_t task
)
383 void * bt
[TASK_REF_BTDEPTH
];
386 numsaved
= OSBacktrace(bt
, TASK_REF_BTDEPTH
);
388 btlog_add_entry(task_ref_btlog
, task
, TASK_REF_OP_DECR
,
390 return hw_atomic_sub(&(task
)->ref_count
, 1);
393 #endif /* TASK_REFERENCE_LEAK_DEBUG */
399 lck_grp_attr_setdefault(&task_lck_grp_attr
);
400 lck_grp_init(&task_lck_grp
, "task", &task_lck_grp_attr
);
401 lck_attr_setdefault(&task_lck_attr
);
402 lck_mtx_init(&tasks_threads_lock
, &task_lck_grp
, &task_lck_attr
);
406 task_max
* sizeof(struct task
),
407 TASK_CHUNK
* sizeof(struct task
),
410 zone_change(task_zone
, Z_NOENCRYPT
, TRUE
);
413 * Configure per-task memory limit.
414 * The boot-arg is interpreted as Megabytes,
415 * and takes precedence over the device tree.
416 * Setting the boot-arg to 0 disables task limits.
418 if (!PE_parse_boot_argn("max_task_pmem", &max_task_footprint_mb
,
419 sizeof (max_task_footprint_mb
))) {
421 * No limit was found in boot-args, so go look in the device tree.
423 if (!PE_get_default("kern.max_task_pmem", &max_task_footprint_mb
,
424 sizeof(max_task_footprint_mb
))) {
426 * No limit was found in device tree.
428 max_task_footprint_mb
= 0;
432 if (max_task_footprint_mb
!= 0) {
434 if (max_task_footprint_mb
< 50) {
435 printf("Warning: max_task_pmem %d below minimum.\n",
436 max_task_footprint_mb
);
437 max_task_footprint_mb
= 50;
439 printf("Limiting task physical memory footprint to %d MB\n",
440 max_task_footprint_mb
);
442 max_task_footprint
= (ledger_amount_t
)max_task_footprint_mb
* 1024 * 1024; // Convert MB to bytes
444 printf("Warning: max_task_footprint specified, but jetsam not configured; ignoring.\n");
449 PE_parse_boot_argn("pmap_ledgers_panic", &pmap_ledgers_panic
,
450 sizeof (pmap_ledgers_panic
));
451 #endif /* MACH_ASSERT */
453 if (!PE_parse_boot_argn("hwm_user_cores", &hwm_user_cores
,
454 sizeof (hwm_user_cores
))) {
458 if (PE_parse_boot_argn("qos_override_mode", &qos_override_mode
, sizeof(qos_override_mode
))) {
459 printf("QOS override mode: 0x%08x\n", qos_override_mode
);
461 qos_override_mode
= QOS_OVERRIDE_MODE_FINE_GRAINED_OVERRIDE_BUT_SINGLE_MUTEX_OVERRIDE
;
464 proc_init_cpumon_params();
466 if (!PE_parse_boot_argn("task_wakeups_monitor_rate", &task_wakeups_monitor_rate
, sizeof (task_wakeups_monitor_rate
))) {
467 task_wakeups_monitor_rate
= TASK_WAKEUPS_MONITOR_DEFAULT_LIMIT
;
470 if (!PE_parse_boot_argn("task_wakeups_monitor_interval", &task_wakeups_monitor_interval
, sizeof (task_wakeups_monitor_interval
))) {
471 task_wakeups_monitor_interval
= TASK_WAKEUPS_MONITOR_DEFAULT_INTERVAL
;
474 if (!PE_parse_boot_argn("task_wakeups_monitor_ustackshots_trigger_pct", &task_wakeups_monitor_ustackshots_trigger_pct
,
475 sizeof (task_wakeups_monitor_ustackshots_trigger_pct
))) {
476 task_wakeups_monitor_ustackshots_trigger_pct
= TASK_WAKEUPS_MONITOR_DEFAULT_USTACKSHOTS_TRIGGER
;
479 if (!PE_parse_boot_argn("disable_exc_resource", &disable_exc_resource
,
480 sizeof (disable_exc_resource
))) {
481 disable_exc_resource
= 0;
485 * If we have coalitions, coalition_init() will call init_task_ledgers() as it
486 * sets up the ledgers for the default coalition. If we don't have coalitions,
487 * then we have to call it now.
489 #if CONFIG_COALITIONS
490 assert(task_ledger_template
);
491 #else /* CONFIG_COALITIONS */
493 #endif /* CONFIG_COALITIONS */
495 #if TASK_REFERENCE_LEAK_DEBUG
496 simple_lock_init(&task_ref_lock
, 0);
497 task_ref_btlog
= btlog_create(100000,
500 task_ref_lock_unlock
,
502 assert(task_ref_btlog
);
506 * Create the kernel task as the first task.
509 if (task_create_internal(TASK_NULL
, NULL
, FALSE
, TRUE
, &kernel_task
) != KERN_SUCCESS
)
511 if (task_create_internal(TASK_NULL
, NULL
, FALSE
, FALSE
, &kernel_task
) != KERN_SUCCESS
)
513 panic("task_init\n");
515 vm_map_deallocate(kernel_task
->map
);
516 kernel_task
->map
= kernel_map
;
517 lck_spin_init(&dead_task_statistics_lock
, &task_lck_grp
, &task_lck_attr
);
522 * Create a task running in the kernel address space. It may
523 * have its own map of size mem_size and may have ipc privileges.
527 __unused task_t parent_task
,
528 __unused vm_offset_t map_base
,
529 __unused vm_size_t map_size
,
530 __unused task_t
*child_task
)
532 return (KERN_INVALID_ARGUMENT
);
538 __unused ledger_port_array_t ledger_ports
,
539 __unused mach_msg_type_number_t num_ledger_ports
,
540 __unused boolean_t inherit_memory
,
541 __unused task_t
*child_task
) /* OUT */
543 if (parent_task
== TASK_NULL
)
544 return(KERN_INVALID_ARGUMENT
);
547 * No longer supported: too many calls assume that a task has a valid
550 return(KERN_FAILURE
);
554 host_security_create_task_token(
555 host_security_t host_security
,
557 __unused security_token_t sec_token
,
558 __unused audit_token_t audit_token
,
559 __unused host_priv_t host_priv
,
560 __unused ledger_port_array_t ledger_ports
,
561 __unused mach_msg_type_number_t num_ledger_ports
,
562 __unused boolean_t inherit_memory
,
563 __unused task_t
*child_task
) /* OUT */
565 if (parent_task
== TASK_NULL
)
566 return(KERN_INVALID_ARGUMENT
);
568 if (host_security
== HOST_NULL
)
569 return(KERN_INVALID_SECURITY
);
572 * No longer supported.
574 return(KERN_FAILURE
);
582 * Physical footprint: This is the sum of:
583 * + (internal - alternate_accounting)
584 * + (internal_compressed - alternate_accounting_compressed)
586 * + purgeable_nonvolatile
587 * + purgeable_nonvolatile_compressed
590 * The task's anonymous memory, which on iOS is always resident.
592 * internal_compressed
593 * Amount of this task's internal memory which is held by the compressor.
594 * Such memory is no longer actually resident for the task [i.e., resident in its pmap],
595 * and could be either decompressed back into memory, or paged out to storage, depending
596 * on our implementation.
599 * IOKit mappings: The total size of all IOKit mappings in this task, regardless of
600 clean/dirty or internal/external state].
602 * alternate_accounting
603 * The number of internal dirty pages which are part of IOKit mappings. By definition, these pages
604 * are counted in both internal *and* iokit_mapped, so we must subtract them from the total to avoid
608 init_task_ledgers(void)
612 assert(task_ledger_template
== NULL
);
613 assert(kernel_task
== TASK_NULL
);
615 if ((t
= ledger_template_create("Per-task ledger")) == NULL
)
616 panic("couldn't create task ledger template");
618 task_ledgers
.cpu_time
= ledger_entry_add(t
, "cpu_time", "sched", "ns");
619 task_ledgers
.tkm_private
= ledger_entry_add(t
, "tkm_private",
621 task_ledgers
.tkm_shared
= ledger_entry_add(t
, "tkm_shared", "physmem",
623 task_ledgers
.phys_mem
= ledger_entry_add(t
, "phys_mem", "physmem",
625 task_ledgers
.wired_mem
= ledger_entry_add(t
, "wired_mem", "physmem",
627 task_ledgers
.internal
= ledger_entry_add(t
, "internal", "physmem",
629 task_ledgers
.iokit_mapped
= ledger_entry_add(t
, "iokit_mapped", "mappings",
631 task_ledgers
.alternate_accounting
= ledger_entry_add(t
, "alternate_accounting", "physmem",
633 task_ledgers
.alternate_accounting_compressed
= ledger_entry_add(t
, "alternate_accounting_compressed", "physmem",
635 task_ledgers
.phys_footprint
= ledger_entry_add(t
, "phys_footprint", "physmem",
637 task_ledgers
.internal_compressed
= ledger_entry_add(t
, "internal_compressed", "physmem",
639 task_ledgers
.purgeable_volatile
= ledger_entry_add(t
, "purgeable_volatile", "physmem", "bytes");
640 task_ledgers
.purgeable_nonvolatile
= ledger_entry_add(t
, "purgeable_nonvolatile", "physmem", "bytes");
641 task_ledgers
.purgeable_volatile_compressed
= ledger_entry_add(t
, "purgeable_volatile_compress", "physmem", "bytes");
642 task_ledgers
.purgeable_nonvolatile_compressed
= ledger_entry_add(t
, "purgeable_nonvolatile_compress", "physmem", "bytes");
643 task_ledgers
.platform_idle_wakeups
= ledger_entry_add(t
, "platform_idle_wakeups", "power",
645 task_ledgers
.interrupt_wakeups
= ledger_entry_add(t
, "interrupt_wakeups", "power",
649 sfi_class_id_t class_id
, ledger_alias
;
650 for (class_id
= SFI_CLASS_UNSPECIFIED
; class_id
< MAX_SFI_CLASS_ID
; class_id
++) {
651 task_ledgers
.sfi_wait_times
[class_id
] = -1;
654 /* don't account for UNSPECIFIED */
655 for (class_id
= SFI_CLASS_UNSPECIFIED
+ 1; class_id
< MAX_SFI_CLASS_ID
; class_id
++) {
656 ledger_alias
= sfi_get_ledger_alias_for_class(class_id
);
657 if (ledger_alias
!= SFI_CLASS_UNSPECIFIED
) {
658 /* Check to see if alias has been registered yet */
659 if (task_ledgers
.sfi_wait_times
[ledger_alias
] != -1) {
660 task_ledgers
.sfi_wait_times
[class_id
] = task_ledgers
.sfi_wait_times
[ledger_alias
];
662 /* Otherwise, initialize it first */
663 task_ledgers
.sfi_wait_times
[class_id
] = task_ledgers
.sfi_wait_times
[ledger_alias
] = sfi_ledger_entry_add(t
, ledger_alias
);
666 task_ledgers
.sfi_wait_times
[class_id
] = sfi_ledger_entry_add(t
, class_id
);
669 if (task_ledgers
.sfi_wait_times
[class_id
] < 0) {
670 panic("couldn't create entries for task ledger template for SFI class 0x%x", class_id
);
674 assert(task_ledgers
.sfi_wait_times
[MAX_SFI_CLASS_ID
-1] != -1);
675 #endif /* CONFIG_SCHED_SFI */
678 task_ledgers
.cpu_time_billed_to_me
= ledger_entry_add(t
, "cpu_time_billed_to_me", "sched", "ns");
679 task_ledgers
.cpu_time_billed_to_others
= ledger_entry_add(t
, "cpu_time_billed_to_others", "sched", "ns");
681 if ((task_ledgers
.cpu_time
< 0) ||
682 (task_ledgers
.tkm_private
< 0) ||
683 (task_ledgers
.tkm_shared
< 0) ||
684 (task_ledgers
.phys_mem
< 0) ||
685 (task_ledgers
.wired_mem
< 0) ||
686 (task_ledgers
.internal
< 0) ||
687 (task_ledgers
.iokit_mapped
< 0) ||
688 (task_ledgers
.alternate_accounting
< 0) ||
689 (task_ledgers
.alternate_accounting_compressed
< 0) ||
690 (task_ledgers
.phys_footprint
< 0) ||
691 (task_ledgers
.internal_compressed
< 0) ||
692 (task_ledgers
.purgeable_volatile
< 0) ||
693 (task_ledgers
.purgeable_nonvolatile
< 0) ||
694 (task_ledgers
.purgeable_volatile_compressed
< 0) ||
695 (task_ledgers
.purgeable_nonvolatile_compressed
< 0) ||
696 (task_ledgers
.platform_idle_wakeups
< 0) ||
697 (task_ledgers
.interrupt_wakeups
< 0)
699 || (task_ledgers
.cpu_time_billed_to_me
< 0) || (task_ledgers
.cpu_time_billed_to_others
< 0)
702 panic("couldn't create entries for task ledger template");
705 ledger_track_maximum(t
, task_ledgers
.phys_footprint
, 60);
707 if (pmap_ledgers_panic
) {
708 ledger_panic_on_negative(t
, task_ledgers
.phys_footprint
);
709 ledger_panic_on_negative(t
, task_ledgers
.internal
);
710 ledger_panic_on_negative(t
, task_ledgers
.internal_compressed
);
711 ledger_panic_on_negative(t
, task_ledgers
.iokit_mapped
);
712 ledger_panic_on_negative(t
, task_ledgers
.alternate_accounting
);
713 ledger_panic_on_negative(t
, task_ledgers
.alternate_accounting_compressed
);
714 ledger_panic_on_negative(t
, task_ledgers
.purgeable_volatile
);
715 ledger_panic_on_negative(t
, task_ledgers
.purgeable_nonvolatile
);
716 ledger_panic_on_negative(t
, task_ledgers
.purgeable_volatile_compressed
);
717 ledger_panic_on_negative(t
, task_ledgers
.purgeable_nonvolatile_compressed
);
719 #endif /* MACH_ASSERT */
722 ledger_set_callback(t
, task_ledgers
.phys_footprint
, task_footprint_exceeded
, NULL
, NULL
);
725 ledger_set_callback(t
, task_ledgers
.interrupt_wakeups
,
726 task_wakeups_rate_exceeded
, NULL
, NULL
);
728 task_ledger_template
= t
;
732 task_create_internal(
734 coalition_t
*parent_coalitions __unused
,
735 boolean_t inherit_memory
,
737 task_t
*child_task
) /* OUT */
740 vm_shared_region_t shared_region
;
741 ledger_t ledger
= NULL
;
743 new_task
= (task_t
) zalloc(task_zone
);
745 if (new_task
== TASK_NULL
)
746 return(KERN_RESOURCE_SHORTAGE
);
748 /* one ref for just being alive; one for our caller */
749 new_task
->ref_count
= 2;
751 /* allocate with active entries */
752 assert(task_ledger_template
!= NULL
);
753 if ((ledger
= ledger_instantiate(task_ledger_template
,
754 LEDGER_CREATE_ACTIVE_ENTRIES
)) == NULL
) {
755 zfree(task_zone
, new_task
);
756 return(KERN_RESOURCE_SHORTAGE
);
759 new_task
->ledger
= ledger
;
761 #if defined(CONFIG_SCHED_MULTIQ)
762 new_task
->sched_group
= sched_group_create();
765 /* if inherit_memory is true, parent_task MUST not be NULL */
767 new_task
->map
= vm_map_fork(ledger
, parent_task
->map
);
769 new_task
->map
= vm_map_create(pmap_create(ledger
, 0, is_64bit
),
770 (vm_map_offset_t
)(VM_MIN_ADDRESS
),
771 (vm_map_offset_t
)(VM_MAX_ADDRESS
), TRUE
);
773 /* Inherit memlock limit from parent */
775 vm_map_set_user_wire_limit(new_task
->map
, (vm_size_t
)parent_task
->map
->user_wire_limit
);
777 lck_mtx_init(&new_task
->lock
, &task_lck_grp
, &task_lck_attr
);
778 queue_init(&new_task
->threads
);
779 new_task
->suspend_count
= 0;
780 new_task
->thread_count
= 0;
781 new_task
->active_thread_count
= 0;
782 new_task
->user_stop_count
= 0;
783 new_task
->legacy_stop_count
= 0;
784 new_task
->active
= TRUE
;
785 new_task
->halting
= FALSE
;
786 new_task
->user_data
= NULL
;
787 new_task
->faults
= 0;
788 new_task
->cow_faults
= 0;
789 new_task
->pageins
= 0;
790 new_task
->messages_sent
= 0;
791 new_task
->messages_received
= 0;
792 new_task
->syscalls_mach
= 0;
793 new_task
->priv_flags
= 0;
794 new_task
->syscalls_unix
=0;
795 new_task
->c_switch
= new_task
->p_switch
= new_task
->ps_switch
= 0;
796 new_task
->t_flags
= 0;
797 new_task
->importance
= 0;
800 new_task
->atm_context
= NULL
;
803 new_task
->bank_context
= NULL
;
806 zinfo_task_init(new_task
);
809 new_task
->bsd_info
= NULL
;
810 new_task
->corpse_info
= NULL
;
811 #endif /* MACH_BSD */
814 if (max_task_footprint
!= 0) {
815 ledger_set_limit(ledger
, task_ledgers
.phys_footprint
, max_task_footprint
, PHYS_FOOTPRINT_WARNING_LEVEL
);
819 if (task_wakeups_monitor_rate
!= 0) {
820 uint32_t flags
= WAKEMON_ENABLE
| WAKEMON_SET_DEFAULTS
;
821 int32_t rate
; // Ignored because of WAKEMON_SET_DEFAULTS
822 task_wakeups_monitor_ctl(new_task
, &flags
, &rate
);
825 #if defined(__i386__) || defined(__x86_64__)
826 new_task
->i386_ldt
= 0;
829 new_task
->task_debug
= NULL
;
831 queue_init(&new_task
->semaphore_list
);
832 new_task
->semaphores_owned
= 0;
834 ipc_task_init(new_task
, parent_task
);
836 new_task
->total_user_time
= 0;
837 new_task
->total_system_time
= 0;
839 new_task
->vtimers
= 0;
841 new_task
->shared_region
= NULL
;
843 new_task
->affinity_space
= NULL
;
845 new_task
->pidsuspended
= FALSE
;
846 new_task
->frozen
= FALSE
;
847 new_task
->changing_freeze_state
= FALSE
;
848 new_task
->rusage_cpu_flags
= 0;
849 new_task
->rusage_cpu_percentage
= 0;
850 new_task
->rusage_cpu_interval
= 0;
851 new_task
->rusage_cpu_deadline
= 0;
852 new_task
->rusage_cpu_callt
= NULL
;
854 new_task
->suspends_outstanding
= 0;
858 new_task
->hv_task_target
= NULL
;
859 #endif /* HYPERVISOR */
862 new_task
->low_mem_notified_warn
= 0;
863 new_task
->low_mem_notified_critical
= 0;
864 new_task
->low_mem_privileged_listener
= 0;
865 new_task
->purged_memory_warn
= 0;
866 new_task
->purged_memory_critical
= 0;
867 new_task
->mem_notify_reserved
= 0;
868 #if IMPORTANCE_INHERITANCE
869 new_task
->task_imp_base
= NULL
;
870 #endif /* IMPORTANCE_INHERITANCE */
872 #if defined(__x86_64__)
873 new_task
->uexc_range_start
= new_task
->uexc_range_size
= new_task
->uexc_handler
= 0;
876 new_task
->requested_policy
= default_task_requested_policy
;
877 new_task
->effective_policy
= default_task_effective_policy
;
878 new_task
->pended_policy
= default_task_pended_policy
;
880 if (parent_task
!= TASK_NULL
) {
881 new_task
->sec_token
= parent_task
->sec_token
;
882 new_task
->audit_token
= parent_task
->audit_token
;
884 /* inherit the parent's shared region */
885 shared_region
= vm_shared_region_get(parent_task
);
886 vm_shared_region_set(new_task
, shared_region
);
888 if(task_has_64BitAddr(parent_task
))
889 task_set_64BitAddr(new_task
);
890 new_task
->all_image_info_addr
= parent_task
->all_image_info_addr
;
891 new_task
->all_image_info_size
= parent_task
->all_image_info_size
;
893 #if defined(__i386__) || defined(__x86_64__)
894 if (inherit_memory
&& parent_task
->i386_ldt
)
895 new_task
->i386_ldt
= user_ldt_copy(parent_task
->i386_ldt
);
897 if (inherit_memory
&& parent_task
->affinity_space
)
898 task_affinity_create(parent_task
, new_task
);
900 new_task
->pset_hint
= parent_task
->pset_hint
= task_choose_pset(parent_task
);
902 #if IMPORTANCE_INHERITANCE
903 ipc_importance_task_t new_task_imp
= IIT_NULL
;
905 if (task_is_marked_importance_donor(parent_task
)) {
906 new_task_imp
= ipc_importance_for_task(new_task
, FALSE
);
907 assert(IIT_NULL
!= new_task_imp
);
908 ipc_importance_task_mark_donor(new_task_imp
, TRUE
);
910 /* Embedded doesn't want this to inherit */
911 if (task_is_marked_importance_receiver(parent_task
)) {
912 if (IIT_NULL
== new_task_imp
)
913 new_task_imp
= ipc_importance_for_task(new_task
, FALSE
);
914 assert(IIT_NULL
!= new_task_imp
);
915 ipc_importance_task_mark_receiver(new_task_imp
, TRUE
);
917 if (task_is_marked_importance_denap_receiver(parent_task
)) {
918 if (IIT_NULL
== new_task_imp
)
919 new_task_imp
= ipc_importance_for_task(new_task
, FALSE
);
920 assert(IIT_NULL
!= new_task_imp
);
921 ipc_importance_task_mark_denap_receiver(new_task_imp
, TRUE
);
924 if (IIT_NULL
!= new_task_imp
) {
925 assert(new_task
->task_imp_base
== new_task_imp
);
926 ipc_importance_task_release(new_task_imp
);
928 #endif /* IMPORTANCE_INHERITANCE */
930 new_task
->priority
= BASEPRI_DEFAULT
;
931 new_task
->max_priority
= MAXPRI_USER
;
933 new_task
->requested_policy
.t_apptype
= parent_task
->requested_policy
.t_apptype
;
935 new_task
->requested_policy
.int_darwinbg
= parent_task
->requested_policy
.int_darwinbg
;
936 new_task
->requested_policy
.ext_darwinbg
= parent_task
->requested_policy
.ext_darwinbg
;
937 new_task
->requested_policy
.int_iotier
= parent_task
->requested_policy
.int_iotier
;
938 new_task
->requested_policy
.ext_iotier
= parent_task
->requested_policy
.ext_iotier
;
939 new_task
->requested_policy
.int_iopassive
= parent_task
->requested_policy
.int_iopassive
;
940 new_task
->requested_policy
.ext_iopassive
= parent_task
->requested_policy
.ext_iopassive
;
941 new_task
->requested_policy
.bg_iotier
= parent_task
->requested_policy
.bg_iotier
;
942 new_task
->requested_policy
.terminated
= parent_task
->requested_policy
.terminated
;
943 new_task
->requested_policy
.t_qos_clamp
= parent_task
->requested_policy
.t_qos_clamp
;
945 task_policy_create(new_task
, parent_task
->requested_policy
.t_boosted
);
947 new_task
->sec_token
= KERNEL_SECURITY_TOKEN
;
948 new_task
->audit_token
= KERNEL_AUDIT_TOKEN
;
951 task_set_64BitAddr(new_task
);
953 new_task
->all_image_info_addr
= (mach_vm_address_t
)0;
954 new_task
->all_image_info_size
= (mach_vm_size_t
)0;
956 new_task
->pset_hint
= PROCESSOR_SET_NULL
;
958 if (kernel_task
== TASK_NULL
) {
959 new_task
->priority
= BASEPRI_KERNEL
;
960 new_task
->max_priority
= MAXPRI_KERNEL
;
962 new_task
->priority
= BASEPRI_DEFAULT
;
963 new_task
->max_priority
= MAXPRI_USER
;
967 bzero(new_task
->coalition
, sizeof(new_task
->coalition
));
968 for (int i
= 0; i
< COALITION_NUM_TYPES
; i
++)
969 queue_chain_init(new_task
->task_coalition
[i
]);
971 /* Allocate I/O Statistics */
972 new_task
->task_io_stats
= (io_stat_info_t
)kalloc(sizeof(struct io_stat_info
));
973 assert(new_task
->task_io_stats
!= NULL
);
974 bzero(new_task
->task_io_stats
, sizeof(struct io_stat_info
));
975 new_task
->task_immediate_writes
= 0;
976 new_task
->task_deferred_writes
= 0;
977 new_task
->task_invalidated_writes
= 0;
978 new_task
->task_metadata_writes
= 0;
980 bzero(&(new_task
->cpu_time_qos_stats
), sizeof(struct _cpu_time_qos_stats
));
982 bzero(&new_task
->extmod_statistics
, sizeof(new_task
->extmod_statistics
));
983 new_task
->task_timer_wakeups_bin_1
= new_task
->task_timer_wakeups_bin_2
= 0;
984 new_task
->task_gpu_ns
= 0;
986 #if CONFIG_COALITIONS
988 /* TODO: there is no graceful failure path here... */
989 if (parent_coalitions
&& parent_coalitions
[COALITION_TYPE_RESOURCE
]) {
990 coalitions_adopt_task(parent_coalitions
, new_task
);
991 } else if (parent_task
&& parent_task
->coalition
[COALITION_TYPE_RESOURCE
]) {
993 * all tasks at least have a resource coalition, so
994 * if the parent has one then inherit all coalitions
995 * the parent is a part of
997 coalitions_adopt_task(parent_task
->coalition
, new_task
);
999 /* TODO: assert that new_task will be PID 1 (launchd) */
1000 coalitions_adopt_init_task(new_task
);
1003 if (new_task
->coalition
[COALITION_TYPE_RESOURCE
] == COALITION_NULL
) {
1004 panic("created task is not a member of a resource coalition");
1006 #endif /* CONFIG_COALITIONS */
1008 new_task
->dispatchqueue_offset
= 0;
1009 if (parent_task
!= NULL
) {
1010 new_task
->dispatchqueue_offset
= parent_task
->dispatchqueue_offset
;
1013 if (vm_backing_store_low
&& parent_task
!= NULL
)
1014 new_task
->priv_flags
|= (parent_task
->priv_flags
&VM_BACKING_STORE_PRIV
);
1016 new_task
->task_volatile_objects
= 0;
1017 new_task
->task_nonvolatile_objects
= 0;
1018 new_task
->task_purgeable_disowning
= FALSE
;
1019 new_task
->task_purgeable_disowned
= FALSE
;
1021 ipc_task_enable(new_task
);
1023 lck_mtx_lock(&tasks_threads_lock
);
1024 queue_enter(&tasks
, new_task
, task_t
, tasks
);
1026 if (tasks_suspend_state
) {
1027 task_suspend_internal(new_task
);
1029 lck_mtx_unlock(&tasks_threads_lock
);
1031 *child_task
= new_task
;
1032 return(KERN_SUCCESS
);
1035 int task_dropped_imp_count
= 0;
1040 * Drop a reference on a task.
1046 ledger_amount_t credit
, debit
, interrupt_wakeups
, platform_idle_wakeups
;
1049 if (task
== TASK_NULL
)
1052 refs
= task_deallocate_internal(task
);
1054 #if IMPORTANCE_INHERITANCE
1060 * If last ref potentially comes from the task's importance,
1061 * disconnect it. But more task refs may be added before
1062 * that completes, so wait for the reference to go to zero
1063 * naturually (it may happen on a recursive task_deallocate()
1064 * from the ipc_importance_disconnect_task() call).
1066 if (IIT_NULL
!= task
->task_imp_base
)
1067 ipc_importance_disconnect_task(task
);
1073 #endif /* IMPORTANCE_INHERITANCE */
1075 lck_mtx_lock(&tasks_threads_lock
);
1076 queue_remove(&terminated_tasks
, task
, task_t
, tasks
);
1077 terminated_tasks_count
--;
1078 lck_mtx_unlock(&tasks_threads_lock
);
1081 * remove the reference on atm descriptor
1083 task_atm_reset(task
);
1087 * remove the reference on bank context
1089 if (task
->bank_context
!= NULL
) {
1090 bank_task_destroy(task
->bank_context
);
1091 task
->bank_context
= NULL
;
1095 if (task
->task_io_stats
)
1096 kfree(task
->task_io_stats
, sizeof(struct io_stat_info
));
1099 * Give the machine dependent code a chance
1100 * to perform cleanup before ripping apart
1103 machine_task_terminate(task
);
1105 ipc_task_terminate(task
);
1107 if (task
->affinity_space
)
1108 task_affinity_deallocate(task
);
1111 if (task
->ledger
!= NULL
&&
1112 task
->map
!= NULL
&&
1113 task
->map
->pmap
!= NULL
&&
1114 task
->map
->pmap
->ledger
!= NULL
) {
1115 assert(task
->ledger
== task
->map
->pmap
->ledger
);
1117 #endif /* MACH_ASSERT */
1119 vm_purgeable_disown(task
);
1120 assert(task
->task_purgeable_disowned
);
1121 if (task
->task_volatile_objects
!= 0 ||
1122 task
->task_nonvolatile_objects
!= 0) {
1123 panic("task_deallocate(%p): "
1124 "volatile_objects=%d nonvolatile_objects=%d\n",
1126 task
->task_volatile_objects
,
1127 task
->task_nonvolatile_objects
);
1130 vm_map_deallocate(task
->map
);
1131 is_release(task
->itk_space
);
1133 ledger_get_entries(task
->ledger
, task_ledgers
.interrupt_wakeups
,
1134 &interrupt_wakeups
, &debit
);
1135 ledger_get_entries(task
->ledger
, task_ledgers
.platform_idle_wakeups
,
1136 &platform_idle_wakeups
, &debit
);
1138 #if defined(CONFIG_SCHED_MULTIQ)
1139 sched_group_destroy(task
->sched_group
);
1142 /* Accumulate statistics for dead tasks */
1143 lck_spin_lock(&dead_task_statistics_lock
);
1144 dead_task_statistics
.total_user_time
+= task
->total_user_time
;
1145 dead_task_statistics
.total_system_time
+= task
->total_system_time
;
1147 dead_task_statistics
.task_interrupt_wakeups
+= interrupt_wakeups
;
1148 dead_task_statistics
.task_platform_idle_wakeups
+= platform_idle_wakeups
;
1150 dead_task_statistics
.task_timer_wakeups_bin_1
+= task
->task_timer_wakeups_bin_1
;
1151 dead_task_statistics
.task_timer_wakeups_bin_2
+= task
->task_timer_wakeups_bin_2
;
1153 lck_spin_unlock(&dead_task_statistics_lock
);
1154 lck_mtx_destroy(&task
->lock
, &task_lck_grp
);
1156 if (!ledger_get_entries(task
->ledger
, task_ledgers
.tkm_private
, &credit
,
1158 OSAddAtomic64(credit
, (int64_t *)&tasks_tkm_private
.alloc
);
1159 OSAddAtomic64(debit
, (int64_t *)&tasks_tkm_private
.free
);
1161 if (!ledger_get_entries(task
->ledger
, task_ledgers
.tkm_shared
, &credit
,
1163 OSAddAtomic64(credit
, (int64_t *)&tasks_tkm_shared
.alloc
);
1164 OSAddAtomic64(debit
, (int64_t *)&tasks_tkm_shared
.free
);
1166 ledger_dereference(task
->ledger
);
1167 zinfo_task_free(task
);
1169 #if TASK_REFERENCE_LEAK_DEBUG
1170 btlog_remove_entries_for_element(task_ref_btlog
, task
);
1173 #if CONFIG_COALITIONS
1174 if (!task
->coalition
[COALITION_TYPE_RESOURCE
])
1175 panic("deallocating task was not a member of a resource coalition");
1176 task_release_coalitions(task
);
1177 #endif /* CONFIG_COALITIONS */
1179 bzero(task
->coalition
, sizeof(task
->coalition
));
1182 /* clean up collected information since last reference to task is gone */
1183 if (task
->corpse_info
) {
1184 task_crashinfo_destroy(task
->corpse_info
);
1185 task
->corpse_info
= NULL
;
1189 zfree(task_zone
, task
);
1193 * task_name_deallocate:
1195 * Drop a reference on a task name.
1198 task_name_deallocate(
1199 task_name_t task_name
)
1201 return(task_deallocate((task_t
)task_name
));
1205 * task_suspension_token_deallocate:
1207 * Drop a reference on a task suspension token.
1210 task_suspension_token_deallocate(
1211 task_suspension_token_t token
)
1213 return(task_deallocate((task_t
)token
));
1218 * task_collect_crash_info:
1220 * collect crash info from bsd and mach based data
1223 task_collect_crash_info(task_t task
)
1225 kern_return_t kr
= KERN_SUCCESS
;
1227 kcdata_descriptor_t crash_data
= NULL
;
1228 kcdata_descriptor_t crash_data_release
= NULL
;
1229 mach_msg_type_number_t size
= CORPSEINFO_ALLOCATION_SIZE
;
1230 mach_vm_offset_t crash_data_user_ptr
= 0;
1232 if (!corpses_enabled()) {
1233 return KERN_NOT_SUPPORTED
;
1237 assert(task
->bsd_info
!= NULL
);
1238 if (task
->corpse_info
== NULL
&& task
->bsd_info
!= NULL
) {
1240 /* map crash data memory in task's vm map */
1241 kr
= mach_vm_allocate(task
->map
, &crash_data_user_ptr
, size
, (VM_MAKE_TAG(VM_MEMORY_CORPSEINFO
) | VM_FLAGS_ANYWHERE
));
1243 if (kr
!= KERN_SUCCESS
)
1246 crash_data
= task_crashinfo_alloc_init((mach_vm_address_t
)crash_data_user_ptr
, size
);
1249 crash_data_release
= task
->corpse_info
;
1250 task
->corpse_info
= crash_data
;
1254 /* if failed to create corpse info, free the mapping */
1255 if (KERN_SUCCESS
!= mach_vm_deallocate(task
->map
, crash_data_user_ptr
, size
)) {
1256 printf("mach_vm_deallocate failed to clear corpse_data for pid %d.\n", task_pid(task
));
1261 if (crash_data_release
!= NULL
) {
1262 task_crashinfo_destroy(crash_data_release
);
1273 * task_deliver_crash_notification:
1275 * Makes outcall to registered host port for a corpse.
1278 task_deliver_crash_notification(task_t task
)
1280 kcdata_descriptor_t crash_info
= task
->corpse_info
;
1281 thread_t th_iter
= NULL
;
1282 kern_return_t kr
= KERN_SUCCESS
;
1283 wait_interrupt_t wsave
;
1284 mach_exception_data_type_t code
[EXCEPTION_CODE_MAX
];
1286 if (crash_info
== NULL
)
1287 return KERN_FAILURE
;
1289 code
[0] = crash_info
->kcd_addr_begin
;
1290 code
[1] = crash_info
->kcd_length
;
1293 queue_iterate(&task
->threads
, th_iter
, thread_t
, task_threads
)
1295 ipc_thread_reset(th_iter
);
1299 wsave
= thread_interrupt_level(THREAD_UNINT
);
1300 kr
= exception_triage(EXC_CORPSE_NOTIFY
, code
, EXCEPTION_CODE_MAX
);
1301 if (kr
!= KERN_SUCCESS
) {
1302 printf("Failed to send exception EXC_CORPSE_NOTIFY. error code: %d for pid %d\n", kr
, task_pid(task
));
1306 * crash reporting is done. Now release threads
1307 * for reaping by thread_terminate_daemon
1310 assert(task
->active_thread_count
== 0);
1311 queue_iterate(&task
->threads
, th_iter
, thread_t
, task_threads
)
1313 thread_mtx_lock(th_iter
);
1314 assert(th_iter
->inspection
== TRUE
);
1315 th_iter
->inspection
= FALSE
;
1316 /* now that the corpse has been autopsied, dispose of the thread name */
1317 uthread_cleanup_name(th_iter
->uthread
);
1318 thread_mtx_unlock(th_iter
);
1321 thread_terminate_crashed_threads();
1322 /* remove the pending corpse report flag */
1323 task_clear_corpse_pending_report(task
);
1327 (void)thread_interrupt_level(wsave
);
1328 task_terminate_internal(task
);
1336 * Terminate the specified task. See comments on thread_terminate
1337 * (kern/thread.c) about problems with terminating the "current task."
1344 if (task
== TASK_NULL
)
1345 return (KERN_INVALID_ARGUMENT
);
1348 return (KERN_FAILURE
);
1350 return (task_terminate_internal(task
));
1354 extern int proc_pid(struct proc
*);
1355 extern void proc_name_kdp(task_t t
, char *buf
, int size
);
1356 #endif /* MACH_ASSERT */
1358 #define VM_MAP_PARTIAL_REAP 0x54 /* 0x150 */
1360 __unused
task_partial_reap(task_t task
, __unused
int pid
)
1362 unsigned int reclaimed_resident
= 0;
1363 unsigned int reclaimed_compressed
= 0;
1364 uint64_t task_page_count
;
1366 task_page_count
= (get_task_phys_footprint(task
) / PAGE_SIZE_64
);
1368 KERNEL_DEBUG_CONSTANT((MACHDBG_CODE(DBG_MACH_VM
, VM_MAP_PARTIAL_REAP
) | DBG_FUNC_START
),
1369 pid
, task_page_count
, 0, 0, 0);
1371 vm_map_partial_reap(task
->map
, &reclaimed_resident
, &reclaimed_compressed
);
1373 KERNEL_DEBUG_CONSTANT((MACHDBG_CODE(DBG_MACH_VM
, VM_MAP_PARTIAL_REAP
) | DBG_FUNC_END
),
1374 pid
, reclaimed_resident
, reclaimed_compressed
, 0, 0);
1378 task_mark_corpse(task_t task
)
1380 kern_return_t kr
= KERN_SUCCESS
;
1381 thread_t self_thread
;
1383 wait_interrupt_t wsave
;
1385 assert(task
!= kernel_task
);
1386 assert(task
== current_task());
1387 assert(!task_is_a_corpse(task
));
1389 kr
= task_collect_crash_info(task
);
1390 if (kr
!= KERN_SUCCESS
) {
1394 self_thread
= current_thread();
1396 wsave
= thread_interrupt_level(THREAD_UNINT
);
1399 task_set_corpse_pending_report(task
);
1400 task_set_corpse(task
);
1402 kr
= task_start_halt_locked(task
, TRUE
);
1403 assert(kr
== KERN_SUCCESS
);
1404 ipc_task_reset(task
);
1405 ipc_task_enable(task
);
1408 /* terminate the ipc space */
1409 ipc_space_terminate(task
->itk_space
);
1411 task_start_halt(task
);
1412 thread_terminate_internal(self_thread
);
1413 (void) thread_interrupt_level(wsave
);
1414 assert(task
->halting
== TRUE
);
1419 task_terminate_internal(
1422 thread_t thread
, self
;
1424 boolean_t interrupt_save
;
1427 assert(task
!= kernel_task
);
1429 self
= current_thread();
1430 self_task
= self
->task
;
1433 * Get the task locked and make sure that we are not racing
1434 * with someone else trying to terminate us.
1436 if (task
== self_task
)
1439 if (task
< self_task
) {
1441 task_lock(self_task
);
1444 task_lock(self_task
);
1448 if (!task
->active
) {
1450 * Task is already being terminated.
1451 * Just return an error. If we are dying, this will
1452 * just get us to our AST special handler and that
1453 * will get us to finalize the termination of ourselves.
1456 if (self_task
!= task
)
1457 task_unlock(self_task
);
1459 return (KERN_FAILURE
);
1462 if (task_corpse_pending_report(task
)) {
1464 * Task is marked for reporting as corpse.
1465 * Just return an error. This will
1466 * just get us to our AST special handler and that
1467 * will get us to finish the path to death
1470 if (self_task
!= task
)
1471 task_unlock(self_task
);
1473 return (KERN_FAILURE
);
1476 if (self_task
!= task
)
1477 task_unlock(self_task
);
1480 * Make sure the current thread does not get aborted out of
1481 * the waits inside these operations.
1483 interrupt_save
= thread_interrupt_level(THREAD_UNINT
);
1486 * Indicate that we want all the threads to stop executing
1487 * at user space by holding the task (we would have held
1488 * each thread independently in thread_terminate_internal -
1489 * but this way we may be more likely to already find it
1490 * held there). Mark the task inactive, and prevent
1491 * further task operations via the task port.
1493 task_hold_locked(task
);
1494 task
->active
= FALSE
;
1495 ipc_task_disable(task
);
1497 #if CONFIG_TELEMETRY
1499 * Notify telemetry that this task is going away.
1501 telemetry_task_ctl_locked(task
, TF_TELEMETRY
, 0);
1505 * Terminate each thread in the task.
1507 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
1508 thread_terminate_internal(thread
);
1512 if (task
->bsd_info
!= NULL
) {
1513 pid
= proc_pid(task
->bsd_info
);
1515 #endif /* MACH_BSD */
1519 proc_set_task_policy(task
, THREAD_NULL
, TASK_POLICY_ATTRIBUTE
,
1520 TASK_POLICY_TERMINATED
, TASK_POLICY_ENABLE
);
1522 /* Early object reap phase */
1524 // PR-17045188: Revisit implementation
1525 // task_partial_reap(task, pid);
1529 * Destroy all synchronizers owned by the task.
1531 task_synchronizer_destroy_all(task
);
1534 * Destroy the IPC space, leaving just a reference for it.
1536 ipc_space_terminate(task
->itk_space
);
1539 /* if some ledgers go negative on tear-down again... */
1540 ledger_disable_panic_on_negative(task
->map
->pmap
->ledger
,
1541 task_ledgers
.phys_footprint
);
1542 ledger_disable_panic_on_negative(task
->map
->pmap
->ledger
,
1543 task_ledgers
.internal
);
1544 ledger_disable_panic_on_negative(task
->map
->pmap
->ledger
,
1545 task_ledgers
.internal_compressed
);
1546 ledger_disable_panic_on_negative(task
->map
->pmap
->ledger
,
1547 task_ledgers
.iokit_mapped
);
1548 ledger_disable_panic_on_negative(task
->map
->pmap
->ledger
,
1549 task_ledgers
.alternate_accounting
);
1550 ledger_disable_panic_on_negative(task
->map
->pmap
->ledger
,
1551 task_ledgers
.alternate_accounting_compressed
);
1555 * If the current thread is a member of the task
1556 * being terminated, then the last reference to
1557 * the task will not be dropped until the thread
1558 * is finally reaped. To avoid incurring the
1559 * expense of removing the address space regions
1560 * at reap time, we do it explictly here.
1563 vm_map_lock(task
->map
);
1564 vm_map_disable_hole_optimization(task
->map
);
1565 vm_map_unlock(task
->map
);
1567 vm_map_remove(task
->map
,
1568 task
->map
->min_offset
,
1569 task
->map
->max_offset
,
1570 /* no unnesting on final cleanup: */
1571 VM_MAP_REMOVE_NO_UNNESTING
);
1573 /* release our shared region */
1574 vm_shared_region_set(task
, NULL
);
1579 * Identify the pmap's process, in case the pmap ledgers drift
1580 * and we have to report it.
1583 if (task
->bsd_info
) {
1584 pid
= proc_pid(task
->bsd_info
);
1585 proc_name_kdp(task
, procname
, sizeof (procname
));
1588 strlcpy(procname
, "<unknown>", sizeof (procname
));
1590 pmap_set_process(task
->map
->pmap
, pid
, procname
);
1591 #endif /* MACH_ASSERT */
1593 lck_mtx_lock(&tasks_threads_lock
);
1594 queue_remove(&tasks
, task
, task_t
, tasks
);
1595 queue_enter(&terminated_tasks
, task
, task_t
, tasks
);
1597 terminated_tasks_count
++;
1598 lck_mtx_unlock(&tasks_threads_lock
);
1601 * We no longer need to guard against being aborted, so restore
1602 * the previous interruptible state.
1604 thread_interrupt_level(interrupt_save
);
1607 /* force the task to release all ctrs */
1608 if (task
->t_chud
& TASK_KPC_FORCED_ALL_CTRS
)
1609 kpc_force_all_ctrs(task
, 0);
1612 #if CONFIG_COALITIONS
1614 * Leave our coalitions. (drop activation but not reference)
1616 coalitions_remove_task(task
);
1620 * Get rid of the task active reference on itself.
1622 task_deallocate(task
);
1624 return (KERN_SUCCESS
);
1628 tasks_system_suspend(boolean_t suspend
)
1632 lck_mtx_lock(&tasks_threads_lock
);
1633 assert(tasks_suspend_state
!= suspend
);
1634 tasks_suspend_state
= suspend
;
1635 queue_iterate(&tasks
, task
, task_t
, tasks
) {
1636 if (task
== kernel_task
) {
1639 suspend
? task_suspend_internal(task
) : task_resume_internal(task
);
1641 lck_mtx_unlock(&tasks_threads_lock
);
1647 * Shut the current task down (except for the current thread) in
1648 * preparation for dramatic changes to the task (probably exec).
1649 * We hold the task and mark all other threads in the task for
1653 task_start_halt(task_t task
)
1655 kern_return_t kr
= KERN_SUCCESS
;
1657 kr
= task_start_halt_locked(task
, FALSE
);
1662 static kern_return_t
1663 task_start_halt_locked(task_t task
, boolean_t should_mark_corpse
)
1665 thread_t thread
, self
;
1666 uint64_t dispatchqueue_offset
;
1668 assert(task
!= kernel_task
);
1670 self
= current_thread();
1672 if (task
!= self
->task
)
1673 return (KERN_INVALID_ARGUMENT
);
1675 if (task
->halting
|| !task
->active
|| !self
->active
) {
1677 * Task or current thread is already being terminated.
1678 * Hurry up and return out of the current kernel context
1679 * so that we run our AST special handler to terminate
1682 return (KERN_FAILURE
);
1685 task
->halting
= TRUE
;
1688 * Mark all the threads to keep them from starting any more
1689 * user-level execution. The thread_terminate_internal code
1690 * would do this on a thread by thread basis anyway, but this
1691 * gives us a better chance of not having to wait there.
1693 task_hold_locked(task
);
1694 dispatchqueue_offset
= get_dispatchqueue_offset_from_proc(task
->bsd_info
);
1697 * Terminate all the other threads in the task.
1699 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
)
1701 if (should_mark_corpse
) {
1702 thread_mtx_lock(thread
);
1703 thread
->inspection
= TRUE
;
1704 thread_mtx_unlock(thread
);
1707 thread_terminate_internal(thread
);
1709 task
->dispatchqueue_offset
= dispatchqueue_offset
;
1711 task_release_locked(task
);
1713 return KERN_SUCCESS
;
1718 * task_complete_halt:
1720 * Complete task halt by waiting for threads to terminate, then clean
1721 * up task resources (VM, port namespace, etc...) and then let the
1722 * current thread go in the (practically empty) task context.
1725 task_complete_halt(task_t task
)
1728 assert(task
->halting
);
1729 assert(task
== current_task());
1732 * Wait for the other threads to get shut down.
1733 * When the last other thread is reaped, we'll be
1736 if (task
->thread_count
> 1) {
1737 assert_wait((event_t
)&task
->halting
, THREAD_UNINT
);
1739 thread_block(THREAD_CONTINUE_NULL
);
1745 * Give the machine dependent code a chance
1746 * to perform cleanup of task-level resources
1747 * associated with the current thread before
1748 * ripping apart the task.
1750 machine_task_terminate(task
);
1753 * Destroy all synchronizers owned by the task.
1755 task_synchronizer_destroy_all(task
);
1758 * Destroy the contents of the IPC space, leaving just
1759 * a reference for it.
1761 ipc_space_clean(task
->itk_space
);
1764 * Clean out the address space, as we are going to be
1765 * getting a new one.
1767 vm_map_remove(task
->map
, task
->map
->min_offset
,
1768 task
->map
->max_offset
,
1769 /* no unnesting on final cleanup: */
1770 VM_MAP_REMOVE_NO_UNNESTING
);
1772 task
->halting
= FALSE
;
1778 * Suspend execution of the specified task.
1779 * This is a recursive-style suspension of the task, a count of
1780 * suspends is maintained.
1782 * CONDITIONS: the task is locked and active.
1786 register task_t task
)
1788 register thread_t thread
;
1790 assert(task
->active
);
1792 if (task
->suspend_count
++ > 0)
1796 * Iterate through all the threads and hold them.
1798 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
1799 thread_mtx_lock(thread
);
1800 thread_hold(thread
);
1801 thread_mtx_unlock(thread
);
1808 * Same as the internal routine above, except that is must lock
1809 * and verify that the task is active. This differs from task_suspend
1810 * in that it places a kernel hold on the task rather than just a
1811 * user-level hold. This keeps users from over resuming and setting
1812 * it running out from under the kernel.
1814 * CONDITIONS: the caller holds a reference on the task
1818 register task_t task
)
1820 if (task
== TASK_NULL
)
1821 return (KERN_INVALID_ARGUMENT
);
1825 if (!task
->active
) {
1828 return (KERN_FAILURE
);
1831 task_hold_locked(task
);
1834 return (KERN_SUCCESS
);
1840 boolean_t until_not_runnable
)
1842 if (task
== TASK_NULL
)
1843 return (KERN_INVALID_ARGUMENT
);
1847 if (!task
->active
) {
1850 return (KERN_FAILURE
);
1853 task_wait_locked(task
, until_not_runnable
);
1856 return (KERN_SUCCESS
);
1862 * Wait for all threads in task to stop.
1865 * Called with task locked, active, and held.
1869 register task_t task
,
1870 boolean_t until_not_runnable
)
1872 register thread_t thread
, self
;
1874 assert(task
->active
);
1875 assert(task
->suspend_count
> 0);
1877 self
= current_thread();
1880 * Iterate through all the threads and wait for them to
1881 * stop. Do not wait for the current thread if it is within
1884 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
1886 thread_wait(thread
, until_not_runnable
);
1891 * task_release_locked:
1893 * Release a kernel hold on a task.
1895 * CONDITIONS: the task is locked and active
1898 task_release_locked(
1899 register task_t task
)
1901 register thread_t thread
;
1903 assert(task
->active
);
1904 assert(task
->suspend_count
> 0);
1906 if (--task
->suspend_count
> 0)
1909 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
1910 thread_mtx_lock(thread
);
1911 thread_release(thread
);
1912 thread_mtx_unlock(thread
);
1919 * Same as the internal routine above, except that it must lock
1920 * and verify that the task is active.
1922 * CONDITIONS: The caller holds a reference to the task
1928 if (task
== TASK_NULL
)
1929 return (KERN_INVALID_ARGUMENT
);
1933 if (!task
->active
) {
1936 return (KERN_FAILURE
);
1939 task_release_locked(task
);
1942 return (KERN_SUCCESS
);
1948 thread_act_array_t
*threads_out
,
1949 mach_msg_type_number_t
*count
)
1951 mach_msg_type_number_t actual
;
1952 thread_t
*thread_list
;
1954 vm_size_t size
, size_needed
;
1958 if (task
== TASK_NULL
)
1959 return (KERN_INVALID_ARGUMENT
);
1961 size
= 0; addr
= NULL
;
1965 if (!task
->active
) {
1971 return (KERN_FAILURE
);
1974 actual
= task
->thread_count
;
1976 /* do we have the memory we need? */
1977 size_needed
= actual
* sizeof (mach_port_t
);
1978 if (size_needed
<= size
)
1981 /* unlock the task and allocate more memory */
1987 assert(size_needed
> 0);
1990 addr
= kalloc(size
);
1992 return (KERN_RESOURCE_SHORTAGE
);
1995 /* OK, have memory and the task is locked & active */
1996 thread_list
= (thread_t
*)addr
;
2000 for (thread
= (thread_t
)queue_first(&task
->threads
); i
< actual
;
2001 ++i
, thread
= (thread_t
)queue_next(&thread
->task_threads
)) {
2002 thread_reference_internal(thread
);
2003 thread_list
[j
++] = thread
;
2006 assert(queue_end(&task
->threads
, (queue_entry_t
)thread
));
2009 size_needed
= actual
* sizeof (mach_port_t
);
2011 /* can unlock task now that we've got the thread refs */
2015 /* no threads, so return null pointer and deallocate memory */
2017 *threads_out
= NULL
;
2024 /* if we allocated too much, must copy */
2026 if (size_needed
< size
) {
2029 newaddr
= kalloc(size_needed
);
2031 for (i
= 0; i
< actual
; ++i
)
2032 thread_deallocate(thread_list
[i
]);
2034 return (KERN_RESOURCE_SHORTAGE
);
2037 bcopy(addr
, newaddr
, size_needed
);
2039 thread_list
= (thread_t
*)newaddr
;
2042 *threads_out
= thread_list
;
2045 /* do the conversion that Mig should handle */
2047 for (i
= 0; i
< actual
; ++i
)
2048 ((ipc_port_t
*) thread_list
)[i
] = convert_thread_to_port(thread_list
[i
]);
2051 return (KERN_SUCCESS
);
2054 #define TASK_HOLD_NORMAL 0
2055 #define TASK_HOLD_PIDSUSPEND 1
2056 #define TASK_HOLD_LEGACY 2
2057 #define TASK_HOLD_LEGACY_ALL 3
2059 static kern_return_t
2061 register task_t task
,
2064 if (!task
->active
) {
2065 return (KERN_FAILURE
);
2068 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
2069 MACHDBG_CODE(DBG_MACH_IPC
,MACH_TASK_SUSPEND
) | DBG_FUNC_NONE
,
2070 task_pid(task
), ((thread_t
)queue_first(&task
->threads
))->thread_id
,
2071 task
->user_stop_count
, task
->user_stop_count
+ 1, 0);
2074 current_task()->suspends_outstanding
++;
2077 if (mode
== TASK_HOLD_LEGACY
)
2078 task
->legacy_stop_count
++;
2080 if (task
->user_stop_count
++ > 0) {
2082 * If the stop count was positive, the task is
2083 * already stopped and we can exit.
2085 return (KERN_SUCCESS
);
2089 * Put a kernel-level hold on the threads in the task (all
2090 * user-level task suspensions added together represent a
2091 * single kernel-level hold). We then wait for the threads
2092 * to stop executing user code.
2094 task_hold_locked(task
);
2095 task_wait_locked(task
, FALSE
);
2097 return (KERN_SUCCESS
);
2100 static kern_return_t
2102 register task_t task
,
2105 register boolean_t release
= FALSE
;
2107 if (!task
->active
) {
2108 return (KERN_FAILURE
);
2111 if (mode
== TASK_HOLD_PIDSUSPEND
) {
2112 if (task
->pidsuspended
== FALSE
) {
2113 return (KERN_FAILURE
);
2115 task
->pidsuspended
= FALSE
;
2118 if (task
->user_stop_count
> (task
->pidsuspended
? 1 : 0)) {
2120 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
2121 MACHDBG_CODE(DBG_MACH_IPC
,MACH_TASK_RESUME
) | DBG_FUNC_NONE
,
2122 task_pid(task
), ((thread_t
)queue_first(&task
->threads
))->thread_id
,
2123 task
->user_stop_count
, mode
, task
->legacy_stop_count
);
2127 * This is obviously not robust; if we suspend one task and then resume a different one,
2128 * we'll fly under the radar. This is only meant to catch the common case of a crashed
2129 * or buggy suspender.
2131 current_task()->suspends_outstanding
--;
2134 if (mode
== TASK_HOLD_LEGACY_ALL
) {
2135 if (task
->legacy_stop_count
>= task
->user_stop_count
) {
2136 task
->user_stop_count
= 0;
2139 task
->user_stop_count
-= task
->legacy_stop_count
;
2141 task
->legacy_stop_count
= 0;
2143 if (mode
== TASK_HOLD_LEGACY
&& task
->legacy_stop_count
> 0)
2144 task
->legacy_stop_count
--;
2145 if (--task
->user_stop_count
== 0)
2150 return (KERN_FAILURE
);
2154 * Release the task if necessary.
2157 task_release_locked(task
);
2159 return (KERN_SUCCESS
);
2166 * Implement an (old-fashioned) user-level suspension on a task.
2168 * Because the user isn't expecting to have to manage a suspension
2169 * token, we'll track it for him in the kernel in the form of a naked
2170 * send right to the task's resume port. All such send rights
2171 * account for a single suspension against the task (unlike task_suspend2()
2172 * where each caller gets a unique suspension count represented by a
2173 * unique send-once right).
2176 * The caller holds a reference to the task
2180 register task_t task
)
2183 mach_port_t port
, send
, old_notify
;
2184 mach_port_name_t name
;
2186 if (task
== TASK_NULL
|| task
== kernel_task
)
2187 return (KERN_INVALID_ARGUMENT
);
2192 * Claim a send right on the task resume port, and request a no-senders
2193 * notification on that port (if none outstanding).
2195 if (task
->itk_resume
== IP_NULL
) {
2196 task
->itk_resume
= ipc_port_alloc_kernel();
2197 if (!IP_VALID(task
->itk_resume
))
2198 panic("failed to create resume port");
2199 ipc_kobject_set(task
->itk_resume
, (ipc_kobject_t
)task
, IKOT_TASK_RESUME
);
2202 port
= task
->itk_resume
;
2204 assert(ip_active(port
));
2206 send
= ipc_port_make_send_locked(port
);
2207 assert(IP_VALID(send
));
2209 if (port
->ip_nsrequest
== IP_NULL
) {
2210 ipc_port_nsrequest(port
, port
->ip_mscount
, ipc_port_make_sonce_locked(port
), &old_notify
);
2211 assert(old_notify
== IP_NULL
);
2218 * place a legacy hold on the task.
2220 kr
= place_task_hold(task
, TASK_HOLD_LEGACY
);
2221 if (kr
!= KERN_SUCCESS
) {
2223 ipc_port_release_send(send
);
2230 * Copyout the send right into the calling task's IPC space. It won't know it is there,
2231 * but we'll look it up when calling a traditional resume. Any IPC operations that
2232 * deallocate the send right will auto-release the suspension.
2234 if ((kr
= ipc_kmsg_copyout_object(current_task()->itk_space
, (ipc_object_t
)send
,
2235 MACH_MSG_TYPE_MOVE_SEND
, &name
)) != KERN_SUCCESS
) {
2236 printf("warning: %s(%d) failed to copyout suspension token for pid %d with error: %d\n",
2237 proc_name_address(current_task()->bsd_info
), proc_pid(current_task()->bsd_info
),
2238 task_pid(task
), kr
);
2247 * Release a user hold on a task.
2250 * The caller holds a reference to the task
2254 register task_t task
)
2257 mach_port_name_t resume_port_name
;
2258 ipc_entry_t resume_port_entry
;
2259 ipc_space_t space
= current_task()->itk_space
;
2261 if (task
== TASK_NULL
|| task
== kernel_task
)
2262 return (KERN_INVALID_ARGUMENT
);
2264 /* release a legacy task hold */
2266 kr
= release_task_hold(task
, TASK_HOLD_LEGACY
);
2269 is_write_lock(space
);
2270 if (is_active(space
) && IP_VALID(task
->itk_resume
) &&
2271 ipc_hash_lookup(space
, (ipc_object_t
)task
->itk_resume
, &resume_port_name
, &resume_port_entry
) == TRUE
) {
2273 * We found a suspension token in the caller's IPC space. Release a send right to indicate that
2274 * we are holding one less legacy hold on the task from this caller. If the release failed,
2275 * go ahead and drop all the rights, as someone either already released our holds or the task
2278 if (kr
== KERN_SUCCESS
)
2279 ipc_right_dealloc(space
, resume_port_name
, resume_port_entry
);
2281 ipc_right_destroy(space
, resume_port_name
, resume_port_entry
, FALSE
, 0);
2282 /* space unlocked */
2284 is_write_unlock(space
);
2285 if (kr
== KERN_SUCCESS
)
2286 printf("warning: %s(%d) performed out-of-band resume on pid %d\n",
2287 proc_name_address(current_task()->bsd_info
), proc_pid(current_task()->bsd_info
),
2295 * Suspend the target task.
2296 * Making/holding a token/reference/port is the callers responsibility.
2299 task_suspend_internal(task_t task
)
2303 if (task
== TASK_NULL
|| task
== kernel_task
)
2304 return (KERN_INVALID_ARGUMENT
);
2307 kr
= place_task_hold(task
, TASK_HOLD_NORMAL
);
2313 * Suspend the target task, and return a suspension token. The token
2314 * represents a reference on the suspended task.
2318 register task_t task
,
2319 task_suspension_token_t
*suspend_token
)
2323 kr
= task_suspend_internal(task
);
2324 if (kr
!= KERN_SUCCESS
) {
2325 *suspend_token
= TASK_NULL
;
2330 * Take a reference on the target task and return that to the caller
2331 * as a "suspension token," which can be converted into an SO right to
2332 * the now-suspended task's resume port.
2334 task_reference_internal(task
);
2335 *suspend_token
= task
;
2337 return (KERN_SUCCESS
);
2342 * (reference/token/port management is caller's responsibility).
2345 task_resume_internal(
2346 register task_suspension_token_t task
)
2350 if (task
== TASK_NULL
|| task
== kernel_task
)
2351 return (KERN_INVALID_ARGUMENT
);
2354 kr
= release_task_hold(task
, TASK_HOLD_NORMAL
);
2360 * Resume the task using a suspension token. Consumes the token's ref.
2364 register task_suspension_token_t task
)
2368 kr
= task_resume_internal(task
);
2369 task_suspension_token_deallocate(task
);
2375 task_suspension_notify(mach_msg_header_t
*request_header
)
2377 ipc_port_t port
= (ipc_port_t
) request_header
->msgh_remote_port
;
2378 task_t task
= convert_port_to_task_suspension_token(port
);
2379 mach_msg_type_number_t not_count
;
2381 if (task
== TASK_NULL
|| task
== kernel_task
)
2382 return TRUE
; /* nothing to do */
2384 switch (request_header
->msgh_id
) {
2386 case MACH_NOTIFY_SEND_ONCE
:
2387 /* release the hold held by this specific send-once right */
2389 release_task_hold(task
, TASK_HOLD_NORMAL
);
2393 case MACH_NOTIFY_NO_SENDERS
:
2394 not_count
= ((mach_no_senders_notification_t
*)request_header
)->not_count
;
2398 if (port
->ip_mscount
== not_count
) {
2400 /* release all the [remaining] outstanding legacy holds */
2401 assert(port
->ip_nsrequest
== IP_NULL
);
2403 release_task_hold(task
, TASK_HOLD_LEGACY_ALL
);
2406 } else if (port
->ip_nsrequest
== IP_NULL
) {
2407 ipc_port_t old_notify
;
2410 /* new send rights, re-arm notification at current make-send count */
2411 ipc_port_nsrequest(port
, port
->ip_mscount
, ipc_port_make_sonce_locked(port
), &old_notify
);
2412 assert(old_notify
== IP_NULL
);
2424 task_suspension_token_deallocate(task
); /* drop token reference */
2429 task_pidsuspend_locked(task_t task
)
2433 if (task
->pidsuspended
) {
2438 task
->pidsuspended
= TRUE
;
2440 kr
= place_task_hold(task
, TASK_HOLD_PIDSUSPEND
);
2441 if (kr
!= KERN_SUCCESS
) {
2442 task
->pidsuspended
= FALSE
;
2452 * Suspends a task by placing a hold on its threads.
2455 * The caller holds a reference to the task
2459 register task_t task
)
2463 if (task
== TASK_NULL
|| task
== kernel_task
)
2464 return (KERN_INVALID_ARGUMENT
);
2468 kr
= task_pidsuspend_locked(task
);
2475 /* If enabled, we bring all the frozen pages back in prior to resumption; otherwise, they're faulted back in on demand */
2476 #define THAW_ON_RESUME 1
2480 * Resumes a previously suspended task.
2483 * The caller holds a reference to the task
2487 register task_t task
)
2491 if (task
== TASK_NULL
|| task
== kernel_task
)
2492 return (KERN_INVALID_ARGUMENT
);
2496 #if (CONFIG_FREEZE && THAW_ON_RESUME)
2498 while (task
->changing_freeze_state
) {
2500 assert_wait((event_t
)&task
->changing_freeze_state
, THREAD_UNINT
);
2502 thread_block(THREAD_CONTINUE_NULL
);
2506 task
->changing_freeze_state
= TRUE
;
2509 kr
= release_task_hold(task
, TASK_HOLD_PIDSUSPEND
);
2513 #if (CONFIG_FREEZE && THAW_ON_RESUME)
2514 if ((kr
== KERN_SUCCESS
) && (task
->frozen
== TRUE
)) {
2516 if (COMPRESSED_PAGER_IS_ACTIVE
|| DEFAULT_FREEZER_COMPRESSED_PAGER_IS_ACTIVE
) {
2521 kr
= vm_map_thaw(task
->map
);
2526 if (kr
== KERN_SUCCESS
)
2527 task
->frozen
= FALSE
;
2528 task
->changing_freeze_state
= FALSE
;
2529 thread_wakeup(&task
->changing_freeze_state
);
2545 * The caller holds a reference to the task
2547 extern void vm_wake_compactor_swapper();
2548 extern queue_head_t c_swapout_list_head
;
2552 register task_t task
,
2553 uint32_t *purgeable_count
,
2554 uint32_t *wired_count
,
2555 uint32_t *clean_count
,
2556 uint32_t *dirty_count
,
2557 uint32_t dirty_budget
,
2559 boolean_t walk_only
)
2563 if (task
== TASK_NULL
|| task
== kernel_task
)
2564 return (KERN_INVALID_ARGUMENT
);
2568 while (task
->changing_freeze_state
) {
2570 assert_wait((event_t
)&task
->changing_freeze_state
, THREAD_UNINT
);
2572 thread_block(THREAD_CONTINUE_NULL
);
2578 return (KERN_FAILURE
);
2580 task
->changing_freeze_state
= TRUE
;
2585 kr
= vm_map_freeze_walk(task
->map
, purgeable_count
, wired_count
, clean_count
, dirty_count
, dirty_budget
, shared
);
2587 kr
= vm_map_freeze(task
->map
, purgeable_count
, wired_count
, clean_count
, dirty_count
, dirty_budget
, shared
);
2592 if (walk_only
== FALSE
&& kr
== KERN_SUCCESS
)
2593 task
->frozen
= TRUE
;
2594 task
->changing_freeze_state
= FALSE
;
2595 thread_wakeup(&task
->changing_freeze_state
);
2599 if (COMPRESSED_PAGER_IS_ACTIVE
|| DEFAULT_FREEZER_COMPRESSED_PAGER_IS_ACTIVE
) {
2600 vm_wake_compactor_swapper();
2602 * We do an explicit wakeup of the swapout thread here
2603 * because the compact_and_swap routines don't have
2604 * knowledge about these kind of "per-task packed c_segs"
2605 * and so will not be evaluating whether we need to do
2608 thread_wakeup((event_t
)&c_swapout_list_head
);
2617 * Thaw a currently frozen task.
2620 * The caller holds a reference to the task
2624 register task_t task
)
2628 if (task
== TASK_NULL
|| task
== kernel_task
)
2629 return (KERN_INVALID_ARGUMENT
);
2633 while (task
->changing_freeze_state
) {
2635 assert_wait((event_t
)&task
->changing_freeze_state
, THREAD_UNINT
);
2637 thread_block(THREAD_CONTINUE_NULL
);
2641 if (!task
->frozen
) {
2643 return (KERN_FAILURE
);
2645 task
->changing_freeze_state
= TRUE
;
2647 if (DEFAULT_PAGER_IS_ACTIVE
|| DEFAULT_FREEZER_IS_ACTIVE
) {
2650 kr
= vm_map_thaw(task
->map
);
2654 if (kr
== KERN_SUCCESS
)
2655 task
->frozen
= FALSE
;
2657 task
->frozen
= FALSE
;
2661 task
->changing_freeze_state
= FALSE
;
2662 thread_wakeup(&task
->changing_freeze_state
);
2666 if (COMPRESSED_PAGER_IS_ACTIVE
|| DEFAULT_FREEZER_COMPRESSED_PAGER_IS_ACTIVE
) {
2667 vm_wake_compactor_swapper();
2673 #endif /* CONFIG_FREEZE */
2676 host_security_set_task_token(
2677 host_security_t host_security
,
2679 security_token_t sec_token
,
2680 audit_token_t audit_token
,
2681 host_priv_t host_priv
)
2683 ipc_port_t host_port
;
2686 if (task
== TASK_NULL
)
2687 return(KERN_INVALID_ARGUMENT
);
2689 if (host_security
== HOST_NULL
)
2690 return(KERN_INVALID_SECURITY
);
2693 task
->sec_token
= sec_token
;
2694 task
->audit_token
= audit_token
;
2698 if (host_priv
!= HOST_PRIV_NULL
) {
2699 kr
= host_get_host_priv_port(host_priv
, &host_port
);
2701 kr
= host_get_host_port(host_priv_self(), &host_port
);
2703 assert(kr
== KERN_SUCCESS
);
2704 kr
= task_set_special_port(task
, TASK_HOST_PORT
, host_port
);
2709 task_send_trace_memory(
2711 __unused
uint32_t pid
,
2712 __unused
uint64_t uniqueid
)
2714 kern_return_t kr
= KERN_INVALID_ARGUMENT
;
2715 if (target_task
== TASK_NULL
)
2716 return (KERN_INVALID_ARGUMENT
);
2719 kr
= atm_send_proc_inspect_notification(target_task
,
2727 * This routine was added, pretty much exclusively, for registering the
2728 * RPC glue vector for in-kernel short circuited tasks. Rather than
2729 * removing it completely, I have only disabled that feature (which was
2730 * the only feature at the time). It just appears that we are going to
2731 * want to add some user data to tasks in the future (i.e. bsd info,
2732 * task names, etc...), so I left it in the formal task interface.
2737 task_flavor_t flavor
,
2738 __unused task_info_t task_info_in
, /* pointer to IN array */
2739 __unused mach_msg_type_number_t task_info_count
)
2741 if (task
== TASK_NULL
)
2742 return(KERN_INVALID_ARGUMENT
);
2747 case TASK_TRACE_MEMORY_INFO
:
2749 if (task_info_count
!= TASK_TRACE_MEMORY_INFO_COUNT
)
2750 return (KERN_INVALID_ARGUMENT
);
2752 assert(task_info_in
!= NULL
);
2753 task_trace_memory_info_t mem_info
;
2754 mem_info
= (task_trace_memory_info_t
) task_info_in
;
2755 kern_return_t kr
= atm_register_trace_memory(task
,
2756 mem_info
->user_memory_address
,
2757 mem_info
->buffer_size
);
2764 return (KERN_INVALID_ARGUMENT
);
2766 return (KERN_SUCCESS
);
2769 int radar_20146450
= 1;
2773 task_flavor_t flavor
,
2774 task_info_t task_info_out
,
2775 mach_msg_type_number_t
*task_info_count
)
2777 kern_return_t error
= KERN_SUCCESS
;
2779 if (task
== TASK_NULL
)
2780 return (KERN_INVALID_ARGUMENT
);
2784 if ((task
!= current_task()) && (!task
->active
)) {
2786 return (KERN_INVALID_ARGUMENT
);
2791 case TASK_BASIC_INFO_32
:
2792 case TASK_BASIC2_INFO_32
:
2794 task_basic_info_32_t basic_info
;
2799 if (*task_info_count
< TASK_BASIC_INFO_32_COUNT
) {
2800 error
= KERN_INVALID_ARGUMENT
;
2804 basic_info
= (task_basic_info_32_t
)task_info_out
;
2806 map
= (task
== kernel_task
)? kernel_map
: task
->map
;
2807 basic_info
->virtual_size
= (typeof(basic_info
->virtual_size
))map
->size
;
2808 if (flavor
== TASK_BASIC2_INFO_32
) {
2810 * The "BASIC2" flavor gets the maximum resident
2811 * size instead of the current resident size...
2813 basic_info
->resident_size
= pmap_resident_max(map
->pmap
);
2815 basic_info
->resident_size
= pmap_resident_count(map
->pmap
);
2817 basic_info
->resident_size
*= PAGE_SIZE
;
2819 basic_info
->policy
= ((task
!= kernel_task
)?
2820 POLICY_TIMESHARE
: POLICY_RR
);
2821 basic_info
->suspend_count
= task
->user_stop_count
;
2823 absolutetime_to_microtime(task
->total_user_time
, &secs
, &usecs
);
2824 basic_info
->user_time
.seconds
=
2825 (typeof(basic_info
->user_time
.seconds
))secs
;
2826 basic_info
->user_time
.microseconds
= usecs
;
2828 absolutetime_to_microtime(task
->total_system_time
, &secs
, &usecs
);
2829 basic_info
->system_time
.seconds
=
2830 (typeof(basic_info
->system_time
.seconds
))secs
;
2831 basic_info
->system_time
.microseconds
= usecs
;
2833 *task_info_count
= TASK_BASIC_INFO_32_COUNT
;
2837 case TASK_BASIC_INFO_64
:
2839 task_basic_info_64_t basic_info
;
2844 if (*task_info_count
< TASK_BASIC_INFO_64_COUNT
) {
2845 error
= KERN_INVALID_ARGUMENT
;
2849 basic_info
= (task_basic_info_64_t
)task_info_out
;
2851 map
= (task
== kernel_task
)? kernel_map
: task
->map
;
2852 basic_info
->virtual_size
= map
->size
;
2853 basic_info
->resident_size
=
2854 (mach_vm_size_t
)(pmap_resident_count(map
->pmap
))
2857 basic_info
->policy
= ((task
!= kernel_task
)?
2858 POLICY_TIMESHARE
: POLICY_RR
);
2859 basic_info
->suspend_count
= task
->user_stop_count
;
2861 absolutetime_to_microtime(task
->total_user_time
, &secs
, &usecs
);
2862 basic_info
->user_time
.seconds
=
2863 (typeof(basic_info
->user_time
.seconds
))secs
;
2864 basic_info
->user_time
.microseconds
= usecs
;
2866 absolutetime_to_microtime(task
->total_system_time
, &secs
, &usecs
);
2867 basic_info
->system_time
.seconds
=
2868 (typeof(basic_info
->system_time
.seconds
))secs
;
2869 basic_info
->system_time
.microseconds
= usecs
;
2871 *task_info_count
= TASK_BASIC_INFO_64_COUNT
;
2875 case MACH_TASK_BASIC_INFO
:
2877 mach_task_basic_info_t basic_info
;
2882 if (*task_info_count
< MACH_TASK_BASIC_INFO_COUNT
) {
2883 error
= KERN_INVALID_ARGUMENT
;
2887 basic_info
= (mach_task_basic_info_t
)task_info_out
;
2889 map
= (task
== kernel_task
) ? kernel_map
: task
->map
;
2891 basic_info
->virtual_size
= map
->size
;
2893 basic_info
->resident_size
=
2894 (mach_vm_size_t
)(pmap_resident_count(map
->pmap
));
2895 basic_info
->resident_size
*= PAGE_SIZE_64
;
2897 basic_info
->resident_size_max
=
2898 (mach_vm_size_t
)(pmap_resident_max(map
->pmap
));
2899 basic_info
->resident_size_max
*= PAGE_SIZE_64
;
2901 basic_info
->policy
= ((task
!= kernel_task
) ?
2902 POLICY_TIMESHARE
: POLICY_RR
);
2904 basic_info
->suspend_count
= task
->user_stop_count
;
2906 absolutetime_to_microtime(task
->total_user_time
, &secs
, &usecs
);
2907 basic_info
->user_time
.seconds
=
2908 (typeof(basic_info
->user_time
.seconds
))secs
;
2909 basic_info
->user_time
.microseconds
= usecs
;
2911 absolutetime_to_microtime(task
->total_system_time
, &secs
, &usecs
);
2912 basic_info
->system_time
.seconds
=
2913 (typeof(basic_info
->system_time
.seconds
))secs
;
2914 basic_info
->system_time
.microseconds
= usecs
;
2916 *task_info_count
= MACH_TASK_BASIC_INFO_COUNT
;
2920 case TASK_THREAD_TIMES_INFO
:
2922 register task_thread_times_info_t times_info
;
2923 register thread_t thread
;
2925 if (*task_info_count
< TASK_THREAD_TIMES_INFO_COUNT
) {
2926 error
= KERN_INVALID_ARGUMENT
;
2930 times_info
= (task_thread_times_info_t
) task_info_out
;
2931 times_info
->user_time
.seconds
= 0;
2932 times_info
->user_time
.microseconds
= 0;
2933 times_info
->system_time
.seconds
= 0;
2934 times_info
->system_time
.microseconds
= 0;
2937 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
2938 time_value_t user_time
, system_time
;
2940 if (thread
->options
& TH_OPT_IDLE_THREAD
)
2943 thread_read_times(thread
, &user_time
, &system_time
);
2945 time_value_add(×_info
->user_time
, &user_time
);
2946 time_value_add(×_info
->system_time
, &system_time
);
2949 *task_info_count
= TASK_THREAD_TIMES_INFO_COUNT
;
2953 case TASK_ABSOLUTETIME_INFO
:
2955 task_absolutetime_info_t info
;
2956 register thread_t thread
;
2958 if (*task_info_count
< TASK_ABSOLUTETIME_INFO_COUNT
) {
2959 error
= KERN_INVALID_ARGUMENT
;
2963 info
= (task_absolutetime_info_t
)task_info_out
;
2964 info
->threads_user
= info
->threads_system
= 0;
2967 info
->total_user
= task
->total_user_time
;
2968 info
->total_system
= task
->total_system_time
;
2970 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
2974 if (thread
->options
& TH_OPT_IDLE_THREAD
)
2978 thread_lock(thread
);
2980 tval
= timer_grab(&thread
->user_timer
);
2981 info
->threads_user
+= tval
;
2982 info
->total_user
+= tval
;
2984 tval
= timer_grab(&thread
->system_timer
);
2985 if (thread
->precise_user_kernel_time
) {
2986 info
->threads_system
+= tval
;
2987 info
->total_system
+= tval
;
2989 /* system_timer may represent either sys or user */
2990 info
->threads_user
+= tval
;
2991 info
->total_user
+= tval
;
2994 thread_unlock(thread
);
2999 *task_info_count
= TASK_ABSOLUTETIME_INFO_COUNT
;
3003 case TASK_DYLD_INFO
:
3005 task_dyld_info_t info
;
3008 * We added the format field to TASK_DYLD_INFO output. For
3009 * temporary backward compatibility, accept the fact that
3010 * clients may ask for the old version - distinquished by the
3011 * size of the expected result structure.
3013 #define TASK_LEGACY_DYLD_INFO_COUNT \
3014 offsetof(struct task_dyld_info, all_image_info_format)/sizeof(natural_t)
3016 if (*task_info_count
< TASK_LEGACY_DYLD_INFO_COUNT
) {
3017 error
= KERN_INVALID_ARGUMENT
;
3021 info
= (task_dyld_info_t
)task_info_out
;
3022 info
->all_image_info_addr
= task
->all_image_info_addr
;
3023 info
->all_image_info_size
= task
->all_image_info_size
;
3025 /* only set format on output for those expecting it */
3026 if (*task_info_count
>= TASK_DYLD_INFO_COUNT
) {
3027 info
->all_image_info_format
= task_has_64BitAddr(task
) ?
3028 TASK_DYLD_ALL_IMAGE_INFO_64
:
3029 TASK_DYLD_ALL_IMAGE_INFO_32
;
3030 *task_info_count
= TASK_DYLD_INFO_COUNT
;
3032 *task_info_count
= TASK_LEGACY_DYLD_INFO_COUNT
;
3037 case TASK_EXTMOD_INFO
:
3039 task_extmod_info_t info
;
3042 if (*task_info_count
< TASK_EXTMOD_INFO_COUNT
) {
3043 error
= KERN_INVALID_ARGUMENT
;
3047 info
= (task_extmod_info_t
)task_info_out
;
3049 p
= get_bsdtask_info(task
);
3051 proc_getexecutableuuid(p
, info
->task_uuid
, sizeof(info
->task_uuid
));
3053 bzero(info
->task_uuid
, sizeof(info
->task_uuid
));
3055 info
->extmod_statistics
= task
->extmod_statistics
;
3056 *task_info_count
= TASK_EXTMOD_INFO_COUNT
;
3061 case TASK_KERNELMEMORY_INFO
:
3063 task_kernelmemory_info_t tkm_info
;
3064 ledger_amount_t credit
, debit
;
3066 if (*task_info_count
< TASK_KERNELMEMORY_INFO_COUNT
) {
3067 error
= KERN_INVALID_ARGUMENT
;
3071 tkm_info
= (task_kernelmemory_info_t
) task_info_out
;
3072 tkm_info
->total_palloc
= 0;
3073 tkm_info
->total_pfree
= 0;
3074 tkm_info
->total_salloc
= 0;
3075 tkm_info
->total_sfree
= 0;
3077 if (task
== kernel_task
) {
3079 * All shared allocs/frees from other tasks count against
3080 * the kernel private memory usage. If we are looking up
3081 * info for the kernel task, gather from everywhere.
3085 /* start by accounting for all the terminated tasks against the kernel */
3086 tkm_info
->total_palloc
= tasks_tkm_private
.alloc
+ tasks_tkm_shared
.alloc
;
3087 tkm_info
->total_pfree
= tasks_tkm_private
.free
+ tasks_tkm_shared
.free
;
3089 /* count all other task/thread shared alloc/free against the kernel */
3090 lck_mtx_lock(&tasks_threads_lock
);
3092 /* XXX this really shouldn't be using the function parameter 'task' as a local var! */
3093 queue_iterate(&tasks
, task
, task_t
, tasks
) {
3094 if (task
== kernel_task
) {
3095 if (ledger_get_entries(task
->ledger
,
3096 task_ledgers
.tkm_private
, &credit
,
3097 &debit
) == KERN_SUCCESS
) {
3098 tkm_info
->total_palloc
+= credit
;
3099 tkm_info
->total_pfree
+= debit
;
3102 if (!ledger_get_entries(task
->ledger
,
3103 task_ledgers
.tkm_shared
, &credit
, &debit
)) {
3104 tkm_info
->total_palloc
+= credit
;
3105 tkm_info
->total_pfree
+= debit
;
3108 lck_mtx_unlock(&tasks_threads_lock
);
3110 if (!ledger_get_entries(task
->ledger
,
3111 task_ledgers
.tkm_private
, &credit
, &debit
)) {
3112 tkm_info
->total_palloc
= credit
;
3113 tkm_info
->total_pfree
= debit
;
3115 if (!ledger_get_entries(task
->ledger
,
3116 task_ledgers
.tkm_shared
, &credit
, &debit
)) {
3117 tkm_info
->total_salloc
= credit
;
3118 tkm_info
->total_sfree
= debit
;
3123 *task_info_count
= TASK_KERNELMEMORY_INFO_COUNT
;
3124 return KERN_SUCCESS
;
3128 case TASK_SCHED_FIFO_INFO
:
3131 if (*task_info_count
< POLICY_FIFO_BASE_COUNT
) {
3132 error
= KERN_INVALID_ARGUMENT
;
3136 error
= KERN_INVALID_POLICY
;
3141 case TASK_SCHED_RR_INFO
:
3143 register policy_rr_base_t rr_base
;
3144 uint32_t quantum_time
;
3145 uint64_t quantum_ns
;
3147 if (*task_info_count
< POLICY_RR_BASE_COUNT
) {
3148 error
= KERN_INVALID_ARGUMENT
;
3152 rr_base
= (policy_rr_base_t
) task_info_out
;
3154 if (task
!= kernel_task
) {
3155 error
= KERN_INVALID_POLICY
;
3159 rr_base
->base_priority
= task
->priority
;
3161 quantum_time
= SCHED(initial_quantum_size
)(THREAD_NULL
);
3162 absolutetime_to_nanoseconds(quantum_time
, &quantum_ns
);
3164 rr_base
->quantum
= (uint32_t)(quantum_ns
/ 1000 / 1000);
3166 *task_info_count
= POLICY_RR_BASE_COUNT
;
3171 case TASK_SCHED_TIMESHARE_INFO
:
3173 register policy_timeshare_base_t ts_base
;
3175 if (*task_info_count
< POLICY_TIMESHARE_BASE_COUNT
) {
3176 error
= KERN_INVALID_ARGUMENT
;
3180 ts_base
= (policy_timeshare_base_t
) task_info_out
;
3182 if (task
== kernel_task
) {
3183 error
= KERN_INVALID_POLICY
;
3187 ts_base
->base_priority
= task
->priority
;
3189 *task_info_count
= POLICY_TIMESHARE_BASE_COUNT
;
3193 case TASK_SECURITY_TOKEN
:
3195 register security_token_t
*sec_token_p
;
3197 if (*task_info_count
< TASK_SECURITY_TOKEN_COUNT
) {
3198 error
= KERN_INVALID_ARGUMENT
;
3202 sec_token_p
= (security_token_t
*) task_info_out
;
3204 *sec_token_p
= task
->sec_token
;
3206 *task_info_count
= TASK_SECURITY_TOKEN_COUNT
;
3210 case TASK_AUDIT_TOKEN
:
3212 register audit_token_t
*audit_token_p
;
3214 if (*task_info_count
< TASK_AUDIT_TOKEN_COUNT
) {
3215 error
= KERN_INVALID_ARGUMENT
;
3219 audit_token_p
= (audit_token_t
*) task_info_out
;
3221 *audit_token_p
= task
->audit_token
;
3223 *task_info_count
= TASK_AUDIT_TOKEN_COUNT
;
3227 case TASK_SCHED_INFO
:
3228 error
= KERN_INVALID_ARGUMENT
;
3231 case TASK_EVENTS_INFO
:
3233 register task_events_info_t events_info
;
3234 register thread_t thread
;
3236 if (*task_info_count
< TASK_EVENTS_INFO_COUNT
) {
3237 error
= KERN_INVALID_ARGUMENT
;
3241 events_info
= (task_events_info_t
) task_info_out
;
3244 events_info
->faults
= task
->faults
;
3245 events_info
->pageins
= task
->pageins
;
3246 events_info
->cow_faults
= task
->cow_faults
;
3247 events_info
->messages_sent
= task
->messages_sent
;
3248 events_info
->messages_received
= task
->messages_received
;
3249 events_info
->syscalls_mach
= task
->syscalls_mach
;
3250 events_info
->syscalls_unix
= task
->syscalls_unix
;
3252 events_info
->csw
= task
->c_switch
;
3254 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
3255 events_info
->csw
+= thread
->c_switch
;
3256 events_info
->syscalls_mach
+= thread
->syscalls_mach
;
3257 events_info
->syscalls_unix
+= thread
->syscalls_unix
;
3261 *task_info_count
= TASK_EVENTS_INFO_COUNT
;
3264 case TASK_AFFINITY_TAG_INFO
:
3266 if (*task_info_count
< TASK_AFFINITY_TAG_INFO_COUNT
) {
3267 error
= KERN_INVALID_ARGUMENT
;
3271 error
= task_affinity_info(task
, task_info_out
, task_info_count
);
3274 case TASK_POWER_INFO
:
3276 if (*task_info_count
< TASK_POWER_INFO_COUNT
) {
3277 error
= KERN_INVALID_ARGUMENT
;
3281 task_power_info_locked(task
, (task_power_info_t
)task_info_out
, NULL
);
3285 case TASK_POWER_INFO_V2
:
3287 if (*task_info_count
< TASK_POWER_INFO_V2_COUNT
) {
3288 error
= KERN_INVALID_ARGUMENT
;
3291 task_power_info_v2_t tpiv2
= (task_power_info_v2_t
) task_info_out
;
3292 task_power_info_locked(task
, &tpiv2
->cpu_energy
, &tpiv2
->gpu_energy
);
3297 case TASK_VM_INFO_PURGEABLE
:
3299 task_vm_info_t vm_info
;
3302 if (*task_info_count
< TASK_VM_INFO_REV0_COUNT
) {
3303 error
= KERN_INVALID_ARGUMENT
;
3307 vm_info
= (task_vm_info_t
)task_info_out
;
3309 if (task
== kernel_task
) {
3314 vm_map_lock_read(map
);
3317 vm_info
->virtual_size
= (typeof(vm_info
->virtual_size
))map
->size
;
3318 vm_info
->region_count
= map
->hdr
.nentries
;
3319 vm_info
->page_size
= vm_map_page_size(map
);
3321 vm_info
->resident_size
= pmap_resident_count(map
->pmap
);
3322 vm_info
->resident_size
*= PAGE_SIZE
;
3323 vm_info
->resident_size_peak
= pmap_resident_max(map
->pmap
);
3324 vm_info
->resident_size_peak
*= PAGE_SIZE
;
3326 #define _VM_INFO(_name) \
3327 vm_info->_name = ((mach_vm_size_t) map->pmap->stats._name) * PAGE_SIZE
3330 _VM_INFO(device_peak
);
3332 _VM_INFO(external_peak
);
3334 _VM_INFO(internal_peak
);
3336 _VM_INFO(reusable_peak
);
3337 _VM_INFO(compressed
);
3338 _VM_INFO(compressed_peak
);
3339 _VM_INFO(compressed_lifetime
);
3341 vm_info
->purgeable_volatile_pmap
= 0;
3342 vm_info
->purgeable_volatile_resident
= 0;
3343 vm_info
->purgeable_volatile_virtual
= 0;
3344 if (task
== kernel_task
) {
3346 * We do not maintain the detailed stats for the
3347 * kernel_pmap, so just count everything as
3350 vm_info
->internal
= vm_info
->resident_size
;
3352 * ... but since the memory held by the VM compressor
3353 * in the kernel address space ought to be attributed
3354 * to user-space tasks, we subtract it from "internal"
3355 * to give memory reporting tools a more accurate idea
3356 * of what the kernel itself is actually using, instead
3357 * of making it look like the kernel is leaking memory
3358 * when the system is under memory pressure.
3360 vm_info
->internal
-= (VM_PAGE_COMPRESSOR_COUNT
*
3363 mach_vm_size_t volatile_virtual_size
;
3364 mach_vm_size_t volatile_resident_size
;
3365 mach_vm_size_t volatile_compressed_size
;
3366 mach_vm_size_t volatile_pmap_size
;
3367 mach_vm_size_t volatile_compressed_pmap_size
;
3370 if (flavor
== TASK_VM_INFO_PURGEABLE
) {
3371 kr
= vm_map_query_volatile(
3373 &volatile_virtual_size
,
3374 &volatile_resident_size
,
3375 &volatile_compressed_size
,
3376 &volatile_pmap_size
,
3377 &volatile_compressed_pmap_size
);
3378 if (kr
== KERN_SUCCESS
) {
3379 vm_info
->purgeable_volatile_pmap
=
3381 if (radar_20146450
) {
3382 vm_info
->compressed
-=
3383 volatile_compressed_pmap_size
;
3385 vm_info
->purgeable_volatile_resident
=
3386 volatile_resident_size
;
3387 vm_info
->purgeable_volatile_virtual
=
3388 volatile_virtual_size
;
3391 vm_map_unlock_read(map
);
3394 if (*task_info_count
>= TASK_VM_INFO_COUNT
) {
3395 vm_info
->phys_footprint
= 0;
3396 *task_info_count
= TASK_VM_INFO_COUNT
;
3398 *task_info_count
= TASK_VM_INFO_REV0_COUNT
;
3404 case TASK_WAIT_STATE_INFO
:
3407 * Deprecated flavor. Currently allowing some results until all users
3408 * stop calling it. The results may not be accurate.
3410 task_wait_state_info_t wait_state_info
;
3411 uint64_t total_sfi_ledger_val
= 0;
3413 if (*task_info_count
< TASK_WAIT_STATE_INFO_COUNT
) {
3414 error
= KERN_INVALID_ARGUMENT
;
3418 wait_state_info
= (task_wait_state_info_t
) task_info_out
;
3420 wait_state_info
->total_wait_state_time
= 0;
3421 bzero(wait_state_info
->_reserved
, sizeof(wait_state_info
->_reserved
));
3423 #if CONFIG_SCHED_SFI
3424 int i
, prev_lentry
= -1;
3425 int64_t val_credit
, val_debit
;
3427 for (i
= 0; i
< MAX_SFI_CLASS_ID
; i
++){
3430 * checking with prev_lentry != entry ensures adjacent classes
3431 * which share the same ledger do not add wait times twice.
3432 * Note: Use ledger() call to get data for each individual sfi class.
3434 if (prev_lentry
!= task_ledgers
.sfi_wait_times
[i
] &&
3435 KERN_SUCCESS
== ledger_get_entries(task
->ledger
,
3436 task_ledgers
.sfi_wait_times
[i
], &val_credit
, &val_debit
)) {
3437 total_sfi_ledger_val
+= val_credit
;
3439 prev_lentry
= task_ledgers
.sfi_wait_times
[i
];
3442 #endif /* CONFIG_SCHED_SFI */
3443 wait_state_info
->total_wait_sfi_state_time
= total_sfi_ledger_val
;
3444 *task_info_count
= TASK_WAIT_STATE_INFO_COUNT
;
3448 case TASK_VM_INFO_PURGEABLE_ACCOUNT
:
3450 #if DEVELOPMENT || DEBUG
3451 pvm_account_info_t acnt_info
;
3453 if (*task_info_count
< PVM_ACCOUNT_INFO_COUNT
) {
3454 error
= KERN_INVALID_ARGUMENT
;
3458 if (task_info_out
== NULL
) {
3459 error
= KERN_INVALID_ARGUMENT
;
3463 acnt_info
= (pvm_account_info_t
) task_info_out
;
3465 error
= vm_purgeable_account(task
, acnt_info
);
3467 *task_info_count
= PVM_ACCOUNT_INFO_COUNT
;
3470 #else /* DEVELOPMENT || DEBUG */
3471 error
= KERN_NOT_SUPPORTED
;
3473 #endif /* DEVELOPMENT || DEBUG */
3475 case TASK_FLAGS_INFO
:
3477 task_flags_info_t flags_info
;
3479 if (*task_info_count
< TASK_FLAGS_INFO_COUNT
) {
3480 error
= KERN_INVALID_ARGUMENT
;
3484 flags_info
= (task_flags_info_t
)task_info_out
;
3486 /* only publish the 64-bit flag of the task */
3487 flags_info
->flags
= task
->t_flags
& TF_64B_ADDR
;
3489 *task_info_count
= TASK_FLAGS_INFO_COUNT
;
3493 case TASK_DEBUG_INFO_INTERNAL
:
3495 #if DEVELOPMENT || DEBUG
3496 task_debug_info_internal_t dbg_info
;
3497 if (*task_info_count
< TASK_DEBUG_INFO_INTERNAL_COUNT
) {
3498 error
= KERN_NOT_SUPPORTED
;
3502 if (task_info_out
== NULL
) {
3503 error
= KERN_INVALID_ARGUMENT
;
3506 dbg_info
= (task_debug_info_internal_t
) task_info_out
;
3507 dbg_info
->ipc_space_size
= 0;
3508 if (task
->itk_space
){
3509 dbg_info
->ipc_space_size
= task
->itk_space
->is_table_size
;
3512 error
= KERN_SUCCESS
;
3513 *task_info_count
= TASK_DEBUG_INFO_INTERNAL_COUNT
;
3515 #else /* DEVELOPMENT || DEBUG */
3516 error
= KERN_NOT_SUPPORTED
;
3518 #endif /* DEVELOPMENT || DEBUG */
3521 error
= KERN_INVALID_ARGUMENT
;
3531 * Returns power stats for the task.
3532 * Note: Called with task locked.
3535 task_power_info_locked(
3537 task_power_info_t info
,
3538 gpu_energy_data_t ginfo
)
3541 ledger_amount_t tmp
;
3543 task_lock_assert_owned(task
);
3545 ledger_get_entries(task
->ledger
, task_ledgers
.interrupt_wakeups
,
3546 (ledger_amount_t
*)&info
->task_interrupt_wakeups
, &tmp
);
3547 ledger_get_entries(task
->ledger
, task_ledgers
.platform_idle_wakeups
,
3548 (ledger_amount_t
*)&info
->task_platform_idle_wakeups
, &tmp
);
3550 info
->task_timer_wakeups_bin_1
= task
->task_timer_wakeups_bin_1
;
3551 info
->task_timer_wakeups_bin_2
= task
->task_timer_wakeups_bin_2
;
3553 info
->total_user
= task
->total_user_time
;
3554 info
->total_system
= task
->total_system_time
;
3557 ginfo
->task_gpu_utilisation
= task
->task_gpu_ns
;
3560 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
3564 if (thread
->options
& TH_OPT_IDLE_THREAD
)
3568 thread_lock(thread
);
3570 info
->task_timer_wakeups_bin_1
+= thread
->thread_timer_wakeups_bin_1
;
3571 info
->task_timer_wakeups_bin_2
+= thread
->thread_timer_wakeups_bin_2
;
3573 tval
= timer_grab(&thread
->user_timer
);
3574 info
->total_user
+= tval
;
3576 tval
= timer_grab(&thread
->system_timer
);
3577 if (thread
->precise_user_kernel_time
) {
3578 info
->total_system
+= tval
;
3580 /* system_timer may represent either sys or user */
3581 info
->total_user
+= tval
;
3585 ginfo
->task_gpu_utilisation
+= ml_gpu_stat(thread
);
3587 thread_unlock(thread
);
3593 * task_gpu_utilisation
3595 * Returns the total gpu time used by the all the threads of the task
3596 * (both dead and alive)
3599 task_gpu_utilisation(
3602 uint64_t gpu_time
= 0;
3606 gpu_time
+= task
->task_gpu_ns
;
3608 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
3611 thread_lock(thread
);
3612 gpu_time
+= ml_gpu_stat(thread
);
3613 thread_unlock(thread
);
3624 task_purgable_info_t
*stats
)
3626 if (task
== TASK_NULL
|| stats
== NULL
)
3627 return KERN_INVALID_ARGUMENT
;
3628 /* Take task reference */
3629 task_reference(task
);
3630 vm_purgeable_stats((vm_purgeable_info_t
)stats
, task
);
3631 /* Drop task reference */
3632 task_deallocate(task
);
3633 return KERN_SUCCESS
;
3644 /* assert(task == current_task()); */ /* bogus assert 4803227 4807483 */
3648 task
->vtimers
|= which
;
3652 case TASK_VTIMER_USER
:
3653 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
3655 thread_lock(thread
);
3656 if (thread
->precise_user_kernel_time
)
3657 thread
->vtimer_user_save
= timer_grab(&thread
->user_timer
);
3659 thread
->vtimer_user_save
= timer_grab(&thread
->system_timer
);
3660 thread_unlock(thread
);
3665 case TASK_VTIMER_PROF
:
3666 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
3668 thread_lock(thread
);
3669 thread
->vtimer_prof_save
= timer_grab(&thread
->user_timer
);
3670 thread
->vtimer_prof_save
+= timer_grab(&thread
->system_timer
);
3671 thread_unlock(thread
);
3676 case TASK_VTIMER_RLIM
:
3677 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
3679 thread_lock(thread
);
3680 thread
->vtimer_rlim_save
= timer_grab(&thread
->user_timer
);
3681 thread
->vtimer_rlim_save
+= timer_grab(&thread
->system_timer
);
3682 thread_unlock(thread
);
3696 assert(task
== current_task());
3700 task
->vtimers
&= ~which
;
3710 uint32_t *microsecs
)
3712 thread_t thread
= current_thread();
3717 assert(task
== current_task());
3719 assert(task
->vtimers
& which
);
3725 case TASK_VTIMER_USER
:
3726 if (thread
->precise_user_kernel_time
) {
3727 tdelt
= (uint32_t)timer_delta(&thread
->user_timer
,
3728 &thread
->vtimer_user_save
);
3730 tdelt
= (uint32_t)timer_delta(&thread
->system_timer
,
3731 &thread
->vtimer_user_save
);
3733 absolutetime_to_microtime(tdelt
, &secs
, microsecs
);
3736 case TASK_VTIMER_PROF
:
3737 tsum
= timer_grab(&thread
->user_timer
);
3738 tsum
+= timer_grab(&thread
->system_timer
);
3739 tdelt
= (uint32_t)(tsum
- thread
->vtimer_prof_save
);
3740 absolutetime_to_microtime(tdelt
, &secs
, microsecs
);
3741 /* if the time delta is smaller than a usec, ignore */
3742 if (*microsecs
!= 0)
3743 thread
->vtimer_prof_save
= tsum
;
3746 case TASK_VTIMER_RLIM
:
3747 tsum
= timer_grab(&thread
->user_timer
);
3748 tsum
+= timer_grab(&thread
->system_timer
);
3749 tdelt
= (uint32_t)(tsum
- thread
->vtimer_rlim_save
);
3750 thread
->vtimer_rlim_save
= tsum
;
3751 absolutetime_to_microtime(tdelt
, &secs
, microsecs
);
3760 * Change the assigned processor set for the task
3764 __unused task_t task
,
3765 __unused processor_set_t new_pset
,
3766 __unused boolean_t assign_threads
)
3768 return(KERN_FAILURE
);
3772 * task_assign_default:
3774 * Version of task_assign to assign to default processor set.
3777 task_assign_default(
3779 boolean_t assign_threads
)
3781 return (task_assign(task
, &pset0
, assign_threads
));
3785 * task_get_assignment
3787 * Return name of processor set that task is assigned to.
3790 task_get_assignment(
3792 processor_set_t
*pset
)
3795 return(KERN_FAILURE
);
3799 return (KERN_SUCCESS
);
3803 get_task_dispatchqueue_offset(
3806 return task
->dispatchqueue_offset
;
3812 * Set scheduling policy and parameters, both base and limit, for
3813 * the given task. Policy must be a policy which is enabled for the
3814 * processor set. Change contained threads if requested.
3818 __unused task_t task
,
3819 __unused policy_t policy_id
,
3820 __unused policy_base_t base
,
3821 __unused mach_msg_type_number_t count
,
3822 __unused boolean_t set_limit
,
3823 __unused boolean_t change
)
3825 return(KERN_FAILURE
);
3831 * Set scheduling policy and parameters, both base and limit, for
3832 * the given task. Policy can be any policy implemented by the
3833 * processor set, whether enabled or not. Change contained threads
3838 __unused task_t task
,
3839 __unused processor_set_t pset
,
3840 __unused policy_t policy_id
,
3841 __unused policy_base_t base
,
3842 __unused mach_msg_type_number_t base_count
,
3843 __unused policy_limit_t limit
,
3844 __unused mach_msg_type_number_t limit_count
,
3845 __unused boolean_t change
)
3847 return(KERN_FAILURE
);
3852 __unused task_t task
,
3853 __unused vm_offset_t pc
,
3854 __unused vm_offset_t endpc
)
3856 return KERN_FAILURE
;
3860 task_synchronizer_destroy_all(task_t task
)
3863 * Destroy owned semaphores
3865 semaphore_destroy_all(task
);
3869 * Install default (machine-dependent) initial thread state
3870 * on the task. Subsequent thread creation will have this initial
3871 * state set on the thread by machine_thread_inherit_taskwide().
3872 * Flavors and structures are exactly the same as those to thread_set_state()
3878 thread_state_t state
,
3879 mach_msg_type_number_t state_count
)
3883 if (task
== TASK_NULL
) {
3884 return (KERN_INVALID_ARGUMENT
);
3889 if (!task
->active
) {
3891 return (KERN_FAILURE
);
3894 ret
= machine_task_set_state(task
, flavor
, state
, state_count
);
3901 * Examine the default (machine-dependent) initial thread state
3902 * on the task, as set by task_set_state(). Flavors and structures
3903 * are exactly the same as those passed to thread_get_state().
3909 thread_state_t state
,
3910 mach_msg_type_number_t
*state_count
)
3914 if (task
== TASK_NULL
) {
3915 return (KERN_INVALID_ARGUMENT
);
3920 if (!task
->active
) {
3922 return (KERN_FAILURE
);
3925 ret
= machine_task_get_state(task
, flavor
, state
, state_count
);
3932 #define HWM_USERCORE_MINSPACE 250 // free space (in MB) required *after* core file creation
3934 void __attribute__((noinline
))
3935 PROC_CROSSED_HIGH_WATERMARK__SEND_EXC_RESOURCE_AND_SUSPEND(int max_footprint_mb
)
3937 task_t task
= current_task();
3939 const char *procname
= "unknown";
3940 mach_exception_data_type_t code
[EXCEPTION_CODE_MAX
];
3943 pid
= proc_selfpid();
3947 * Cannot have ReportCrash analyzing
3948 * a suspended initproc.
3953 if (task
->bsd_info
!= NULL
)
3954 procname
= proc_name_address(current_task()->bsd_info
);
3957 if (hwm_user_cores
) {
3959 uint64_t starttime
, end
;
3960 clock_sec_t secs
= 0;
3961 uint32_t microsecs
= 0;
3963 starttime
= mach_absolute_time();
3965 * Trigger a coredump of this process. Don't proceed unless we know we won't
3966 * be filling up the disk; and ignore the core size resource limit for this
3969 if ((error
= coredump(current_task()->bsd_info
, HWM_USERCORE_MINSPACE
, COREDUMP_IGNORE_ULIMIT
)) != 0) {
3970 printf("couldn't take coredump of %s[%d]: %d\n", procname
, pid
, error
);
3973 * coredump() leaves the task suspended.
3975 task_resume_internal(current_task());
3977 end
= mach_absolute_time();
3978 absolutetime_to_microtime(end
- starttime
, &secs
, µsecs
);
3979 printf("coredump of %s[%d] taken in %d secs %d microsecs\n",
3980 proc_name_address(current_task()->bsd_info
), pid
, (int)secs
, microsecs
);
3983 if (disable_exc_resource
) {
3984 printf("process %s[%d] crossed memory high watermark (%d MB); EXC_RESOURCE "
3985 "supressed by a boot-arg.\n", procname
, pid
, max_footprint_mb
);
3990 * A task that has triggered an EXC_RESOURCE, should not be
3991 * jetsammed when the device is under memory pressure. Here
3992 * we set the P_MEMSTAT_TERMINATED flag so that the process
3993 * will be skipped if the memorystatus_thread wakes up.
3995 proc_memstat_terminated(current_task()->bsd_info
, TRUE
);
3997 printf("process %s[%d] crossed memory high watermark (%d MB); sending "
3998 "EXC_RESOURCE.\n", procname
, pid
, max_footprint_mb
);
4000 code
[0] = code
[1] = 0;
4001 EXC_RESOURCE_ENCODE_TYPE(code
[0], RESOURCE_TYPE_MEMORY
);
4002 EXC_RESOURCE_ENCODE_FLAVOR(code
[0], FLAVOR_HIGH_WATERMARK
);
4003 EXC_RESOURCE_HWM_ENCODE_LIMIT(code
[0], max_footprint_mb
);
4006 * Use the _internal_ variant so that no user-space
4007 * process can resume our task from under us.
4009 task_suspend_internal(task
);
4010 exception_triage(EXC_RESOURCE
, code
, EXCEPTION_CODE_MAX
);
4011 task_resume_internal(task
);
4014 * After the EXC_RESOURCE has been handled, we must clear the
4015 * P_MEMSTAT_TERMINATED flag so that the process can again be
4016 * considered for jetsam if the memorystatus_thread wakes up.
4018 proc_memstat_terminated(current_task()->bsd_info
, FALSE
); /* clear the flag */
4022 * Callback invoked when a task exceeds its physical footprint limit.
4025 task_footprint_exceeded(int warning
, __unused
const void *param0
, __unused
const void *param1
)
4027 ledger_amount_t max_footprint
, max_footprint_mb
;
4028 ledger_amount_t footprint_after_purge
;
4031 if (warning
== LEDGER_WARNING_DIPPED_BELOW
) {
4033 * Task memory limits only provide a warning on the way up.
4038 task
= current_task();
4040 ledger_get_limit(task
->ledger
, task_ledgers
.phys_footprint
, &max_footprint
);
4041 max_footprint_mb
= max_footprint
>> 20;
4044 * Try and purge all "volatile" memory in that task first.
4046 (void) task_purge_volatile_memory(task
);
4047 /* are we still over the limit ? */
4048 ledger_get_balance(task
->ledger
,
4049 task_ledgers
.phys_footprint
,
4050 &footprint_after_purge
);
4052 footprint_after_purge
<= max_footprint
) ||
4054 footprint_after_purge
<= ((max_footprint
*
4055 PHYS_FOOTPRINT_WARNING_LEVEL
) / 100))) {
4056 /* all better now */
4057 ledger_reset_callback_state(task
->ledger
,
4058 task_ledgers
.phys_footprint
);
4061 /* still over the limit after purging... */
4064 * If this an actual violation (not a warning),
4065 * generate a non-fatal high watermark EXC_RESOURCE.
4067 if ((warning
== 0) && (task
->rusage_cpu_flags
& TASK_RUSECPU_FLAGS_PHYS_FOOTPRINT_EXCEPTION
)) {
4068 PROC_CROSSED_HIGH_WATERMARK__SEND_EXC_RESOURCE_AND_SUSPEND((int)max_footprint_mb
);
4071 memorystatus_on_ledger_footprint_exceeded((warning
== LEDGER_WARNING_ROSE_ABOVE
) ? TRUE
: FALSE
,
4072 (int)max_footprint_mb
);
4075 extern int proc_check_footprint_priv(void);
4078 task_set_phys_footprint_limit(
4083 kern_return_t error
;
4085 if ((error
= proc_check_footprint_priv())) {
4086 return (KERN_NO_ACCESS
);
4089 return task_set_phys_footprint_limit_internal(task
, new_limit_mb
, old_limit_mb
, FALSE
);
4093 task_convert_phys_footprint_limit(
4095 int *converted_limit_mb
)
4097 if (limit_mb
== -1) {
4101 if (max_task_footprint
!= 0) {
4102 *converted_limit_mb
= (int)(max_task_footprint
/ 1024 / 1024); /* bytes to MB */
4104 *converted_limit_mb
= (int)(LEDGER_LIMIT_INFINITY
>> 20);
4107 /* nothing to convert */
4108 *converted_limit_mb
= limit_mb
;
4110 return (KERN_SUCCESS
);
4115 task_set_phys_footprint_limit_internal(
4119 boolean_t trigger_exception
)
4121 ledger_amount_t old
;
4123 ledger_get_limit(task
->ledger
, task_ledgers
.phys_footprint
, &old
);
4127 * Check that limit >> 20 will not give an "unexpected" 32-bit
4128 * result. There are, however, implicit assumptions that -1 mb limit
4129 * equates to LEDGER_LIMIT_INFINITY.
4131 assert(((old
& 0xFFF0000000000000LL
) == 0) || (old
== LEDGER_LIMIT_INFINITY
));
4132 *old_limit_mb
= (int)(old
>> 20);
4135 if (new_limit_mb
== -1) {
4137 * Caller wishes to remove the limit.
4139 ledger_set_limit(task
->ledger
, task_ledgers
.phys_footprint
,
4140 max_task_footprint
? max_task_footprint
: LEDGER_LIMIT_INFINITY
,
4141 max_task_footprint
? PHYS_FOOTPRINT_WARNING_LEVEL
: 0);
4142 return (KERN_SUCCESS
);
4145 #ifdef CONFIG_NOMONITORS
4146 return (KERN_SUCCESS
);
4147 #endif /* CONFIG_NOMONITORS */
4151 if (trigger_exception
) {
4152 task
->rusage_cpu_flags
|= TASK_RUSECPU_FLAGS_PHYS_FOOTPRINT_EXCEPTION
;
4154 task
->rusage_cpu_flags
&= ~TASK_RUSECPU_FLAGS_PHYS_FOOTPRINT_EXCEPTION
;
4157 ledger_set_limit(task
->ledger
, task_ledgers
.phys_footprint
,
4158 (ledger_amount_t
)new_limit_mb
<< 20, PHYS_FOOTPRINT_WARNING_LEVEL
);
4160 if (task
== current_task()) {
4161 ledger_check_new_balance(task
->ledger
, task_ledgers
.phys_footprint
);
4166 return (KERN_SUCCESS
);
4170 task_get_phys_footprint_limit(
4174 ledger_amount_t limit
;
4176 ledger_get_limit(task
->ledger
, task_ledgers
.phys_footprint
, &limit
);
4178 * Check that limit >> 20 will not give an "unexpected" signed, 32-bit
4179 * result. There are, however, implicit assumptions that -1 mb limit
4180 * equates to LEDGER_LIMIT_INFINITY.
4182 assert(((limit
& 0xFFF0000000000000LL
) == 0) || (limit
== LEDGER_LIMIT_INFINITY
));
4183 *limit_mb
= (int)(limit
>> 20);
4185 return (KERN_SUCCESS
);
4187 #else /* CONFIG_JETSAM */
4189 task_set_phys_footprint_limit(
4190 __unused task_t task
,
4191 __unused
int new_limit_mb
,
4192 __unused
int *old_limit_mb
)
4194 return (KERN_FAILURE
);
4198 task_get_phys_footprint_limit(
4199 __unused task_t task
,
4200 __unused
int *limit_mb
)
4202 return (KERN_FAILURE
);
4204 #endif /* CONFIG_JETSAM */
4207 * We need to export some functions to other components that
4208 * are currently implemented in macros within the osfmk
4209 * component. Just export them as functions of the same name.
4211 boolean_t
is_kerneltask(task_t t
)
4213 if (t
== kernel_task
)
4220 check_for_tasksuspend(task_t task
)
4223 if (task
== TASK_NULL
)
4226 return (task
->suspend_count
> 0);
4230 task_t
current_task(void);
4231 task_t
current_task(void)
4233 return (current_task_fast());
4236 #undef task_reference
4237 void task_reference(task_t task
);
4242 if (task
!= TASK_NULL
)
4243 task_reference_internal(task
);
4246 /* defined in bsd/kern/kern_prot.c */
4247 extern int get_audit_token_pid(audit_token_t
*audit_token
);
4249 int task_pid(task_t task
)
4252 return get_audit_token_pid(&task
->audit_token
);
4258 * This routine is called always with task lock held.
4259 * And it returns a thread handle without reference as the caller
4260 * operates on it under the task lock held.
4263 task_findtid(task_t task
, uint64_t tid
)
4265 thread_t thread
= THREAD_NULL
;
4267 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
) {
4268 if (thread
->thread_id
== tid
)
4271 return(THREAD_NULL
);
4275 * Control the CPU usage monitor for a task.
4278 task_cpu_usage_monitor_ctl(task_t task
, uint32_t *flags
)
4280 int error
= KERN_SUCCESS
;
4282 if (*flags
& CPUMON_MAKE_FATAL
) {
4283 task
->rusage_cpu_flags
|= TASK_RUSECPU_FLAGS_FATAL_CPUMON
;
4285 error
= KERN_INVALID_ARGUMENT
;
4292 * Control the wakeups monitor for a task.
4295 task_wakeups_monitor_ctl(task_t task
, uint32_t *flags
, int32_t *rate_hz
)
4297 ledger_t ledger
= task
->ledger
;
4300 if (*flags
& WAKEMON_GET_PARAMS
) {
4301 ledger_amount_t limit
;
4304 ledger_get_limit(ledger
, task_ledgers
.interrupt_wakeups
, &limit
);
4305 ledger_get_period(ledger
, task_ledgers
.interrupt_wakeups
, &period
);
4307 if (limit
!= LEDGER_LIMIT_INFINITY
) {
4309 * An active limit means the wakeups monitor is enabled.
4311 *rate_hz
= (int32_t)(limit
/ (int64_t)(period
/ NSEC_PER_SEC
));
4312 *flags
= WAKEMON_ENABLE
;
4313 if (task
->rusage_cpu_flags
& TASK_RUSECPU_FLAGS_FATAL_WAKEUPSMON
) {
4314 *flags
|= WAKEMON_MAKE_FATAL
;
4317 *flags
= WAKEMON_DISABLE
;
4322 * If WAKEMON_GET_PARAMS is present in flags, all other flags are ignored.
4325 return KERN_SUCCESS
;
4328 if (*flags
& WAKEMON_ENABLE
) {
4329 if (*flags
& WAKEMON_SET_DEFAULTS
) {
4330 *rate_hz
= task_wakeups_monitor_rate
;
4333 #ifndef CONFIG_NOMONITORS
4334 if (*flags
& WAKEMON_MAKE_FATAL
) {
4335 task
->rusage_cpu_flags
|= TASK_RUSECPU_FLAGS_FATAL_WAKEUPSMON
;
4337 #endif /* CONFIG_NOMONITORS */
4341 return KERN_INVALID_ARGUMENT
;
4344 #ifndef CONFIG_NOMONITORS
4345 ledger_set_limit(ledger
, task_ledgers
.interrupt_wakeups
, *rate_hz
* task_wakeups_monitor_interval
,
4346 task_wakeups_monitor_ustackshots_trigger_pct
);
4347 ledger_set_period(ledger
, task_ledgers
.interrupt_wakeups
, task_wakeups_monitor_interval
* NSEC_PER_SEC
);
4348 ledger_enable_callback(ledger
, task_ledgers
.interrupt_wakeups
);
4349 #endif /* CONFIG_NOMONITORS */
4350 } else if (*flags
& WAKEMON_DISABLE
) {
4352 * Caller wishes to disable wakeups monitor on the task.
4354 * Disable telemetry if it was triggered by the wakeups monitor, and
4355 * remove the limit & callback on the wakeups ledger entry.
4357 #if CONFIG_TELEMETRY
4358 telemetry_task_ctl_locked(current_task(), TF_WAKEMON_WARNING
, 0);
4360 ledger_disable_refill(ledger
, task_ledgers
.interrupt_wakeups
);
4361 ledger_disable_callback(ledger
, task_ledgers
.interrupt_wakeups
);
4365 return KERN_SUCCESS
;
4369 task_wakeups_rate_exceeded(int warning
, __unused
const void *param0
, __unused
const void *param1
)
4371 if (warning
== LEDGER_WARNING_ROSE_ABOVE
) {
4372 #if CONFIG_TELEMETRY
4374 * This task is in danger of violating the wakeups monitor. Enable telemetry on this task
4375 * so there are micro-stackshots available if and when EXC_RESOURCE is triggered.
4377 telemetry_task_ctl(current_task(), TF_WAKEMON_WARNING
, 1);
4382 #if CONFIG_TELEMETRY
4384 * If the balance has dipped below the warning level (LEDGER_WARNING_DIPPED_BELOW) or
4385 * exceeded the limit, turn telemetry off for the task.
4387 telemetry_task_ctl(current_task(), TF_WAKEMON_WARNING
, 0);
4391 THIS_PROCESS_IS_CAUSING_TOO_MANY_WAKEUPS__SENDING_EXC_RESOURCE();
4395 void __attribute__((noinline
))
4396 THIS_PROCESS_IS_CAUSING_TOO_MANY_WAKEUPS__SENDING_EXC_RESOURCE(void)
4398 task_t task
= current_task();
4400 const char *procname
= "unknown";
4401 uint64_t observed_wakeups_rate
;
4402 uint64_t permitted_wakeups_rate
;
4403 uint64_t observation_interval
;
4404 mach_exception_data_type_t code
[EXCEPTION_CODE_MAX
];
4405 struct ledger_entry_info lei
;
4408 pid
= proc_selfpid();
4409 if (task
->bsd_info
!= NULL
)
4410 procname
= proc_name_address(current_task()->bsd_info
);
4413 ledger_get_entry_info(task
->ledger
, task_ledgers
.interrupt_wakeups
, &lei
);
4416 * Disable the exception notification so we don't overwhelm
4417 * the listener with an endless stream of redundant exceptions.
4419 uint32_t flags
= WAKEMON_DISABLE
;
4420 task_wakeups_monitor_ctl(task
, &flags
, NULL
);
4422 observed_wakeups_rate
= (lei
.lei_balance
* (int64_t)NSEC_PER_SEC
) / lei
.lei_last_refill
;
4423 permitted_wakeups_rate
= lei
.lei_limit
/ task_wakeups_monitor_interval
;
4424 observation_interval
= lei
.lei_refill_period
/ NSEC_PER_SEC
;
4426 if (disable_exc_resource
) {
4427 printf("process %s[%d] caught causing excessive wakeups. EXC_RESOURCE "
4428 "supressed by a boot-arg\n", procname
, pid
);
4432 printf("process %s[%d] caught causing excessive wakeups. EXC_RESOURCE "
4433 "supressed due to audio playback\n", procname
, pid
);
4436 printf("process %s[%d] caught causing excessive wakeups. Observed wakeups rate "
4437 "(per sec): %lld; Maximum permitted wakeups rate (per sec): %lld; Observation "
4438 "period: %lld seconds; Task lifetime number of wakeups: %lld\n",
4439 procname
, pid
, observed_wakeups_rate
, permitted_wakeups_rate
,
4440 observation_interval
, lei
.lei_credit
);
4442 code
[0] = code
[1] = 0;
4443 EXC_RESOURCE_ENCODE_TYPE(code
[0], RESOURCE_TYPE_WAKEUPS
);
4444 EXC_RESOURCE_ENCODE_FLAVOR(code
[0], FLAVOR_WAKEUPS_MONITOR
);
4445 EXC_RESOURCE_CPUMONITOR_ENCODE_WAKEUPS_PERMITTED(code
[0], task_wakeups_monitor_rate
);
4446 EXC_RESOURCE_CPUMONITOR_ENCODE_OBSERVATION_INTERVAL(code
[0], observation_interval
);
4447 EXC_RESOURCE_CPUMONITOR_ENCODE_WAKEUPS_OBSERVED(code
[1], lei
.lei_balance
* (int64_t)NSEC_PER_SEC
/ lei
.lei_last_refill
);
4448 exception_triage(EXC_RESOURCE
, code
, EXCEPTION_CODE_MAX
);
4450 if (task
->rusage_cpu_flags
& TASK_RUSECPU_FLAGS_FATAL_WAKEUPSMON
) {
4451 task_terminate_internal(task
);
4456 task_purge_volatile_memory(
4460 int num_object_purged
;
4462 if (task
== TASK_NULL
)
4463 return KERN_INVALID_TASK
;
4467 if (!task
->active
) {
4469 return KERN_INVALID_TASK
;
4472 if (map
== VM_MAP_NULL
) {
4474 return KERN_INVALID_TASK
;
4476 vm_map_reference(task
->map
);
4480 num_object_purged
= vm_map_purge(map
);
4481 vm_map_deallocate(map
);
4483 return KERN_SUCCESS
;
4486 /* Placeholders for the task set/get voucher interfaces */
4488 task_get_mach_voucher(
4490 mach_voucher_selector_t __unused which
,
4491 ipc_voucher_t
*voucher
)
4493 if (TASK_NULL
== task
)
4494 return KERN_INVALID_TASK
;
4497 return KERN_SUCCESS
;
4501 task_set_mach_voucher(
4503 ipc_voucher_t __unused voucher
)
4505 if (TASK_NULL
== task
)
4506 return KERN_INVALID_TASK
;
4508 return KERN_SUCCESS
;
4512 task_swap_mach_voucher(
4514 ipc_voucher_t new_voucher
,
4515 ipc_voucher_t
*in_out_old_voucher
)
4517 if (TASK_NULL
== task
)
4518 return KERN_INVALID_TASK
;
4520 *in_out_old_voucher
= new_voucher
;
4521 return KERN_SUCCESS
;
4524 void task_set_gpu_denied(task_t task
, boolean_t denied
)
4529 task
->t_flags
|= TF_GPU_DENIED
;
4531 task
->t_flags
&= ~TF_GPU_DENIED
;
4537 boolean_t
task_is_gpu_denied(task_t task
)
4539 /* We don't need the lock to read this flag */
4540 return (task
->t_flags
& TF_GPU_DENIED
) ? TRUE
: FALSE
;
4543 void task_update_logical_writes(task_t task
, uint32_t io_size
, int flags
)
4545 KERNEL_DEBUG_CONSTANT((MACHDBG_CODE(DBG_MACH_VM
, VM_DATA_WRITE
)) | DBG_FUNC_NONE
, task_pid(task
), io_size
, flags
, 0, 0);
4547 case TASK_WRITE_IMMEDIATE
:
4548 OSAddAtomic64(io_size
, (SInt64
*)&(task
->task_immediate_writes
));
4550 case TASK_WRITE_DEFERRED
:
4551 OSAddAtomic64(io_size
, (SInt64
*)&(task
->task_deferred_writes
));
4553 case TASK_WRITE_INVALIDATED
:
4554 OSAddAtomic64(io_size
, (SInt64
*)&(task
->task_invalidated_writes
));
4556 case TASK_WRITE_METADATA
:
4557 OSAddAtomic64(io_size
, (SInt64
*)&(task
->task_metadata_writes
));