2 * Copyright (c) 2013-2017 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 #include <mach/mach_types.h>
30 #include <mach/vm_param.h>
31 #include <mach/mach_vm.h>
32 #include <mach/clock_types.h>
33 #include <sys/errno.h>
34 #include <sys/stackshot.h>
35 #ifdef IMPORTANCE_INHERITANCE
36 #include <ipc/ipc_importance.h>
38 #include <sys/appleapiopts.h>
39 #include <kern/debug.h>
40 #include <kern/block_hint.h>
41 #include <uuid/uuid.h>
43 #include <kdp/kdp_dyld.h>
44 #include <kdp/kdp_en_debugger.h>
46 #include <libsa/types.h>
47 #include <libkern/version.h>
49 #include <string.h> /* bcopy */
51 #include <kern/coalition.h>
52 #include <kern/processor.h>
53 #include <kern/thread.h>
54 #include <kern/thread_group.h>
55 #include <kern/task.h>
56 #include <kern/telemetry.h>
57 #include <kern/clock.h>
58 #include <kern/policy_internal.h>
59 #include <vm/vm_map.h>
60 #include <vm/vm_kern.h>
61 #include <vm/vm_pageout.h>
62 #include <vm/vm_fault.h>
63 #include <vm/vm_shared_region.h>
64 #include <libkern/OSKextLibPrivate.h>
67 #include <pexpert/pexpert.h> /* For gPanicBase/gPanicBase */
71 #include <kern/monotonic.h>
72 #endif /* MONOTONIC */
74 #include <san/kasan.h>
76 extern unsigned int not_in_kdp
;
79 uuid_t kernelcache_uuid
;
82 /* indicate to the compiler that some accesses are unaligned */
83 typedef uint64_t unaligned_u64
__attribute__((aligned(1)));
85 extern addr64_t
kdp_vtophys(pmap_t pmap
, addr64_t va
);
86 extern void * proc_get_uthread_uu_threadlist(void * uthread_v
);
89 static kern_return_t stack_snapshot_ret
= 0;
90 static uint32_t stack_snapshot_bytes_traced
= 0;
92 static kcdata_descriptor_t stackshot_kcdata_p
= NULL
;
93 static void *stack_snapshot_buf
;
94 static uint32_t stack_snapshot_bufsize
;
95 int stack_snapshot_pid
;
96 static uint32_t stack_snapshot_flags
;
97 static uint64_t stack_snapshot_delta_since_timestamp
;
98 static boolean_t panic_stackshot
;
100 static boolean_t stack_enable_faulting
= FALSE
;
101 static struct stackshot_fault_stats fault_stats
;
103 static unaligned_u64
* stackshot_duration_outer
;
104 static uint64_t stackshot_microsecs
;
106 void * kernel_stackshot_buf
= NULL
; /* Pointer to buffer for stackshots triggered from the kernel and retrieved later */
107 int kernel_stackshot_buf_size
= 0;
109 void * stackshot_snapbuf
= NULL
; /* Used by stack_snapshot2 (to be removed) */
111 __private_extern__
void stackshot_init( void );
112 static boolean_t
memory_iszero(void *addr
, size_t size
);
114 kern_return_t
stack_microstackshot(user_addr_t tracebuf
, uint32_t tracebuf_size
, uint32_t flags
, int32_t *retval
);
116 uint32_t get_stackshot_estsize(uint32_t prev_size_hint
);
117 kern_return_t
kern_stack_snapshot_internal(int stackshot_config_version
, void *stackshot_config
,
118 size_t stackshot_config_size
, boolean_t stackshot_from_user
);
119 kern_return_t
do_stackshot(void *);
120 void kdp_snapshot_preflight(int pid
, void * tracebuf
, uint32_t tracebuf_size
, uint32_t flags
, kcdata_descriptor_t data_p
, uint64_t since_timestamp
);
121 boolean_t
stackshot_thread_is_idle_worker_unsafe(thread_t thread
);
122 static int kdp_stackshot_kcdata_format(int pid
, uint32_t trace_flags
, uint32_t *pBytesTraced
);
123 uint32_t kdp_stack_snapshot_bytes_traced(void);
124 static void kdp_mem_and_io_snapshot(struct mem_and_io_snapshot
*memio_snap
);
125 static boolean_t
kdp_copyin(vm_map_t map
, uint64_t uaddr
, void *dest
, size_t size
, boolean_t try_fault
, uint32_t *kdp_fault_result
);
126 static boolean_t
kdp_copyin_word(task_t task
, uint64_t addr
, uint64_t *result
, boolean_t try_fault
, uint32_t *kdp_fault_results
);
127 static uint64_t proc_was_throttled_from_task(task_t task
);
128 static void stackshot_thread_wait_owner_info(thread_t thread
, thread_waitinfo_t
* waitinfo
);
129 static int stackshot_thread_has_valid_waitinfo(thread_t thread
);
131 #if CONFIG_COALITIONS
132 static void stackshot_coalition_jetsam_count(void *arg
, int i
, coalition_t coal
);
133 static void stackshot_coalition_jetsam_snapshot(void *arg
, int i
, coalition_t coal
);
134 #endif /* CONFIG_COALITIONS */
137 extern uint32_t workqueue_get_pwq_state_kdp(void *proc
);
139 extern int proc_pid(void *p
);
140 extern uint64_t proc_uniqueid(void *p
);
141 extern uint64_t proc_was_throttled(void *p
);
142 extern uint64_t proc_did_throttle(void *p
);
143 static uint64_t proc_did_throttle_from_task(task_t task
);
144 extern void proc_name_kdp(task_t task
, char * buf
, int size
);
145 extern int proc_threadname_kdp(void * uth
, char * buf
, size_t size
);
146 extern void proc_starttime_kdp(void * p
, uint64_t * tv_sec
, uint64_t * tv_usec
, uint64_t * abstime
);
147 extern int memorystatus_get_pressure_status_kdp(void);
148 extern boolean_t
memorystatus_proc_is_dirty_unsafe(void * v
);
150 extern int count_busy_buffers(void); /* must track with declaration in bsd/sys/buf_internal.h */
151 extern void bcopy_phys(addr64_t
, addr64_t
, vm_size_t
);
154 extern kern_return_t
stack_microstackshot(user_addr_t tracebuf
, uint32_t tracebuf_size
, uint32_t flags
, int32_t *retval
);
155 #endif /* CONFIG_TELEMETRY */
157 extern kern_return_t
kern_stack_snapshot_with_reason(char* reason
);
158 extern kern_return_t
kern_stack_snapshot_internal(int stackshot_config_version
, void *stackshot_config
, size_t stackshot_config_size
, boolean_t stackshot_from_user
);
161 * Validates that the given address is both a valid page and has
162 * default caching attributes for the current map. Returns
163 * 0 if the address is invalid, and a kernel virtual address for
164 * the given address if it is valid.
166 vm_offset_t
machine_trace_thread_get_kva(vm_offset_t cur_target_addr
, vm_map_t map
, uint32_t *thread_trace_flags
);
168 #define KDP_FAULT_RESULT_PAGED_OUT 0x1 /* some data was unable to be retrieved */
169 #define KDP_FAULT_RESULT_TRIED_FAULT 0x2 /* tried to fault in data */
170 #define KDP_FAULT_RESULT_FAULTED_IN 0x4 /* successfully faulted in data */
173 * Looks up the physical translation for the given address in the target map, attempting
174 * to fault data in if requested and it is not resident. Populates thread_trace_flags if requested
177 vm_offset_t
kdp_find_phys(vm_map_t map
, vm_offset_t target_addr
, boolean_t try_fault
, uint32_t *kdp_fault_results
);
179 static size_t stackshot_strlcpy(char *dst
, const char *src
, size_t maxlen
);
180 static void stackshot_memcpy(void *dst
, const void *src
, size_t len
);
182 /* Clears caching information used by the above validation routine
183 * (in case the current map has been changed or cleared).
185 void machine_trace_thread_clear_validation_cache(void);
187 #define MAX_FRAMES 1000
188 #define MAX_LOADINFOS 500
189 #define TASK_IMP_WALK_LIMIT 20
191 typedef struct thread_snapshot
*thread_snapshot_t
;
192 typedef struct task_snapshot
*task_snapshot_t
;
194 #if CONFIG_KDP_INTERACTIVE_DEBUGGING
195 extern kdp_send_t kdp_en_send_pkt
;
199 * Globals to support machine_trace_thread_get_kva.
201 static vm_offset_t prev_target_page
= 0;
202 static vm_offset_t prev_target_kva
= 0;
203 static boolean_t validate_next_addr
= TRUE
;
206 * Stackshot locking and other defines.
208 static lck_grp_t
*stackshot_subsys_lck_grp
;
209 static lck_grp_attr_t
*stackshot_subsys_lck_grp_attr
;
210 static lck_attr_t
*stackshot_subsys_lck_attr
;
211 static lck_mtx_t stackshot_subsys_mutex
;
213 #define STACKSHOT_SUBSYS_LOCK() lck_mtx_lock(&stackshot_subsys_mutex)
214 #define STACKSHOT_SUBSYS_TRY_LOCK() lck_mtx_try_lock(&stackshot_subsys_mutex)
215 #define STACKSHOT_SUBSYS_UNLOCK() lck_mtx_unlock(&stackshot_subsys_mutex)
217 #define SANE_BOOTPROFILE_TRACEBUF_SIZE (64 * 1024 * 1024)
218 #define SANE_TRACEBUF_SIZE (8 * 1024 * 1024)
221 * We currently set a ceiling of 3 milliseconds spent in the kdp fault path
222 * for non-panic stackshots where faulting is requested.
224 #define KDP_FAULT_PATH_MAX_TIME_PER_STACKSHOT_NSECS (3 * NSEC_PER_MSEC)
226 #define STACKSHOT_SUPP_SIZE (16 * 1024) /* Minimum stackshot size */
227 #define TASK_UUID_AVG_SIZE (16 * sizeof(uuid_t)) /* Average space consumed by UUIDs/task */
230 * Initialize the mutex governing access to the stack snapshot subsystem
231 * and other stackshot related bits.
233 __private_extern__
void
234 stackshot_init( void )
236 mach_timebase_info_data_t timebase
;
238 stackshot_subsys_lck_grp_attr
= lck_grp_attr_alloc_init();
240 stackshot_subsys_lck_grp
= lck_grp_alloc_init("stackshot_subsys_lock", stackshot_subsys_lck_grp_attr
);
242 stackshot_subsys_lck_attr
= lck_attr_alloc_init();
244 lck_mtx_init(&stackshot_subsys_mutex
, stackshot_subsys_lck_grp
, stackshot_subsys_lck_attr
);
246 clock_timebase_info(&timebase
);
247 fault_stats
.sfs_system_max_fault_time
= ((KDP_FAULT_PATH_MAX_TIME_PER_STACKSHOT_NSECS
* timebase
.denom
)/ timebase
.numer
);
251 * Method for grabbing timer values safely, in the sense that no infinite loop will occur
252 * Certain flavors of the timer_grab function, which would seem to be the thing to use,
253 * can loop infinitely if called while the timer is in the process of being updated.
254 * Unfortunately, it is (rarely) possible to get inconsistent top and bottom halves of
255 * the timer using this method. This seems insoluble, since stackshot runs in a context
256 * where the timer might be half-updated, and has no way of yielding control just long
257 * enough to finish the update.
260 static uint64_t safe_grab_timer_value(struct timer
*t
)
262 #if defined(__LP64__)
265 uint64_t time
= t
->high_bits
; /* endian independent grab */
266 time
= (time
<< 32) | t
->low_bits
;
272 * Called with interrupts disabled after stackshot context has been
273 * initialized. Updates stack_snapshot_ret.
278 return DebuggerTrapWithState(DBOP_STACKSHOT
, NULL
, NULL
, NULL
, 0, FALSE
, 0);
283 stack_snapshot_from_kernel(int pid
, void *buf
, uint32_t size
, uint32_t flags
, uint64_t delta_since_timestamp
, unsigned *bytes_traced
)
285 kern_return_t error
= KERN_SUCCESS
;
288 #if DEVELOPMENT || DEBUG
289 if (kern_feature_override(KF_STACKSHOT_OVRD
) == TRUE
) {
290 error
= KERN_NOT_SUPPORTED
;
294 if ((buf
== NULL
) || (size
<= 0) || (bytes_traced
== NULL
)) {
295 return KERN_INVALID_ARGUMENT
;
298 /* cap in individual stackshot to SANE_TRACEBUF_SIZE */
299 if (size
> SANE_TRACEBUF_SIZE
) {
300 size
= SANE_TRACEBUF_SIZE
;
303 /* Serialize tracing */
304 if (flags
& STACKSHOT_TRYLOCK
) {
305 if (!STACKSHOT_SUBSYS_TRY_LOCK()) {
306 return KERN_LOCK_OWNED
;
309 STACKSHOT_SUBSYS_LOCK();
312 struct kcdata_descriptor kcdata
;
313 uint32_t hdr_tag
= (flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
) ?
314 KCDATA_BUFFER_BEGIN_DELTA_STACKSHOT
: KCDATA_BUFFER_BEGIN_STACKSHOT
;
316 error
= kcdata_memory_static_init(&kcdata
, (mach_vm_address_t
)buf
, hdr_tag
, size
,
317 KCFLAG_USE_MEMCOPY
| KCFLAG_NO_AUTO_ENDBUFFER
);
322 istate
= ml_set_interrupts_enabled(FALSE
);
324 /* Preload trace parameters*/
325 kdp_snapshot_preflight(pid
, buf
, size
, flags
, &kcdata
, delta_since_timestamp
);
328 * Trap to the debugger to obtain a coherent stack snapshot; this populates
331 error
= stackshot_trap();
333 ml_set_interrupts_enabled(istate
);
335 *bytes_traced
= kdp_stack_snapshot_bytes_traced();
338 stackshot_kcdata_p
= NULL
;
339 STACKSHOT_SUBSYS_UNLOCK();
345 stack_microstackshot(user_addr_t tracebuf
, uint32_t tracebuf_size
, uint32_t flags
, int32_t *retval
)
347 int error
= KERN_SUCCESS
;
348 uint32_t bytes_traced
= 0;
353 * Control related operations
355 if (flags
& STACKSHOT_GLOBAL_MICROSTACKSHOT_ENABLE
) {
356 telemetry_global_ctl(1);
359 } else if (flags
& STACKSHOT_GLOBAL_MICROSTACKSHOT_DISABLE
) {
360 telemetry_global_ctl(0);
366 * Data related operations
370 if ((((void*)tracebuf
) == NULL
) || (tracebuf_size
== 0)) {
371 error
= KERN_INVALID_ARGUMENT
;
375 STACKSHOT_SUBSYS_LOCK();
377 if (flags
& STACKSHOT_GET_MICROSTACKSHOT
) {
378 if (tracebuf_size
> SANE_TRACEBUF_SIZE
) {
379 error
= KERN_INVALID_ARGUMENT
;
383 bytes_traced
= tracebuf_size
;
384 error
= telemetry_gather(tracebuf
, &bytes_traced
,
385 (flags
& STACKSHOT_SET_MICROSTACKSHOT_MARK
) ? TRUE
: FALSE
);
386 *retval
= (int)bytes_traced
;
390 if (flags
& STACKSHOT_GET_BOOT_PROFILE
) {
392 if (tracebuf_size
> SANE_BOOTPROFILE_TRACEBUF_SIZE
) {
393 error
= KERN_INVALID_ARGUMENT
;
397 bytes_traced
= tracebuf_size
;
398 error
= bootprofile_gather(tracebuf
, &bytes_traced
);
399 *retval
= (int)bytes_traced
;
403 STACKSHOT_SUBSYS_UNLOCK();
407 #endif /* CONFIG_TELEMETRY */
410 * Return the estimated size of a stackshot based on the
411 * number of currently running threads and tasks.
414 get_stackshot_estsize(uint32_t prev_size_hint
)
416 vm_size_t thread_total
;
417 vm_size_t task_total
;
418 uint32_t estimated_size
;
420 thread_total
= (threads_count
* sizeof(struct thread_snapshot
));
421 task_total
= (tasks_count
* (sizeof(struct task_snapshot
) + TASK_UUID_AVG_SIZE
));
423 estimated_size
= (uint32_t) VM_MAP_ROUND_PAGE((thread_total
+ task_total
+ STACKSHOT_SUPP_SIZE
), PAGE_MASK
);
424 if (estimated_size
< prev_size_hint
) {
425 estimated_size
= (uint32_t) VM_MAP_ROUND_PAGE(prev_size_hint
, PAGE_MASK
);
428 return estimated_size
;
432 * stackshot_remap_buffer: Utility function to remap bytes_traced bytes starting at stackshotbuf
433 * into the current task's user space and subsequently copy out the address
434 * at which the buffer has been mapped in user space to out_buffer_addr.
436 * Inputs: stackshotbuf - pointer to the original buffer in the kernel's address space
437 * bytes_traced - length of the buffer to remap starting from stackshotbuf
438 * out_buffer_addr - pointer to placeholder where newly mapped buffer will be mapped.
439 * out_size_addr - pointer to be filled in with the size of the buffer
441 * Outputs: ENOSPC if there is not enough free space in the task's address space to remap the buffer
442 * EINVAL for all other errors returned by task_remap_buffer/mach_vm_remap
443 * an error from copyout
446 stackshot_remap_buffer(void *stackshotbuf
, uint32_t bytes_traced
, uint64_t out_buffer_addr
, uint64_t out_size_addr
)
449 mach_vm_offset_t stackshotbuf_user_addr
= (mach_vm_offset_t
)NULL
;
450 vm_prot_t cur_prot
, max_prot
;
452 error
= mach_vm_remap_kernel(get_task_map(current_task()), &stackshotbuf_user_addr
, bytes_traced
, 0,
453 VM_FLAGS_ANYWHERE
, VM_KERN_MEMORY_NONE
, kernel_map
, (mach_vm_offset_t
)stackshotbuf
, FALSE
, &cur_prot
, &max_prot
, VM_INHERIT_DEFAULT
);
455 * If the call to mach_vm_remap fails, we return the appropriate converted error
457 if (error
== KERN_SUCCESS
) {
459 * If we fail to copy out the address or size of the new buffer, we remove the buffer mapping that
460 * we just made in the task's user space.
462 error
= copyout(CAST_DOWN(void *, &stackshotbuf_user_addr
), (user_addr_t
)out_buffer_addr
, sizeof(stackshotbuf_user_addr
));
463 if (error
!= KERN_SUCCESS
) {
464 mach_vm_deallocate(get_task_map(current_task()), stackshotbuf_user_addr
, (mach_vm_size_t
)bytes_traced
);
467 error
= copyout(&bytes_traced
, (user_addr_t
)out_size_addr
, sizeof(bytes_traced
));
468 if (error
!= KERN_SUCCESS
) {
469 mach_vm_deallocate(get_task_map(current_task()), stackshotbuf_user_addr
, (mach_vm_size_t
)bytes_traced
);
477 kern_stack_snapshot_internal(int stackshot_config_version
, void *stackshot_config
, size_t stackshot_config_size
, boolean_t stackshot_from_user
)
480 boolean_t prev_interrupt_state
;
481 uint32_t bytes_traced
= 0;
482 uint32_t stackshotbuf_size
= 0;
483 void * stackshotbuf
= NULL
;
484 kcdata_descriptor_t kcdata_p
= NULL
;
486 void * buf_to_free
= NULL
;
487 int size_to_free
= 0;
489 /* Parsed arguments */
490 uint64_t out_buffer_addr
;
491 uint64_t out_size_addr
;
494 uint64_t since_timestamp
;
495 uint32_t size_hint
= 0;
497 if(stackshot_config
== NULL
) {
498 return KERN_INVALID_ARGUMENT
;
500 #if DEVELOPMENT || DEBUG
501 /* TBD: ask stackshot clients to avoid issuing stackshots in this
502 * configuration in lieu of the kernel feature override.
504 if (kern_feature_override(KF_STACKSHOT_OVRD
) == TRUE
) {
505 return KERN_NOT_SUPPORTED
;
509 switch (stackshot_config_version
) {
510 case STACKSHOT_CONFIG_TYPE
:
511 if (stackshot_config_size
!= sizeof(stackshot_config_t
)) {
512 return KERN_INVALID_ARGUMENT
;
514 stackshot_config_t
*config
= (stackshot_config_t
*) stackshot_config
;
515 out_buffer_addr
= config
->sc_out_buffer_addr
;
516 out_size_addr
= config
->sc_out_size_addr
;
517 pid
= config
->sc_pid
;
518 flags
= config
->sc_flags
;
519 since_timestamp
= config
->sc_delta_timestamp
;
520 if (config
->sc_size
<= SANE_TRACEBUF_SIZE
) {
521 size_hint
= config
->sc_size
;
525 return KERN_NOT_SUPPORTED
;
529 * Currently saving a kernel buffer and trylock are only supported from the
532 if (stackshot_from_user
) {
533 if (flags
& (STACKSHOT_TRYLOCK
| STACKSHOT_SAVE_IN_KERNEL_BUFFER
| STACKSHOT_FROM_PANIC
)) {
534 return KERN_NO_ACCESS
;
537 if (!(flags
& STACKSHOT_SAVE_IN_KERNEL_BUFFER
)) {
538 return KERN_NOT_SUPPORTED
;
542 if (!((flags
& STACKSHOT_KCDATA_FORMAT
) || (flags
& STACKSHOT_RETRIEVE_EXISTING_BUFFER
))) {
543 return KERN_NOT_SUPPORTED
;
547 * If we're not saving the buffer in the kernel pointer, we need a place to copy into.
549 if ((!out_buffer_addr
|| !out_size_addr
) && !(flags
& STACKSHOT_SAVE_IN_KERNEL_BUFFER
)) {
550 return KERN_INVALID_ARGUMENT
;
553 if (since_timestamp
!= 0 && ((flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
) == 0)) {
554 return KERN_INVALID_ARGUMENT
;
558 if (!mt_core_supported
) {
559 flags
&= ~STACKSHOT_INSTRS_CYCLES
;
561 #else /* MONOTONIC */
562 flags
&= ~STACKSHOT_INSTRS_CYCLES
;
563 #endif /* !MONOTONIC */
565 STACKSHOT_SUBSYS_LOCK();
567 if (flags
& STACKSHOT_SAVE_IN_KERNEL_BUFFER
) {
569 * Don't overwrite an existing stackshot
571 if (kernel_stackshot_buf
!= NULL
) {
572 error
= KERN_MEMORY_PRESENT
;
575 } else if (flags
& STACKSHOT_RETRIEVE_EXISTING_BUFFER
) {
576 if ((kernel_stackshot_buf
== NULL
) || (kernel_stackshot_buf_size
<= 0)) {
577 error
= KERN_NOT_IN_SET
;
580 error
= stackshot_remap_buffer(kernel_stackshot_buf
, kernel_stackshot_buf_size
,
581 out_buffer_addr
, out_size_addr
);
583 * If we successfully remapped the buffer into the user's address space, we
584 * set buf_to_free and size_to_free so the prior kernel mapping will be removed
585 * and then clear the kernel stackshot pointer and associated size.
587 if (error
== KERN_SUCCESS
) {
588 buf_to_free
= kernel_stackshot_buf
;
589 size_to_free
= (int) VM_MAP_ROUND_PAGE(kernel_stackshot_buf_size
, PAGE_MASK
);
590 kernel_stackshot_buf
= NULL
;
591 kernel_stackshot_buf_size
= 0;
597 if (flags
& STACKSHOT_GET_BOOT_PROFILE
) {
598 void *bootprofile
= NULL
;
601 bootprofile_get(&bootprofile
, &len
);
603 if (!bootprofile
|| !len
) {
604 error
= KERN_NOT_IN_SET
;
607 error
= stackshot_remap_buffer(bootprofile
, len
, out_buffer_addr
, out_size_addr
);
611 stackshotbuf_size
= get_stackshot_estsize(size_hint
);
613 for (; stackshotbuf_size
<= SANE_TRACEBUF_SIZE
; stackshotbuf_size
<<= 1) {
614 if (kmem_alloc(kernel_map
, (vm_offset_t
*)&stackshotbuf
, stackshotbuf_size
, VM_KERN_MEMORY_DIAG
) != KERN_SUCCESS
) {
615 error
= KERN_RESOURCE_SHORTAGE
;
620 uint32_t hdr_tag
= (flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
) ? KCDATA_BUFFER_BEGIN_DELTA_STACKSHOT
: KCDATA_BUFFER_BEGIN_STACKSHOT
;
621 kcdata_p
= kcdata_memory_alloc_init((mach_vm_address_t
)stackshotbuf
, hdr_tag
, stackshotbuf_size
,
622 KCFLAG_USE_MEMCOPY
| KCFLAG_NO_AUTO_ENDBUFFER
);
624 stackshot_duration_outer
= NULL
;
625 uint64_t time_start
= mach_absolute_time();
628 * Disable interrupts and save the current interrupt state.
630 prev_interrupt_state
= ml_set_interrupts_enabled(FALSE
);
633 * Load stackshot parameters.
635 kdp_snapshot_preflight(pid
, stackshotbuf
, stackshotbuf_size
, flags
, kcdata_p
, since_timestamp
);
637 error
= stackshot_trap();
639 ml_set_interrupts_enabled(prev_interrupt_state
);
641 /* record the duration that interupts were disabled */
643 uint64_t time_end
= mach_absolute_time();
644 if (stackshot_duration_outer
) {
645 *stackshot_duration_outer
= time_end
- time_start
;
648 if (error
!= KERN_SUCCESS
) {
649 if (kcdata_p
!= NULL
) {
650 kcdata_memory_destroy(kcdata_p
);
652 stackshot_kcdata_p
= NULL
;
654 kmem_free(kernel_map
, (vm_offset_t
)stackshotbuf
, stackshotbuf_size
);
656 if (error
== KERN_INSUFFICIENT_BUFFER_SIZE
) {
658 * If we didn't allocate a big enough buffer, deallocate and try again.
666 bytes_traced
= kdp_stack_snapshot_bytes_traced();
668 if (bytes_traced
<= 0) {
669 error
= KERN_ABORTED
;
673 assert(bytes_traced
<= stackshotbuf_size
);
674 if (!(flags
& STACKSHOT_SAVE_IN_KERNEL_BUFFER
)) {
675 error
= stackshot_remap_buffer(stackshotbuf
, bytes_traced
, out_buffer_addr
, out_size_addr
);
680 * Save the stackshot in the kernel buffer.
682 kernel_stackshot_buf
= stackshotbuf
;
683 kernel_stackshot_buf_size
= bytes_traced
;
685 * Figure out if we didn't use all the pages in the buffer. If so, we set buf_to_free to the beginning of
686 * the next page after the end of the stackshot in the buffer so that the kmem_free clips the buffer and
687 * update size_to_free for kmem_free accordingly.
689 size_to_free
= stackshotbuf_size
- (int) VM_MAP_ROUND_PAGE(bytes_traced
, PAGE_MASK
);
691 assert(size_to_free
>= 0);
693 if (size_to_free
!= 0) {
694 buf_to_free
= (void *)((uint64_t)stackshotbuf
+ stackshotbuf_size
- size_to_free
);
698 stackshotbuf_size
= 0;
702 if (stackshotbuf_size
> SANE_TRACEBUF_SIZE
) {
703 error
= KERN_RESOURCE_SHORTAGE
;
707 if (kcdata_p
!= NULL
) {
708 kcdata_memory_destroy(kcdata_p
);
710 stackshot_kcdata_p
= NULL
;
713 if (stackshotbuf
!= NULL
) {
714 kmem_free(kernel_map
, (vm_offset_t
)stackshotbuf
, stackshotbuf_size
);
716 if (buf_to_free
!= NULL
) {
717 kmem_free(kernel_map
, (vm_offset_t
)buf_to_free
, size_to_free
);
719 STACKSHOT_SUBSYS_UNLOCK();
724 * Cache stack snapshot parameters in preparation for a trace.
727 kdp_snapshot_preflight(int pid
, void * tracebuf
, uint32_t tracebuf_size
, uint32_t flags
,
728 kcdata_descriptor_t data_p
, uint64_t since_timestamp
)
730 uint64_t microsecs
= 0, secs
= 0;
731 clock_get_calendar_microtime((clock_sec_t
*)&secs
, (clock_usec_t
*)µsecs
);
733 stackshot_microsecs
= microsecs
+ (secs
* USEC_PER_SEC
);
734 stack_snapshot_pid
= pid
;
735 stack_snapshot_buf
= tracebuf
;
736 stack_snapshot_bufsize
= tracebuf_size
;
737 stack_snapshot_flags
= flags
;
738 stack_snapshot_delta_since_timestamp
= since_timestamp
;
740 panic_stackshot
= ((flags
& STACKSHOT_FROM_PANIC
) != 0);
742 assert(data_p
!= NULL
);
743 assert(stackshot_kcdata_p
== NULL
);
744 stackshot_kcdata_p
= data_p
;
746 stack_snapshot_bytes_traced
= 0;
752 return (stackshot_kcdata_p
!= NULL
);
756 kdp_stack_snapshot_bytes_traced(void)
758 return stack_snapshot_bytes_traced
;
761 static boolean_t
memory_iszero(void *addr
, size_t size
)
763 char *data
= (char *)addr
;
764 for (size_t i
= 0; i
< size
; i
++){
771 #define kcd_end_address(kcd) ((void *)((uint64_t)((kcd)->kcd_addr_begin) + kcdata_memory_get_used_bytes((kcd))))
772 #define kcd_max_address(kcd) ((void *)((kcd)->kcd_addr_begin + (kcd)->kcd_length))
774 * Use of the kcd_exit_on_error(action) macro requires a local
775 * 'kern_return_t error' variable and 'error_exit' label.
777 #define kcd_exit_on_error(action) \
779 if (KERN_SUCCESS != (error = (action))) { \
780 if (error == KERN_RESOURCE_SHORTAGE) { \
781 error = KERN_INSUFFICIENT_BUFFER_SIZE; \
785 } while (0); /* end kcd_exit_on_error */
788 kcdata_get_task_ss_flags(task_t task
)
790 uint64_t ss_flags
= 0;
791 boolean_t task64
= task_has_64BitAddr(task
);
794 ss_flags
|= kUser64_p
;
795 if (!task
->active
|| task_is_a_corpse(task
))
796 ss_flags
|= kTerminatedSnapshot
;
797 if (task
->pidsuspended
)
798 ss_flags
|= kPidSuspended
;
801 if (task
->effective_policy
.tep_darwinbg
== 1)
802 ss_flags
|= kTaskDarwinBG
;
803 if (task
->requested_policy
.trp_role
== TASK_FOREGROUND_APPLICATION
)
804 ss_flags
|= kTaskIsForeground
;
805 if (task
->requested_policy
.trp_boosted
== 1)
806 ss_flags
|= kTaskIsBoosted
;
807 if (task
->effective_policy
.tep_sup_active
== 1)
808 ss_flags
|= kTaskIsSuppressed
;
809 #if CONFIG_MEMORYSTATUS
810 if (memorystatus_proc_is_dirty_unsafe(task
->bsd_info
))
811 ss_flags
|= kTaskIsDirty
;
814 ss_flags
|= (0x7 & workqueue_get_pwq_state_kdp(task
->bsd_info
)) << 17;
816 #if IMPORTANCE_INHERITANCE
817 if (task
->task_imp_base
) {
818 if (task
->task_imp_base
->iit_donor
)
819 ss_flags
|= kTaskIsImpDonor
;
820 if (task
->task_imp_base
->iit_live_donor
)
821 ss_flags
|= kTaskIsLiveImpDonor
;
829 kcdata_record_shared_cache_info(kcdata_descriptor_t kcd
, task_t task
, struct dyld_uuid_info_64_v2
*sys_shared_cache_loadinfo
, unaligned_u64
*task_snap_ss_flags
)
831 kern_return_t error
= KERN_SUCCESS
;
832 mach_vm_address_t out_addr
= 0;
834 uint64_t shared_cache_slide
= 0;
835 uint64_t shared_cache_base_address
= 0;
836 int task_pid
= pid_from_task(task
);
837 uint32_t kdp_fault_results
= 0;
839 assert(task_snap_ss_flags
!= NULL
);
841 if (task
->shared_region
&& ml_validate_nofault((vm_offset_t
)task
->shared_region
, sizeof(struct vm_shared_region
))) {
842 struct vm_shared_region
*sr
= task
->shared_region
;
843 shared_cache_base_address
= sr
->sr_base_address
+ sr
->sr_first_mapping
;
845 *task_snap_ss_flags
|= kTaskSharedRegionInfoUnavailable
;
849 /* We haven't copied in the shared region UUID yet as part of setup */
850 if (!shared_cache_base_address
|| !task
->shared_region
->sr_uuid_copied
) {
855 * No refcounting here, but we are in debugger
856 * context, so that should be safe.
858 shared_cache_slide
= task
->shared_region
->sr_slide_info
.slide
;
860 if (sys_shared_cache_loadinfo
) {
862 /* save launchd's shared cache info as system level */
863 stackshot_memcpy(sys_shared_cache_loadinfo
->imageUUID
, &task
->shared_region
->sr_uuid
, sizeof(task
->shared_region
->sr_uuid
));
864 sys_shared_cache_loadinfo
->imageLoadAddress
= shared_cache_slide
;
865 sys_shared_cache_loadinfo
->imageSlidBaseAddress
= shared_cache_slide
+ task
->shared_region
->sr_base_address
;
869 if (shared_cache_slide
== sys_shared_cache_loadinfo
->imageLoadAddress
&&
870 0 == memcmp(&task
->shared_region
->sr_uuid
, sys_shared_cache_loadinfo
->imageUUID
,
871 sizeof(task
->shared_region
->sr_uuid
))) {
872 /* skip adding shared cache info. its same as system level one */
878 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_SHAREDCACHE_LOADINFO
, sizeof(struct dyld_uuid_info_64_v2
), &out_addr
));
879 struct dyld_uuid_info_64_v2
*shared_cache_data
= (struct dyld_uuid_info_64_v2
*)out_addr
;
880 shared_cache_data
->imageLoadAddress
= shared_cache_slide
;
881 stackshot_memcpy(shared_cache_data
->imageUUID
, task
->shared_region
->sr_uuid
, sizeof(task
->shared_region
->sr_uuid
));
882 shared_cache_data
->imageSlidBaseAddress
= shared_cache_base_address
;
885 if (kdp_fault_results
& KDP_FAULT_RESULT_PAGED_OUT
) {
886 *task_snap_ss_flags
|= kTaskUUIDInfoMissing
;
889 if (kdp_fault_results
& KDP_FAULT_RESULT_TRIED_FAULT
) {
890 *task_snap_ss_flags
|= kTaskUUIDInfoTriedFault
;
893 if (kdp_fault_results
& KDP_FAULT_RESULT_FAULTED_IN
) {
894 *task_snap_ss_flags
|= kTaskUUIDInfoFaultedIn
;
901 kcdata_record_uuid_info(kcdata_descriptor_t kcd
, task_t task
, uint32_t trace_flags
, boolean_t have_pmap
, unaligned_u64
*task_snap_ss_flags
)
903 boolean_t save_loadinfo_p
= ((trace_flags
& STACKSHOT_SAVE_LOADINFO
) != 0);
904 boolean_t save_kextloadinfo_p
= ((trace_flags
& STACKSHOT_SAVE_KEXT_LOADINFO
) != 0);
905 boolean_t collect_delta_stackshot
= ((trace_flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
) != 0);
906 boolean_t minimize_uuids
= collect_delta_stackshot
&& ((trace_flags
& STACKSHOT_TAILSPIN
) != 0);
907 boolean_t should_fault
= (trace_flags
& STACKSHOT_ENABLE_UUID_FAULTING
);
909 kern_return_t error
= KERN_SUCCESS
;
910 mach_vm_address_t out_addr
= 0;
912 uint32_t uuid_info_count
= 0;
913 mach_vm_address_t uuid_info_addr
= 0;
914 uint64_t uuid_info_timestamp
= 0;
915 uint32_t kdp_fault_results
= 0;
917 assert(task_snap_ss_flags
!= NULL
);
919 int task_pid
= pid_from_task(task
);
920 boolean_t task64
= task_has_64BitAddr(task
);
922 if (save_loadinfo_p
&& have_pmap
&& task
->active
&& task_pid
> 0) {
923 /* Read the dyld_all_image_infos struct from the task memory to get UUID array count and location */
925 struct user64_dyld_all_image_infos task_image_infos
;
926 if (kdp_copyin(task
->map
, task
->all_image_info_addr
, &task_image_infos
,
927 sizeof(struct user64_dyld_all_image_infos
), should_fault
, &kdp_fault_results
)) {
928 uuid_info_count
= (uint32_t)task_image_infos
.uuidArrayCount
;
929 uuid_info_addr
= task_image_infos
.uuidArray
;
930 if (task_image_infos
.version
>= DYLD_ALL_IMAGE_INFOS_TIMESTAMP_MINIMUM_VERSION
) {
931 uuid_info_timestamp
= task_image_infos
.timestamp
;
935 struct user32_dyld_all_image_infos task_image_infos
;
936 if (kdp_copyin(task
->map
, task
->all_image_info_addr
, &task_image_infos
,
937 sizeof(struct user32_dyld_all_image_infos
), should_fault
, &kdp_fault_results
)) {
938 uuid_info_count
= task_image_infos
.uuidArrayCount
;
939 uuid_info_addr
= task_image_infos
.uuidArray
;
940 if (task_image_infos
.version
>= DYLD_ALL_IMAGE_INFOS_TIMESTAMP_MINIMUM_VERSION
) {
941 uuid_info_timestamp
= task_image_infos
.timestamp
;
947 * If we get a NULL uuid_info_addr (which can happen when we catch dyld in the middle of updating
948 * this data structure), we zero the uuid_info_count so that we won't even try to save load info
951 if (!uuid_info_addr
) {
956 if (have_pmap
&& task_pid
== 0) {
957 if (save_kextloadinfo_p
&& ml_validate_nofault((vm_offset_t
)(gLoadedKextSummaries
), sizeof(OSKextLoadedKextSummaryHeader
))) {
958 uuid_info_count
= gLoadedKextSummaries
->numSummaries
+ 1; /* include main kernel UUID */
960 uuid_info_count
= 1; /* include kernelcache UUID (embedded) or kernel UUID (desktop) */
964 if (task_pid
> 0 && uuid_info_count
> 0 && uuid_info_count
< MAX_LOADINFOS
) {
965 if (minimize_uuids
&& uuid_info_timestamp
!= 0 && uuid_info_timestamp
< stack_snapshot_delta_since_timestamp
)
968 uint32_t uuid_info_size
= (uint32_t)(task64
? sizeof(struct user64_dyld_uuid_info
) : sizeof(struct user32_dyld_uuid_info
));
969 uint32_t uuid_info_array_size
= uuid_info_count
* uuid_info_size
;
971 kcd_exit_on_error(kcdata_get_memory_addr_for_array(kcd
, (task64
? KCDATA_TYPE_LIBRARY_LOADINFO64
: KCDATA_TYPE_LIBRARY_LOADINFO
),
972 uuid_info_size
, uuid_info_count
, &out_addr
));
974 /* Copy in the UUID info array
975 * It may be nonresident, in which case just fix up nloadinfos to 0 in the task_snap
977 if (have_pmap
&& !kdp_copyin(task
->map
, uuid_info_addr
, (void *)out_addr
, uuid_info_array_size
, should_fault
, &kdp_fault_results
)) {
978 bzero((void *)out_addr
, uuid_info_array_size
);
981 } else if (task_pid
== 0 && uuid_info_count
> 0 && uuid_info_count
< MAX_LOADINFOS
) {
982 if (minimize_uuids
&& gLoadedKextSummaries
!= 0 && gLoadedKextSummariesTimestamp
< stack_snapshot_delta_since_timestamp
)
985 uintptr_t image_load_address
;
990 if (!save_kextloadinfo_p
) {
991 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_KERNELCACHE_LOADINFO
, sizeof(struct dyld_uuid_info_64
), &out_addr
));
992 struct dyld_uuid_info_64
*kc_uuid
= (struct dyld_uuid_info_64
*)out_addr
;
993 kc_uuid
->imageLoadAddress
= VM_MIN_KERNEL_AND_KEXT_ADDRESS
;
994 stackshot_memcpy(&kc_uuid
->imageUUID
, &kernelcache_uuid
, sizeof(uuid_t
));
997 #endif /* CONFIG_EMBEDDED */
999 if (!kernel_uuid
|| !ml_validate_nofault((vm_offset_t
)kernel_uuid
, sizeof(uuid_t
))) {
1000 /* Kernel UUID not found or inaccessible */
1004 kcd_exit_on_error(kcdata_get_memory_addr_for_array(
1005 kcd
, (sizeof(kernel_uuid_info
) == sizeof(struct user64_dyld_uuid_info
)) ? KCDATA_TYPE_LIBRARY_LOADINFO64
1006 : KCDATA_TYPE_LIBRARY_LOADINFO
,
1007 sizeof(kernel_uuid_info
), uuid_info_count
, &out_addr
));
1008 kernel_uuid_info
*uuid_info_array
= (kernel_uuid_info
*)out_addr
;
1009 image_load_address
= (uintptr_t)VM_KERNEL_UNSLIDE(vm_kernel_stext
);
1010 uuid_info_array
[0].imageLoadAddress
= image_load_address
;
1011 stackshot_memcpy(&uuid_info_array
[0].imageUUID
, kernel_uuid
, sizeof(uuid_t
));
1013 if (save_kextloadinfo_p
&&
1014 ml_validate_nofault((vm_offset_t
)(gLoadedKextSummaries
), sizeof(OSKextLoadedKextSummaryHeader
)) &&
1015 ml_validate_nofault((vm_offset_t
)(&gLoadedKextSummaries
->summaries
[0]),
1016 gLoadedKextSummaries
->entry_size
* gLoadedKextSummaries
->numSummaries
)) {
1018 for (kexti
=0 ; kexti
< gLoadedKextSummaries
->numSummaries
; kexti
++) {
1019 image_load_address
= (uintptr_t)VM_KERNEL_UNSLIDE(gLoadedKextSummaries
->summaries
[kexti
].address
);
1020 uuid_info_array
[kexti
+ 1].imageLoadAddress
= image_load_address
;
1021 stackshot_memcpy(&uuid_info_array
[kexti
+ 1].imageUUID
, &gLoadedKextSummaries
->summaries
[kexti
].uuid
, sizeof(uuid_t
));
1028 if (kdp_fault_results
& KDP_FAULT_RESULT_PAGED_OUT
) {
1029 *task_snap_ss_flags
|= kTaskUUIDInfoMissing
;
1032 if (kdp_fault_results
& KDP_FAULT_RESULT_TRIED_FAULT
) {
1033 *task_snap_ss_flags
|= kTaskUUIDInfoTriedFault
;
1036 if (kdp_fault_results
& KDP_FAULT_RESULT_FAULTED_IN
) {
1037 *task_snap_ss_flags
|= kTaskUUIDInfoFaultedIn
;
1043 static kern_return_t
1044 kcdata_record_task_iostats(kcdata_descriptor_t kcd
, task_t task
)
1046 kern_return_t error
= KERN_SUCCESS
;
1047 mach_vm_address_t out_addr
= 0;
1049 /* I/O Statistics if any counters are non zero */
1050 assert(IO_NUM_PRIORITIES
== STACKSHOT_IO_NUM_PRIORITIES
);
1051 if (task
->task_io_stats
&& !memory_iszero(task
->task_io_stats
, sizeof(struct io_stat_info
))) {
1052 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_IOSTATS
, sizeof(struct io_stats_snapshot
), &out_addr
));
1053 struct io_stats_snapshot
*_iostat
= (struct io_stats_snapshot
*)out_addr
;
1054 _iostat
->ss_disk_reads_count
= task
->task_io_stats
->disk_reads
.count
;
1055 _iostat
->ss_disk_reads_size
= task
->task_io_stats
->disk_reads
.size
;
1056 _iostat
->ss_disk_writes_count
= (task
->task_io_stats
->total_io
.count
- task
->task_io_stats
->disk_reads
.count
);
1057 _iostat
->ss_disk_writes_size
= (task
->task_io_stats
->total_io
.size
- task
->task_io_stats
->disk_reads
.size
);
1058 _iostat
->ss_paging_count
= task
->task_io_stats
->paging
.count
;
1059 _iostat
->ss_paging_size
= task
->task_io_stats
->paging
.size
;
1060 _iostat
->ss_non_paging_count
= (task
->task_io_stats
->total_io
.count
- task
->task_io_stats
->paging
.count
);
1061 _iostat
->ss_non_paging_size
= (task
->task_io_stats
->total_io
.size
- task
->task_io_stats
->paging
.size
);
1062 _iostat
->ss_metadata_count
= task
->task_io_stats
->metadata
.count
;
1063 _iostat
->ss_metadata_size
= task
->task_io_stats
->metadata
.size
;
1064 _iostat
->ss_data_count
= (task
->task_io_stats
->total_io
.count
- task
->task_io_stats
->metadata
.count
);
1065 _iostat
->ss_data_size
= (task
->task_io_stats
->total_io
.size
- task
->task_io_stats
->metadata
.size
);
1066 for(int i
= 0; i
< IO_NUM_PRIORITIES
; i
++) {
1067 _iostat
->ss_io_priority_count
[i
] = task
->task_io_stats
->io_priority
[i
].count
;
1068 _iostat
->ss_io_priority_size
[i
] = task
->task_io_stats
->io_priority
[i
].size
;
1076 static kern_return_t
1077 kcdata_record_task_snapshot(kcdata_descriptor_t kcd
, task_t task
, uint32_t trace_flags
, boolean_t have_pmap
, unaligned_u64
**task_snap_ss_flags
)
1079 boolean_t collect_delta_stackshot
= ((trace_flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
) != 0);
1080 boolean_t collect_iostats
= !collect_delta_stackshot
&& !(trace_flags
& STACKSHOT_TAILSPIN
) && !(trace_flags
& STACKSHOT_NO_IO_STATS
);
1082 boolean_t collect_instrs_cycles
= ((trace_flags
& STACKSHOT_INSTRS_CYCLES
) != 0);
1083 #endif /* MONOTONIC */
1085 kern_return_t error
= KERN_SUCCESS
;
1086 mach_vm_address_t out_addr
= 0;
1087 struct task_snapshot_v2
* cur_tsnap
= NULL
;
1089 assert(task_snap_ss_flags
!= NULL
);
1091 int task_pid
= pid_from_task(task
);
1092 uint64_t task_uniqueid
= get_task_uniqueid(task
);
1093 uint64_t proc_starttime_secs
= 0;
1095 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_TASK_SNAPSHOT
, sizeof(struct task_snapshot_v2
), &out_addr
));
1097 cur_tsnap
= (struct task_snapshot_v2
*)out_addr
;
1099 cur_tsnap
->ts_unique_pid
= task_uniqueid
;
1100 cur_tsnap
->ts_ss_flags
= kcdata_get_task_ss_flags(task
);
1101 *task_snap_ss_flags
= (unaligned_u64
*)&cur_tsnap
->ts_ss_flags
;
1102 cur_tsnap
->ts_user_time_in_terminated_threads
= task
->total_user_time
;
1103 cur_tsnap
->ts_system_time_in_terminated_threads
= task
->total_system_time
;
1105 proc_starttime_kdp(task
->bsd_info
, &proc_starttime_secs
, NULL
, NULL
);
1106 cur_tsnap
->ts_p_start_sec
= proc_starttime_secs
;
1109 cur_tsnap
->ts_task_size
= have_pmap
? get_task_phys_footprint(task
) : 0;
1111 cur_tsnap
->ts_task_size
= have_pmap
? (pmap_resident_count(task
->map
->pmap
) * PAGE_SIZE
) : 0;
1113 cur_tsnap
->ts_max_resident_size
= get_task_resident_max(task
);
1114 cur_tsnap
->ts_suspend_count
= task
->suspend_count
;
1115 cur_tsnap
->ts_faults
= task
->faults
;
1116 cur_tsnap
->ts_pageins
= task
->pageins
;
1117 cur_tsnap
->ts_cow_faults
= task
->cow_faults
;
1118 cur_tsnap
->ts_was_throttled
= (uint32_t) proc_was_throttled_from_task(task
);
1119 cur_tsnap
->ts_did_throttle
= (uint32_t) proc_did_throttle_from_task(task
);
1120 cur_tsnap
->ts_latency_qos
= (task
->effective_policy
.tep_latency_qos
== LATENCY_QOS_TIER_UNSPECIFIED
) ?
1121 LATENCY_QOS_TIER_UNSPECIFIED
: ((0xFF << 16) | task
->effective_policy
.tep_latency_qos
);
1122 cur_tsnap
->ts_pid
= task_pid
;
1124 /* Add the BSD process identifiers */
1125 if (task_pid
!= -1 && task
->bsd_info
!= NULL
) {
1126 proc_name_kdp(task
, cur_tsnap
->ts_p_comm
, sizeof(cur_tsnap
->ts_p_comm
));
1127 #if CONFIG_COALITIONS
1128 if (trace_flags
& STACKSHOT_SAVE_JETSAM_COALITIONS
) {
1129 uint64_t jetsam_coal_id
= coalition_id(task
->coalition
[COALITION_TYPE_JETSAM
]);
1130 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_JETSAM_COALITION
, sizeof(jetsam_coal_id
), &out_addr
));
1131 stackshot_memcpy((void*)out_addr
, &jetsam_coal_id
, sizeof(jetsam_coal_id
));
1133 #endif /* CONFIG_COALITIONS */
1136 cur_tsnap
->ts_p_comm
[0] = '\0';
1137 #if IMPORTANCE_INHERITANCE && (DEVELOPMENT || DEBUG)
1138 if (task
->task_imp_base
!= NULL
) {
1139 stackshot_strlcpy(cur_tsnap
->ts_p_comm
, &task
->task_imp_base
->iit_procname
[0],
1140 MIN((int)sizeof(task
->task_imp_base
->iit_procname
), (int)sizeof(cur_tsnap
->ts_p_comm
)));
1142 #endif /* IMPORTANCE_INHERITANCE && (DEVELOPMENT || DEBUG) */
1145 if (collect_iostats
) {
1146 kcd_exit_on_error(kcdata_record_task_iostats(kcd
, task
));
1150 if (collect_instrs_cycles
) {
1151 uint64_t instrs
= 0, cycles
= 0;
1152 mt_stackshot_task(task
, &instrs
, &cycles
);
1154 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_INSTRS_CYCLES
, sizeof(struct instrs_cycles_snapshot
), &out_addr
));
1155 struct instrs_cycles_snapshot
*instrs_cycles
= (struct instrs_cycles_snapshot
*)out_addr
;
1156 instrs_cycles
->ics_instructions
= instrs
;
1157 instrs_cycles
->ics_cycles
= cycles
;
1159 #endif /* MONOTONIC */
1165 static kern_return_t
1166 kcdata_record_task_delta_snapshot(kcdata_descriptor_t kcd
, task_t task
, boolean_t have_pmap
, unaligned_u64
**task_snap_ss_flags
)
1168 kern_return_t error
= KERN_SUCCESS
;
1169 struct task_delta_snapshot_v2
* cur_tsnap
= NULL
;
1170 mach_vm_address_t out_addr
= 0;
1172 uint64_t task_uniqueid
= get_task_uniqueid(task
);
1173 assert(task_snap_ss_flags
!= NULL
);
1175 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_TASK_DELTA_SNAPSHOT
, sizeof(struct task_delta_snapshot_v2
), &out_addr
));
1177 cur_tsnap
= (struct task_delta_snapshot_v2
*)out_addr
;
1179 cur_tsnap
->tds_unique_pid
= task_uniqueid
;
1180 cur_tsnap
->tds_ss_flags
= kcdata_get_task_ss_flags(task
);
1181 *task_snap_ss_flags
= (unaligned_u64
*)&cur_tsnap
->tds_ss_flags
;
1183 cur_tsnap
->tds_user_time_in_terminated_threads
= task
->total_user_time
;
1184 cur_tsnap
->tds_system_time_in_terminated_threads
= task
->total_system_time
;
1187 cur_tsnap
->tds_task_size
= have_pmap
? get_task_phys_footprint(task
) : 0;
1189 cur_tsnap
->tds_task_size
= have_pmap
? (pmap_resident_count(task
->map
->pmap
) * PAGE_SIZE
) : 0;
1192 cur_tsnap
->tds_max_resident_size
= get_task_resident_max(task
);
1193 cur_tsnap
->tds_suspend_count
= task
->suspend_count
;
1194 cur_tsnap
->tds_faults
= task
->faults
;
1195 cur_tsnap
->tds_pageins
= task
->pageins
;
1196 cur_tsnap
->tds_cow_faults
= task
->cow_faults
;
1197 cur_tsnap
->tds_was_throttled
= (uint32_t)proc_was_throttled_from_task(task
);
1198 cur_tsnap
->tds_did_throttle
= (uint32_t)proc_did_throttle_from_task(task
);
1199 cur_tsnap
->tds_latency_qos
= (task
-> effective_policy
.tep_latency_qos
== LATENCY_QOS_TIER_UNSPECIFIED
)
1200 ? LATENCY_QOS_TIER_UNSPECIFIED
1201 : ((0xFF << 16) | task
-> effective_policy
.tep_latency_qos
);
1207 static kern_return_t
1208 kcdata_record_thread_iostats(kcdata_descriptor_t kcd
, thread_t thread
)
1210 kern_return_t error
= KERN_SUCCESS
;
1211 mach_vm_address_t out_addr
= 0;
1213 /* I/O Statistics */
1214 assert(IO_NUM_PRIORITIES
== STACKSHOT_IO_NUM_PRIORITIES
);
1215 if (thread
->thread_io_stats
&& !memory_iszero(thread
->thread_io_stats
, sizeof(struct io_stat_info
))) {
1216 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_IOSTATS
, sizeof(struct io_stats_snapshot
), &out_addr
));
1217 struct io_stats_snapshot
*_iostat
= (struct io_stats_snapshot
*)out_addr
;
1218 _iostat
->ss_disk_reads_count
= thread
->thread_io_stats
->disk_reads
.count
;
1219 _iostat
->ss_disk_reads_size
= thread
->thread_io_stats
->disk_reads
.size
;
1220 _iostat
->ss_disk_writes_count
= (thread
->thread_io_stats
->total_io
.count
- thread
->thread_io_stats
->disk_reads
.count
);
1221 _iostat
->ss_disk_writes_size
= (thread
->thread_io_stats
->total_io
.size
- thread
->thread_io_stats
->disk_reads
.size
);
1222 _iostat
->ss_paging_count
= thread
->thread_io_stats
->paging
.count
;
1223 _iostat
->ss_paging_size
= thread
->thread_io_stats
->paging
.size
;
1224 _iostat
->ss_non_paging_count
= (thread
->thread_io_stats
->total_io
.count
- thread
->thread_io_stats
->paging
.count
);
1225 _iostat
->ss_non_paging_size
= (thread
->thread_io_stats
->total_io
.size
- thread
->thread_io_stats
->paging
.size
);
1226 _iostat
->ss_metadata_count
= thread
->thread_io_stats
->metadata
.count
;
1227 _iostat
->ss_metadata_size
= thread
->thread_io_stats
->metadata
.size
;
1228 _iostat
->ss_data_count
= (thread
->thread_io_stats
->total_io
.count
- thread
->thread_io_stats
->metadata
.count
);
1229 _iostat
->ss_data_size
= (thread
->thread_io_stats
->total_io
.size
- thread
->thread_io_stats
->metadata
.size
);
1230 for(int i
= 0; i
< IO_NUM_PRIORITIES
; i
++) {
1231 _iostat
->ss_io_priority_count
[i
] = thread
->thread_io_stats
->io_priority
[i
].count
;
1232 _iostat
->ss_io_priority_size
[i
] = thread
->thread_io_stats
->io_priority
[i
].size
;
1240 static kern_return_t
1241 kcdata_record_thread_snapshot(
1242 kcdata_descriptor_t kcd
, thread_t thread
, task_t task
, uint32_t trace_flags
, boolean_t have_pmap
, boolean_t thread_on_core
)
1244 boolean_t dispatch_p
= ((trace_flags
& STACKSHOT_GET_DQ
) != 0);
1245 boolean_t active_kthreads_only_p
= ((trace_flags
& STACKSHOT_ACTIVE_KERNEL_THREADS_ONLY
) != 0);
1246 boolean_t trace_fp_p
= false;
1247 boolean_t collect_delta_stackshot
= ((trace_flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
) != 0);
1248 boolean_t collect_iostats
= !collect_delta_stackshot
&& !(trace_flags
& STACKSHOT_TAILSPIN
) && !(trace_flags
& STACKSHOT_NO_IO_STATS
);
1250 boolean_t collect_instrs_cycles
= ((trace_flags
& STACKSHOT_INSTRS_CYCLES
) != 0);
1251 #endif /* MONOTONIC */
1253 kern_return_t error
= KERN_SUCCESS
;
1254 mach_vm_address_t out_addr
= 0;
1255 int saved_count
= 0;
1257 struct thread_snapshot_v4
* cur_thread_snap
= NULL
;
1258 char cur_thread_name
[STACKSHOT_MAX_THREAD_NAME_SIZE
];
1260 boolean_t task64
= task_has_64BitAddr(task
);
1262 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_THREAD_SNAPSHOT
, sizeof(struct thread_snapshot_v4
), &out_addr
));
1263 cur_thread_snap
= (struct thread_snapshot_v4
*)out_addr
;
1265 /* Populate the thread snapshot header */
1266 cur_thread_snap
->ths_thread_id
= thread_tid(thread
);
1267 cur_thread_snap
->ths_wait_event
= VM_KERNEL_UNSLIDE_OR_PERM(thread
->wait_event
);
1268 cur_thread_snap
->ths_continuation
= VM_KERNEL_UNSLIDE(thread
->continuation
);
1269 cur_thread_snap
->ths_total_syscalls
= thread
->syscalls_mach
+ thread
->syscalls_unix
;
1271 if (IPC_VOUCHER_NULL
!= thread
->ith_voucher
)
1272 cur_thread_snap
->ths_voucher_identifier
= VM_KERNEL_ADDRPERM(thread
->ith_voucher
);
1274 cur_thread_snap
->ths_voucher_identifier
= 0;
1276 cur_thread_snap
->ths_dqserialnum
= 0;
1277 if (dispatch_p
&& (task
!= kernel_task
) && (task
->active
) && have_pmap
) {
1278 uint64_t dqkeyaddr
= thread_dispatchqaddr(thread
);
1279 if (dqkeyaddr
!= 0) {
1280 uint64_t dqaddr
= 0;
1281 boolean_t copyin_ok
= kdp_copyin_word(task
, dqkeyaddr
, &dqaddr
, FALSE
, NULL
);
1282 if (copyin_ok
&& dqaddr
!= 0) {
1283 uint64_t dqserialnumaddr
= dqaddr
+ get_task_dispatchqueue_serialno_offset(task
);
1284 uint64_t dqserialnum
= 0;
1285 copyin_ok
= kdp_copyin_word(task
, dqserialnumaddr
, &dqserialnum
, FALSE
, NULL
);
1287 cur_thread_snap
->ths_ss_flags
|= kHasDispatchSerial
;
1288 cur_thread_snap
->ths_dqserialnum
= dqserialnum
;
1294 tval
= safe_grab_timer_value(&thread
->user_timer
);
1295 cur_thread_snap
->ths_user_time
= tval
;
1296 tval
= safe_grab_timer_value(&thread
->system_timer
);
1298 if (thread
->precise_user_kernel_time
) {
1299 cur_thread_snap
->ths_sys_time
= tval
;
1301 cur_thread_snap
->ths_user_time
+= tval
;
1302 cur_thread_snap
->ths_sys_time
= 0;
1305 cur_thread_snap
->ths_ss_flags
= 0;
1306 if (thread
->thread_tag
& THREAD_TAG_MAINTHREAD
)
1307 cur_thread_snap
->ths_ss_flags
|= kThreadMain
;
1308 if (thread
->effective_policy
.thep_darwinbg
)
1309 cur_thread_snap
->ths_ss_flags
|= kThreadDarwinBG
;
1310 if (proc_get_effective_thread_policy(thread
, TASK_POLICY_PASSIVE_IO
))
1311 cur_thread_snap
->ths_ss_flags
|= kThreadIOPassive
;
1312 if (thread
->suspend_count
> 0)
1313 cur_thread_snap
->ths_ss_flags
|= kThreadSuspended
;
1314 if (thread
->options
& TH_OPT_GLOBAL_FORCED_IDLE
)
1315 cur_thread_snap
->ths_ss_flags
|= kGlobalForcedIdle
;
1317 cur_thread_snap
->ths_ss_flags
|= kThreadOnCore
;
1318 if (stackshot_thread_is_idle_worker_unsafe(thread
))
1319 cur_thread_snap
->ths_ss_flags
|= kThreadIdleWorker
;
1321 /* make sure state flags defined in kcdata.h still match internal flags */
1322 static_assert(SS_TH_WAIT
== TH_WAIT
);
1323 static_assert(SS_TH_SUSP
== TH_SUSP
);
1324 static_assert(SS_TH_RUN
== TH_RUN
);
1325 static_assert(SS_TH_UNINT
== TH_UNINT
);
1326 static_assert(SS_TH_TERMINATE
== TH_TERMINATE
);
1327 static_assert(SS_TH_TERMINATE2
== TH_TERMINATE2
);
1328 static_assert(SS_TH_IDLE
== TH_IDLE
);
1330 cur_thread_snap
->ths_last_run_time
= thread
->last_run_time
;
1331 cur_thread_snap
->ths_last_made_runnable_time
= thread
->last_made_runnable_time
;
1332 cur_thread_snap
->ths_state
= thread
->state
;
1333 cur_thread_snap
->ths_sched_flags
= thread
->sched_flags
;
1334 cur_thread_snap
->ths_base_priority
= thread
->base_pri
;
1335 cur_thread_snap
->ths_sched_priority
= thread
->sched_pri
;
1336 cur_thread_snap
->ths_eqos
= thread
->effective_policy
.thep_qos
;
1337 cur_thread_snap
->ths_rqos
= thread
->requested_policy
.thrp_qos
;
1338 cur_thread_snap
->ths_rqos_override
= thread
->requested_policy
.thrp_qos_override
;
1339 cur_thread_snap
->ths_io_tier
= proc_get_effective_thread_policy(thread
, TASK_POLICY_IO
);
1340 cur_thread_snap
->ths_thread_t
= VM_KERNEL_UNSLIDE_OR_PERM(thread
);
1342 static_assert(sizeof(thread
->effective_policy
) == sizeof(uint64_t));
1343 static_assert(sizeof(thread
->requested_policy
) == sizeof(uint64_t));
1344 cur_thread_snap
->ths_requested_policy
= *(unaligned_u64
*) &thread
->requested_policy
;
1345 cur_thread_snap
->ths_effective_policy
= *(unaligned_u64
*) &thread
->effective_policy
;
1347 /* if there is thread name then add to buffer */
1348 cur_thread_name
[0] = '\0';
1349 proc_threadname_kdp(thread
->uthread
, cur_thread_name
, STACKSHOT_MAX_THREAD_NAME_SIZE
);
1350 if (strnlen(cur_thread_name
, STACKSHOT_MAX_THREAD_NAME_SIZE
) > 0) {
1351 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_THREAD_NAME
, sizeof(cur_thread_name
), &out_addr
));
1352 stackshot_memcpy((void *)out_addr
, (void *)cur_thread_name
, sizeof(cur_thread_name
));
1355 /* record system and user cpu times */
1356 time_value_t user_time
;
1357 time_value_t system_time
;
1358 thread_read_times(thread
, &user_time
, &system_time
);
1359 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_CPU_TIMES
, sizeof(struct stackshot_cpu_times
), &out_addr
));
1360 struct stackshot_cpu_times
* stackshot_cpu_times
= (struct stackshot_cpu_times
*)out_addr
;
1361 stackshot_cpu_times
->user_usec
= ((uint64_t)user_time
.seconds
) * USEC_PER_SEC
+ user_time
.microseconds
;
1362 stackshot_cpu_times
->system_usec
= ((uint64_t)system_time
.seconds
) * USEC_PER_SEC
+ system_time
.microseconds
;
1364 /* Trace user stack, if any */
1365 if (!active_kthreads_only_p
&& task
->active
&& thread
->task
->map
!= kernel_map
) {
1366 uint32_t thread_snapshot_flags
= 0;
1369 out_addr
= (mach_vm_address_t
)kcd_end_address(kcd
);
1370 saved_count
= machine_trace_thread64(thread
, (char *)out_addr
, (char *)kcd_max_address(kcd
), MAX_FRAMES
, TRUE
,
1371 trace_fp_p
, &thread_snapshot_flags
);
1372 if (saved_count
> 0) {
1373 int frame_size
= trace_fp_p
? sizeof(struct stack_snapshot_frame64
) : sizeof(uint64_t);
1374 kcd_exit_on_error(kcdata_get_memory_addr_for_array(kcd
, trace_fp_p
? STACKSHOT_KCTYPE_USER_STACKFRAME64
1375 : STACKSHOT_KCTYPE_USER_STACKLR64
,
1376 frame_size
, saved_count
/ frame_size
, &out_addr
));
1377 cur_thread_snap
->ths_ss_flags
|= kUser64_p
;
1380 out_addr
= (mach_vm_address_t
)kcd_end_address(kcd
);
1381 saved_count
= machine_trace_thread(thread
, (char *)out_addr
, (char *)kcd_max_address(kcd
), MAX_FRAMES
, TRUE
, trace_fp_p
,
1382 &thread_snapshot_flags
);
1383 if (saved_count
> 0) {
1384 int frame_size
= trace_fp_p
? sizeof(struct stack_snapshot_frame32
) : sizeof(uint32_t);
1385 kcd_exit_on_error(kcdata_get_memory_addr_for_array(kcd
, trace_fp_p
? STACKSHOT_KCTYPE_USER_STACKFRAME
1386 : STACKSHOT_KCTYPE_USER_STACKLR
,
1387 frame_size
, saved_count
/ frame_size
, &out_addr
));
1391 if (thread_snapshot_flags
!= 0) {
1392 cur_thread_snap
->ths_ss_flags
|= thread_snapshot_flags
;
1396 /* Call through to the machine specific trace routines
1397 * Frames are added past the snapshot header.
1399 if (thread
->kernel_stack
!= 0) {
1400 uint32_t thread_snapshot_flags
= 0;
1401 #if defined(__LP64__)
1402 out_addr
= (mach_vm_address_t
)kcd_end_address(kcd
);
1403 saved_count
= machine_trace_thread64(thread
, (char *)out_addr
, (char *)kcd_max_address(kcd
), MAX_FRAMES
, FALSE
, trace_fp_p
,
1404 &thread_snapshot_flags
);
1405 if (saved_count
> 0) {
1406 int frame_size
= trace_fp_p
? sizeof(struct stack_snapshot_frame64
) : sizeof(uint64_t);
1407 cur_thread_snap
->ths_ss_flags
|= kKernel64_p
;
1408 kcd_exit_on_error(kcdata_get_memory_addr_for_array(kcd
, trace_fp_p
? STACKSHOT_KCTYPE_KERN_STACKFRAME64
1409 : STACKSHOT_KCTYPE_KERN_STACKLR64
,
1410 frame_size
, saved_count
/ frame_size
, &out_addr
));
1413 out_addr
= (mach_vm_address_t
)kcd_end_address(kcd
);
1414 saved_count
= machine_trace_thread(thread
, (char *)out_addr
, (char *)kcd_max_address(kcd
), MAX_FRAMES
, FALSE
, trace_fp_p
,
1415 &thread_snapshot_flags
);
1416 if (saved_count
> 0) {
1417 int frame_size
= trace_fp_p
? sizeof(struct stack_snapshot_frame32
) : sizeof(uint32_t);
1419 kcdata_get_memory_addr_for_array(kcd
, trace_fp_p
? STACKSHOT_KCTYPE_KERN_STACKFRAME
: STACKSHOT_KCTYPE_KERN_STACKLR
,
1420 frame_size
, saved_count
/ frame_size
, &out_addr
));
1423 if (thread_snapshot_flags
!= 0) {
1424 cur_thread_snap
->ths_ss_flags
|= thread_snapshot_flags
;
1429 if (collect_iostats
) {
1430 kcd_exit_on_error(kcdata_record_thread_iostats(kcd
, thread
));
1434 if (collect_instrs_cycles
) {
1435 uint64_t instrs
= 0, cycles
= 0;
1436 mt_stackshot_thread(thread
, &instrs
, &cycles
);
1438 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_INSTRS_CYCLES
, sizeof(struct instrs_cycles_snapshot
), &out_addr
));
1439 struct instrs_cycles_snapshot
*instrs_cycles
= (struct instrs_cycles_snapshot
*)out_addr
;
1440 instrs_cycles
->ics_instructions
= instrs
;
1441 instrs_cycles
->ics_cycles
= cycles
;
1443 #endif /* MONOTONIC */
1450 kcdata_record_thread_delta_snapshot(struct thread_delta_snapshot_v2
* cur_thread_snap
, thread_t thread
, boolean_t thread_on_core
)
1452 cur_thread_snap
->tds_thread_id
= thread_tid(thread
);
1453 if (IPC_VOUCHER_NULL
!= thread
->ith_voucher
)
1454 cur_thread_snap
->tds_voucher_identifier
= VM_KERNEL_ADDRPERM(thread
->ith_voucher
);
1456 cur_thread_snap
->tds_voucher_identifier
= 0;
1458 cur_thread_snap
->tds_ss_flags
= 0;
1459 if (thread
->effective_policy
.thep_darwinbg
)
1460 cur_thread_snap
->tds_ss_flags
|= kThreadDarwinBG
;
1461 if (proc_get_effective_thread_policy(thread
, TASK_POLICY_PASSIVE_IO
))
1462 cur_thread_snap
->tds_ss_flags
|= kThreadIOPassive
;
1463 if (thread
->suspend_count
> 0)
1464 cur_thread_snap
->tds_ss_flags
|= kThreadSuspended
;
1465 if (thread
->options
& TH_OPT_GLOBAL_FORCED_IDLE
)
1466 cur_thread_snap
->tds_ss_flags
|= kGlobalForcedIdle
;
1468 cur_thread_snap
->tds_ss_flags
|= kThreadOnCore
;
1469 if (stackshot_thread_is_idle_worker_unsafe(thread
))
1470 cur_thread_snap
->tds_ss_flags
|= kThreadIdleWorker
;
1472 cur_thread_snap
->tds_last_made_runnable_time
= thread
->last_made_runnable_time
;
1473 cur_thread_snap
->tds_state
= thread
->state
;
1474 cur_thread_snap
->tds_sched_flags
= thread
->sched_flags
;
1475 cur_thread_snap
->tds_base_priority
= thread
->base_pri
;
1476 cur_thread_snap
->tds_sched_priority
= thread
->sched_pri
;
1477 cur_thread_snap
->tds_eqos
= thread
->effective_policy
.thep_qos
;
1478 cur_thread_snap
->tds_rqos
= thread
->requested_policy
.thrp_qos
;
1479 cur_thread_snap
->tds_rqos_override
= thread
->requested_policy
.thrp_qos_override
;
1480 cur_thread_snap
->tds_io_tier
= proc_get_effective_thread_policy(thread
, TASK_POLICY_IO
);
1486 * Why 12? 12 strikes a decent balance between allocating a large array on
1487 * the stack and having large kcdata item overheads for recording nonrunable
1490 #define UNIQUEIDSPERFLUSH 12
1492 struct saved_uniqueids
{
1493 uint64_t ids
[UNIQUEIDSPERFLUSH
];
1497 static kern_return_t
1498 flush_nonrunnable_tasks(struct saved_uniqueids
* ids
)
1500 if (ids
->count
== 0)
1501 return KERN_SUCCESS
;
1502 mach_vm_address_t out_addr
= 0;
1503 kern_return_t ret
= kcdata_get_memory_addr_for_array(stackshot_kcdata_p
, STACKSHOT_KCTYPE_NONRUNNABLE_TASKS
, sizeof(uint64_t),
1504 ids
->count
, &out_addr
);
1505 if (ret
!= KERN_SUCCESS
) {
1508 stackshot_memcpy((void *)out_addr
, ids
->ids
, sizeof(uint64_t) * ids
->count
);
1513 static kern_return_t
1514 handle_nonrunnable_task(struct saved_uniqueids
* ids
, uint64_t pid
)
1516 kern_return_t ret
= KERN_SUCCESS
;
1517 ids
->ids
[ids
->count
] = pid
;
1519 assert(ids
->count
<= UNIQUEIDSPERFLUSH
);
1520 if (ids
->count
== UNIQUEIDSPERFLUSH
)
1521 ret
= flush_nonrunnable_tasks(ids
);
1525 enum thread_classification
{
1526 tc_full_snapshot
, /* take a full snapshot */
1527 tc_delta_snapshot
, /* take a delta snapshot */
1528 tc_nonrunnable
, /* only report id */
1531 static enum thread_classification
1532 classify_thread(thread_t thread
, boolean_t
* thread_on_core_p
, uint32_t trace_flags
)
1534 boolean_t collect_delta_stackshot
= ((trace_flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
) != 0);
1535 boolean_t minimize_nonrunnables
= ((trace_flags
& STACKSHOT_TAILSPIN
) != 0);
1537 processor_t last_processor
= thread
->last_processor
;
1539 boolean_t thread_on_core
=
1540 (last_processor
!= PROCESSOR_NULL
&& last_processor
->state
== PROCESSOR_RUNNING
&& last_processor
->active_thread
== thread
);
1542 *thread_on_core_p
= thread_on_core
;
1544 /* Capture the full thread snapshot if this is not a delta stackshot or if the thread has run subsequent to the
1545 * previous full stackshot */
1546 if (!collect_delta_stackshot
|| thread_on_core
|| (thread
->last_run_time
> stack_snapshot_delta_since_timestamp
)) {
1547 return tc_full_snapshot
;
1549 if (minimize_nonrunnables
&& !(thread
->state
& TH_RUN
)) {
1550 return tc_nonrunnable
;
1552 return tc_delta_snapshot
;
1557 static kern_return_t
1558 kdp_stackshot_kcdata_format(int pid
, uint32_t trace_flags
, uint32_t * pBytesTraced
)
1560 kern_return_t error
= KERN_SUCCESS
;
1561 mach_vm_address_t out_addr
= 0;
1562 uint64_t abs_time
= 0, abs_time_end
= 0;
1563 uint64_t *abs_time_addr
= NULL
;
1564 uint64_t system_state_flags
= 0;
1565 int saved_count
= 0;
1566 task_t task
= TASK_NULL
;
1567 thread_t thread
= THREAD_NULL
;
1568 mach_timebase_info_data_t timebase
= {0, 0};
1569 uint32_t length_to_copy
= 0, tmp32
= 0;
1571 abs_time
= mach_absolute_time();
1573 /* process the flags */
1574 boolean_t active_kthreads_only_p
= ((trace_flags
& STACKSHOT_ACTIVE_KERNEL_THREADS_ONLY
) != 0);
1575 boolean_t save_donating_pids_p
= ((trace_flags
& STACKSHOT_SAVE_IMP_DONATION_PIDS
) != 0);
1576 boolean_t collect_delta_stackshot
= ((trace_flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
) != 0);
1577 boolean_t minimize_nonrunnables
= ((trace_flags
& STACKSHOT_TAILSPIN
) != 0);
1578 boolean_t use_fault_path
= ((trace_flags
& (STACKSHOT_ENABLE_UUID_FAULTING
| STACKSHOT_ENABLE_BT_FAULTING
)) != 0);
1579 boolean_t save_owner_info
= ((trace_flags
& STACKSHOT_THREAD_WAITINFO
) != 0);
1580 stack_enable_faulting
= (trace_flags
& (STACKSHOT_ENABLE_BT_FAULTING
));
1583 /* KEXTs can't be described by just a base address on embedded */
1584 trace_flags
&= ~(STACKSHOT_SAVE_KEXT_LOADINFO
);
1587 struct saved_uniqueids saved_uniqueids
= {.count
= 0};
1589 if (use_fault_path
) {
1590 fault_stats
.sfs_pages_faulted_in
= 0;
1591 fault_stats
.sfs_time_spent_faulting
= 0;
1592 fault_stats
.sfs_stopped_faulting
= (uint8_t) FALSE
;
1595 if (sizeof(void *) == 8)
1596 system_state_flags
|= kKernel64_p
;
1598 if (stackshot_kcdata_p
== NULL
|| pBytesTraced
== NULL
) {
1599 error
= KERN_INVALID_ARGUMENT
;
1603 /* setup mach_absolute_time and timebase info -- copy out in some cases and needed to convert since_timestamp to seconds for proc start time */
1604 clock_timebase_info(&timebase
);
1606 /* begin saving data into the buffer */
1608 kcd_exit_on_error(kcdata_add_uint32_with_description(stackshot_kcdata_p
, trace_flags
, "stackshot_in_flags"));
1609 kcd_exit_on_error(kcdata_add_uint32_with_description(stackshot_kcdata_p
, (uint32_t)pid
, "stackshot_in_pid"));
1610 kcd_exit_on_error(kcdata_add_uint64_with_description(stackshot_kcdata_p
, system_state_flags
, "system_state_flags"));
1613 tmp32
= memorystatus_get_pressure_status_kdp();
1614 kcd_exit_on_error(kcdata_get_memory_addr(stackshot_kcdata_p
, STACKSHOT_KCTYPE_JETSAM_LEVEL
, sizeof(uint32_t), &out_addr
));
1615 stackshot_memcpy((void *)out_addr
, &tmp32
, sizeof(tmp32
));
1618 if (!collect_delta_stackshot
) {
1619 tmp32
= THREAD_POLICY_INTERNAL_STRUCT_VERSION
;
1620 kcd_exit_on_error(kcdata_get_memory_addr(stackshot_kcdata_p
, STACKSHOT_KCTYPE_THREAD_POLICY_VERSION
, sizeof(uint32_t), &out_addr
));
1621 stackshot_memcpy((void *)out_addr
, &tmp32
, sizeof(tmp32
));
1624 kcd_exit_on_error(kcdata_get_memory_addr(stackshot_kcdata_p
, STACKSHOT_KCTYPE_KERN_PAGE_SIZE
, sizeof(uint32_t), &out_addr
));
1625 stackshot_memcpy((void *)out_addr
, &tmp32
, sizeof(tmp32
));
1627 /* save boot-args and osversion string */
1628 length_to_copy
= MIN((uint32_t)(strlen(version
) + 1), OSVERSIZE
);
1629 kcd_exit_on_error(kcdata_get_memory_addr(stackshot_kcdata_p
, STACKSHOT_KCTYPE_OSVERSION
, length_to_copy
, &out_addr
));
1630 stackshot_strlcpy((char*)out_addr
, &version
[0], length_to_copy
);
1632 length_to_copy
= MIN((uint32_t)(strlen(PE_boot_args()) + 1), OSVERSIZE
);
1633 kcd_exit_on_error(kcdata_get_memory_addr(stackshot_kcdata_p
, STACKSHOT_KCTYPE_BOOTARGS
, length_to_copy
, &out_addr
));
1634 stackshot_strlcpy((char*)out_addr
, PE_boot_args(), length_to_copy
);
1636 kcd_exit_on_error(kcdata_get_memory_addr(stackshot_kcdata_p
, KCDATA_TYPE_TIMEBASE
, sizeof(timebase
), &out_addr
));
1637 stackshot_memcpy((void *)out_addr
, &timebase
, sizeof(timebase
));
1639 kcd_exit_on_error(kcdata_get_memory_addr(stackshot_kcdata_p
, STACKSHOT_KCTYPE_DELTA_SINCE_TIMESTAMP
, sizeof(uint64_t), &out_addr
));
1640 stackshot_memcpy((void*)out_addr
, &stack_snapshot_delta_since_timestamp
, sizeof(stack_snapshot_delta_since_timestamp
));
1643 kcd_exit_on_error(kcdata_get_memory_addr(stackshot_kcdata_p
, KCDATA_TYPE_MACH_ABSOLUTE_TIME
, sizeof(uint64_t), &out_addr
));
1644 abs_time_addr
= (uint64_t *)out_addr
;
1645 stackshot_memcpy((void *)abs_time_addr
, &abs_time
, sizeof(uint64_t));
1647 kcd_exit_on_error(kcdata_get_memory_addr(stackshot_kcdata_p
, KCDATA_TYPE_USECS_SINCE_EPOCH
, sizeof(uint64_t), &out_addr
));
1648 stackshot_memcpy((void *)out_addr
, &stackshot_microsecs
, sizeof(uint64_t));
1650 /* reserve space of system level shared cache load info */
1651 struct dyld_uuid_info_64_v2
* sys_shared_cache_loadinfo
= NULL
;
1652 if (!collect_delta_stackshot
) {
1653 kcd_exit_on_error(kcdata_get_memory_addr(stackshot_kcdata_p
, STACKSHOT_KCTYPE_SHAREDCACHE_LOADINFO
,
1654 sizeof(struct dyld_uuid_info_64_v2
), &out_addr
));
1655 sys_shared_cache_loadinfo
= (struct dyld_uuid_info_64_v2
*)out_addr
;
1656 bzero((void *)sys_shared_cache_loadinfo
, sizeof(struct dyld_uuid_info_64_v2
));
1659 /* Add requested information first */
1660 if (trace_flags
& STACKSHOT_GET_GLOBAL_MEM_STATS
) {
1661 kcd_exit_on_error(kcdata_get_memory_addr(stackshot_kcdata_p
, STACKSHOT_KCTYPE_GLOBAL_MEM_STATS
, sizeof(struct mem_and_io_snapshot
), &out_addr
));
1662 kdp_mem_and_io_snapshot((struct mem_and_io_snapshot
*)out_addr
);
1665 #if CONFIG_COALITIONS
1666 int num_coalitions
= 0;
1667 struct jetsam_coalition_snapshot
*coalitions
= NULL
;
1668 /* Iterate over coalitions */
1669 if (trace_flags
& STACKSHOT_SAVE_JETSAM_COALITIONS
) {
1670 if (coalition_iterate_stackshot(stackshot_coalition_jetsam_count
, &num_coalitions
, COALITION_TYPE_JETSAM
) != KERN_SUCCESS
) {
1671 trace_flags
&= ~(STACKSHOT_SAVE_JETSAM_COALITIONS
);
1674 if (trace_flags
& STACKSHOT_SAVE_JETSAM_COALITIONS
) {
1675 if (num_coalitions
> 0) {
1676 kcd_exit_on_error(kcdata_get_memory_addr_for_array(stackshot_kcdata_p
, STACKSHOT_KCTYPE_JETSAM_COALITION_SNAPSHOT
, sizeof(struct jetsam_coalition_snapshot
), num_coalitions
, &out_addr
));
1677 coalitions
= (struct jetsam_coalition_snapshot
*)out_addr
;
1680 if (coalition_iterate_stackshot(stackshot_coalition_jetsam_snapshot
, coalitions
, COALITION_TYPE_JETSAM
) != KERN_SUCCESS
) {
1681 error
= KERN_FAILURE
;
1687 trace_flags
&= ~(STACKSHOT_SAVE_JETSAM_COALITIONS
);
1688 #endif /* CONFIG_COALITIONS */
1690 trace_flags
&= ~(STACKSHOT_THREAD_GROUP
);
1692 /* Iterate over tasks */
1693 queue_head_t
*task_list
= &tasks
;
1694 queue_iterate(task_list
, task
, task_t
, tasks
) {
1696 uint64_t task_uniqueid
= 0;
1697 int num_delta_thread_snapshots
= 0;
1698 int num_nonrunnable_threads
= 0;
1699 int num_waitinfo_threads
= 0;
1701 uint64_t task_start_abstime
= 0;
1702 boolean_t task_delta_stackshot
= FALSE
;
1703 boolean_t task64
= FALSE
, have_map
= FALSE
, have_pmap
= FALSE
;
1704 boolean_t some_thread_ran
= FALSE
;
1705 unaligned_u64
*task_snap_ss_flags
= NULL
;
1707 if ((task
== NULL
) || !ml_validate_nofault((vm_offset_t
)task
, sizeof(struct task
))) {
1708 error
= KERN_FAILURE
;
1712 have_map
= (task
->map
!= NULL
) && (ml_validate_nofault((vm_offset_t
)(task
->map
), sizeof(struct _vm_map
)));
1713 have_pmap
= have_map
&& (task
->map
->pmap
!= NULL
) && (ml_validate_nofault((vm_offset_t
)(task
->map
->pmap
), sizeof(struct pmap
)));
1715 task_pid
= pid_from_task(task
);
1716 task_uniqueid
= get_task_uniqueid(task
);
1717 task64
= task_has_64BitAddr(task
);
1719 if (!task
->active
|| task_is_a_corpse(task
)) {
1721 * Not interested in terminated tasks without threads, and
1722 * at the moment, stackshot can't handle a task without a name.
1724 if (queue_empty(&task
->threads
) || task_pid
== -1) {
1729 if (collect_delta_stackshot
) {
1730 proc_starttime_kdp(task
->bsd_info
, NULL
, NULL
, &task_start_abstime
);
1733 /* Trace everything, unless a process was specified */
1734 if ((pid
== -1) || (pid
== task_pid
)) {
1735 #if DEBUG || DEVELOPMENT
1736 /* we might want to call kcdata_undo_add_container_begin(), which is
1737 * only safe if we call it after kcdata_add_container_marker() but
1738 * before adding any other kcdata items. In development kernels,
1739 * we'll remember where the buffer end was and confirm after calling
1740 * kcdata_undo_add_container_begin() that it's in exactly the same
1742 mach_vm_address_t revert_addr
= stackshot_kcdata_p
->kcd_addr_end
;
1745 /* add task snapshot marker */
1746 kcd_exit_on_error(kcdata_add_container_marker(stackshot_kcdata_p
, KCDATA_TYPE_CONTAINER_BEGIN
,
1747 STACKSHOT_KCCONTAINER_TASK
, task_uniqueid
));
1749 if (!collect_delta_stackshot
|| (task_start_abstime
== 0) ||
1750 (task_start_abstime
> stack_snapshot_delta_since_timestamp
)) {
1751 kcd_exit_on_error(kcdata_record_task_snapshot(stackshot_kcdata_p
, task
, trace_flags
, have_pmap
, &task_snap_ss_flags
));
1753 task_delta_stackshot
= TRUE
;
1754 if (minimize_nonrunnables
) {
1755 // delay taking the task snapshot. If there are no runnable threads we'll skip it.
1757 kcd_exit_on_error(kcdata_record_task_delta_snapshot(stackshot_kcdata_p
, task
, have_pmap
, &task_snap_ss_flags
));
1761 /* Iterate over task threads */
1762 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
)
1764 uint64_t thread_uniqueid
;
1766 if ((thread
== NULL
) || !ml_validate_nofault((vm_offset_t
)thread
, sizeof(struct thread
))) {
1767 error
= KERN_FAILURE
;
1771 if (active_kthreads_only_p
&& thread
->kernel_stack
== 0)
1774 thread_uniqueid
= thread_tid(thread
);
1776 boolean_t thread_on_core
;
1777 enum thread_classification thread_classification
= classify_thread(thread
, &thread_on_core
, trace_flags
);
1779 switch (thread_classification
) {
1780 case tc_full_snapshot
:
1781 /* add thread marker */
1782 kcd_exit_on_error(kcdata_add_container_marker(stackshot_kcdata_p
, KCDATA_TYPE_CONTAINER_BEGIN
,
1783 STACKSHOT_KCCONTAINER_THREAD
, thread_uniqueid
));
1785 kcdata_record_thread_snapshot(stackshot_kcdata_p
, thread
, task
, trace_flags
, have_pmap
, thread_on_core
));
1787 /* mark end of thread snapshot data */
1788 kcd_exit_on_error(kcdata_add_container_marker(stackshot_kcdata_p
, KCDATA_TYPE_CONTAINER_END
,
1789 STACKSHOT_KCCONTAINER_THREAD
, thread_uniqueid
));
1791 some_thread_ran
= TRUE
;
1794 case tc_delta_snapshot
:
1795 num_delta_thread_snapshots
++;
1798 case tc_nonrunnable
:
1799 num_nonrunnable_threads
++;
1803 /* We want to report owner information regardless of whether a thread
1804 * has changed since the last delta, whether it's a normal stackshot,
1805 * or whether it's nonrunnable */
1806 if (save_owner_info
&& stackshot_thread_has_valid_waitinfo(thread
))
1807 num_waitinfo_threads
++;
1810 if (task_delta_stackshot
&& minimize_nonrunnables
) {
1811 if (some_thread_ran
|| num_delta_thread_snapshots
> 0) {
1812 kcd_exit_on_error(kcdata_record_task_delta_snapshot(stackshot_kcdata_p
, task
, have_pmap
, &task_snap_ss_flags
));
1814 kcd_exit_on_error(kcdata_undo_add_container_begin(stackshot_kcdata_p
));
1816 #if DEBUG || DEVELOPMENT
1817 mach_vm_address_t undo_addr
= stackshot_kcdata_p
->kcd_addr_end
;
1818 if (revert_addr
!= undo_addr
) {
1819 panic("tried to revert a container begin but we already moved past it. revert=%p undo=%p",
1820 (void *)revert_addr
, (void *)undo_addr
);
1823 kcd_exit_on_error(handle_nonrunnable_task(&saved_uniqueids
, task_uniqueid
));
1828 struct thread_delta_snapshot_v2
* delta_snapshots
= NULL
;
1829 int current_delta_snapshot_index
= 0;
1831 if (num_delta_thread_snapshots
> 0) {
1832 kcd_exit_on_error(kcdata_get_memory_addr_for_array(stackshot_kcdata_p
, STACKSHOT_KCTYPE_THREAD_DELTA_SNAPSHOT
,
1833 sizeof(struct thread_delta_snapshot_v2
),
1834 num_delta_thread_snapshots
, &out_addr
));
1835 delta_snapshots
= (struct thread_delta_snapshot_v2
*)out_addr
;
1838 uint64_t * nonrunnable_tids
= NULL
;
1839 int current_nonrunnable_index
= 0;
1841 if (num_nonrunnable_threads
> 0) {
1842 kcd_exit_on_error(kcdata_get_memory_addr_for_array(stackshot_kcdata_p
, STACKSHOT_KCTYPE_NONRUNNABLE_TIDS
,
1843 sizeof(uint64_t), num_nonrunnable_threads
, &out_addr
));
1844 nonrunnable_tids
= (uint64_t *)out_addr
;
1847 thread_waitinfo_t
*thread_waitinfo
= NULL
;
1848 int current_waitinfo_index
= 0;
1850 if (num_waitinfo_threads
> 0) {
1851 kcd_exit_on_error(kcdata_get_memory_addr_for_array(stackshot_kcdata_p
, STACKSHOT_KCTYPE_THREAD_WAITINFO
,
1852 sizeof(thread_waitinfo_t
), num_waitinfo_threads
, &out_addr
));
1853 thread_waitinfo
= (thread_waitinfo_t
*)out_addr
;
1856 if (num_delta_thread_snapshots
> 0 || num_nonrunnable_threads
> 0 || num_waitinfo_threads
> 0) {
1857 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
)
1859 if (active_kthreads_only_p
&& thread
->kernel_stack
== 0)
1862 /* If we want owner info, we should capture it regardless of its classification */
1863 if (save_owner_info
&& stackshot_thread_has_valid_waitinfo(thread
)) {
1864 stackshot_thread_wait_owner_info(
1866 &thread_waitinfo
[current_waitinfo_index
++]);
1869 boolean_t thread_on_core
;
1870 enum thread_classification thread_classification
= classify_thread(thread
, &thread_on_core
, trace_flags
);
1872 switch (thread_classification
) {
1873 case tc_full_snapshot
:
1874 /* full thread snapshot captured above */
1877 case tc_delta_snapshot
:
1878 kcd_exit_on_error(kcdata_record_thread_delta_snapshot(&delta_snapshots
[current_delta_snapshot_index
++],
1879 thread
, thread_on_core
));
1882 case tc_nonrunnable
:
1883 nonrunnable_tids
[current_nonrunnable_index
++] = thread_tid(thread
);
1888 #if DEBUG || DEVELOPMENT
1889 if (current_delta_snapshot_index
!= num_delta_thread_snapshots
) {
1890 panic("delta thread snapshot count mismatch while capturing snapshots for task %p. expected %d, found %d", task
,
1891 num_delta_thread_snapshots
, current_delta_snapshot_index
);
1893 if (current_nonrunnable_index
!= num_nonrunnable_threads
) {
1894 panic("nonrunnable thread count mismatch while capturing snapshots for task %p. expected %d, found %d", task
,
1895 num_nonrunnable_threads
, current_nonrunnable_index
);
1897 if (current_waitinfo_index
!= num_waitinfo_threads
) {
1898 panic("thread wait info count mismatch while capturing snapshots for task %p. expected %d, found %d", task
,
1899 num_waitinfo_threads
, current_waitinfo_index
);
1904 #if IMPORTANCE_INHERITANCE
1905 if (save_donating_pids_p
) {
1907 ((((mach_vm_address_t
)kcd_end_address(stackshot_kcdata_p
) + (TASK_IMP_WALK_LIMIT
* sizeof(int32_t))) <
1908 (mach_vm_address_t
)kcd_max_address(stackshot_kcdata_p
))
1910 : KERN_RESOURCE_SHORTAGE
));
1911 saved_count
= task_importance_list_pids(task
, TASK_IMP_LIST_DONATING_PIDS
,
1912 (void *)kcd_end_address(stackshot_kcdata_p
), TASK_IMP_WALK_LIMIT
);
1913 if (saved_count
> 0)
1914 kcd_exit_on_error(kcdata_get_memory_addr_for_array(stackshot_kcdata_p
, STACKSHOT_KCTYPE_DONATING_PIDS
,
1915 sizeof(int32_t), saved_count
, &out_addr
));
1919 if (!collect_delta_stackshot
|| (num_delta_thread_snapshots
!= task
->thread_count
) || !task_delta_stackshot
) {
1921 * Collect shared cache info and UUID info in these scenarios
1922 * 1) a full stackshot
1923 * 2) a delta stackshot where the task started after the previous full stackshot OR
1924 * any thread from the task has run since the previous full stackshot
1927 kcd_exit_on_error(kcdata_record_shared_cache_info(stackshot_kcdata_p
, task
, sys_shared_cache_loadinfo
, task_snap_ss_flags
));
1928 kcd_exit_on_error(kcdata_record_uuid_info(stackshot_kcdata_p
, task
, trace_flags
, have_pmap
, task_snap_ss_flags
));
1930 /* mark end of task snapshot data */
1931 kcd_exit_on_error(kcdata_add_container_marker(stackshot_kcdata_p
, KCDATA_TYPE_CONTAINER_END
, STACKSHOT_KCCONTAINER_TASK
,
1936 if (minimize_nonrunnables
) {
1937 flush_nonrunnable_tasks(&saved_uniqueids
);
1940 if (use_fault_path
) {
1941 kcd_exit_on_error(kcdata_get_memory_addr(stackshot_kcdata_p
, STACKSHOT_KCTYPE_STACKSHOT_FAULT_STATS
,
1942 sizeof(struct stackshot_fault_stats
), &out_addr
));
1943 stackshot_memcpy((void*)out_addr
, &fault_stats
, sizeof(struct stackshot_fault_stats
));
1946 /* update timestamp of the stackshot */
1947 abs_time_end
= mach_absolute_time();
1948 #if DEVELOPMENT || DEBUG
1949 kcd_exit_on_error(kcdata_get_memory_addr(stackshot_kcdata_p
, STACKSHOT_KCTYPE_STACKSHOT_DURATION
,
1950 sizeof(struct stackshot_duration
), &out_addr
));
1951 struct stackshot_duration
* stackshot_duration
= (struct stackshot_duration
*)out_addr
;
1952 stackshot_duration
->stackshot_duration
= (abs_time_end
- abs_time
);
1953 stackshot_duration
->stackshot_duration_outer
= 0;
1954 stackshot_duration_outer
= (unaligned_u64
*)&stackshot_duration
->stackshot_duration_outer
;
1956 stackshot_memcpy((void *)abs_time_addr
, &abs_time_end
, sizeof(uint64_t));
1958 kcd_exit_on_error(kcdata_add_uint32_with_description(stackshot_kcdata_p
, trace_flags
, "stackshot_out_flags"));
1960 kcd_exit_on_error(kcdata_write_buffer_end(stackshot_kcdata_p
));
1962 /* === END of populating stackshot data === */
1964 *pBytesTraced
= (uint32_t) kcdata_memory_get_used_bytes(stackshot_kcdata_p
);
1967 #if INTERRUPT_MASKED_DEBUG
1968 if (!panic_stackshot
) {
1970 * Try to catch instances where stackshot takes too long BEFORE returning from
1973 ml_check_interrupts_disabled_duration(current_thread());
1977 stack_enable_faulting
= FALSE
;
1983 proc_was_throttled_from_task(task_t task
)
1985 uint64_t was_throttled
= 0;
1988 was_throttled
= proc_was_throttled(task
->bsd_info
);
1990 return was_throttled
;
1994 proc_did_throttle_from_task(task_t task
)
1996 uint64_t did_throttle
= 0;
1999 did_throttle
= proc_did_throttle(task
->bsd_info
);
2001 return did_throttle
;
2005 kdp_mem_and_io_snapshot(struct mem_and_io_snapshot
*memio_snap
)
2007 unsigned int pages_reclaimed
;
2008 unsigned int pages_wanted
;
2011 processor_t processor
;
2012 vm_statistics64_t stat
;
2013 vm_statistics64_data_t host_vm_stat
;
2015 processor
= processor_list
;
2016 stat
= &PROCESSOR_DATA(processor
, vm_stat
);
2017 host_vm_stat
= *stat
;
2019 if (processor_count
> 1) {
2021 * processor_list may be in the process of changing as we are
2022 * attempting a stackshot. Ordinarily it will be lock protected,
2023 * but it is not safe to lock in the context of the debugger.
2024 * Fortunately we never remove elements from the processor list,
2025 * and only add to to the end of the list, so we SHOULD be able
2026 * to walk it. If we ever want to truly tear down processors,
2027 * this will have to change.
2029 while ((processor
= processor
->processor_list
) != NULL
) {
2030 stat
= &PROCESSOR_DATA(processor
, vm_stat
);
2031 host_vm_stat
.compressions
+= stat
->compressions
;
2032 host_vm_stat
.decompressions
+= stat
->decompressions
;
2036 memio_snap
->snapshot_magic
= STACKSHOT_MEM_AND_IO_SNAPSHOT_MAGIC
;
2037 memio_snap
->free_pages
= vm_page_free_count
;
2038 memio_snap
->active_pages
= vm_page_active_count
;
2039 memio_snap
->inactive_pages
= vm_page_inactive_count
;
2040 memio_snap
->purgeable_pages
= vm_page_purgeable_count
;
2041 memio_snap
->wired_pages
= vm_page_wire_count
;
2042 memio_snap
->speculative_pages
= vm_page_speculative_count
;
2043 memio_snap
->throttled_pages
= vm_page_throttled_count
;
2044 memio_snap
->busy_buffer_count
= count_busy_buffers();
2045 memio_snap
->filebacked_pages
= vm_page_pageable_external_count
;
2046 memio_snap
->compressions
= (uint32_t)host_vm_stat
.compressions
;
2047 memio_snap
->decompressions
= (uint32_t)host_vm_stat
.decompressions
;
2048 memio_snap
->compressor_size
= VM_PAGE_COMPRESSOR_COUNT
;
2049 kErr
= mach_vm_pressure_monitor(FALSE
, VM_PRESSURE_TIME_WINDOW
, &pages_reclaimed
, &pages_wanted
);
2052 memio_snap
->pages_wanted
= (uint32_t)pages_wanted
;
2053 memio_snap
->pages_reclaimed
= (uint32_t)pages_reclaimed
;
2054 memio_snap
->pages_wanted_reclaimed_valid
= 1;
2056 memio_snap
->pages_wanted
= 0;
2057 memio_snap
->pages_reclaimed
= 0;
2058 memio_snap
->pages_wanted_reclaimed_valid
= 0;
2063 stackshot_memcpy(void *dst
, const void *src
, size_t len
)
2066 if (panic_stackshot
) {
2067 uint8_t *dest_bytes
= (uint8_t *)dst
;
2068 const uint8_t *src_bytes
= (const uint8_t *)src
;
2069 for (size_t i
= 0; i
< len
; i
++) {
2070 dest_bytes
[i
] = src_bytes
[i
];
2074 memcpy(dst
, src
, len
);
2078 stackshot_strlcpy(char *dst
, const char *src
, size_t maxlen
)
2080 const size_t srclen
= strlen(src
);
2082 if (srclen
< maxlen
) {
2083 stackshot_memcpy(dst
, src
, srclen
+1);
2084 } else if (maxlen
!= 0) {
2085 stackshot_memcpy(dst
, src
, maxlen
-1);
2086 dst
[maxlen
-1] = '\0';
2094 * Returns the physical address of the specified map:target address,
2095 * using the kdp fault path if requested and the page is not resident.
2098 kdp_find_phys(vm_map_t map
, vm_offset_t target_addr
, boolean_t try_fault
, uint32_t *kdp_fault_results
)
2100 vm_offset_t cur_phys_addr
;
2101 unsigned cur_wimg_bits
;
2102 uint64_t fault_start_time
= 0;
2104 if (map
== VM_MAP_NULL
) {
2108 cur_phys_addr
= kdp_vtophys(map
->pmap
, target_addr
);
2109 if (!pmap_valid_page((ppnum_t
) atop(cur_phys_addr
))) {
2110 if (!try_fault
|| fault_stats
.sfs_stopped_faulting
) {
2111 if (kdp_fault_results
)
2112 *kdp_fault_results
|= KDP_FAULT_RESULT_PAGED_OUT
;
2118 * The pmap doesn't have a valid page so we start at the top level
2119 * vm map and try a lightweight fault. Update fault path usage stats.
2121 fault_start_time
= mach_absolute_time();
2122 cur_phys_addr
= kdp_lightweight_fault(map
, (target_addr
& ~PAGE_MASK
));
2123 fault_stats
.sfs_time_spent_faulting
+= (mach_absolute_time() - fault_start_time
);
2125 if ((fault_stats
.sfs_time_spent_faulting
>= fault_stats
.sfs_system_max_fault_time
) && !panic_stackshot
) {
2126 fault_stats
.sfs_stopped_faulting
= (uint8_t) TRUE
;
2129 cur_phys_addr
+= (target_addr
& PAGE_MASK
);
2131 if (!pmap_valid_page((ppnum_t
) atop(cur_phys_addr
))) {
2132 if (kdp_fault_results
)
2133 *kdp_fault_results
|= (KDP_FAULT_RESULT_TRIED_FAULT
| KDP_FAULT_RESULT_PAGED_OUT
);
2138 if (kdp_fault_results
)
2139 *kdp_fault_results
|= KDP_FAULT_RESULT_FAULTED_IN
;
2141 fault_stats
.sfs_pages_faulted_in
++;
2144 * This check is done in kdp_lightweight_fault for the fault path.
2146 cur_wimg_bits
= pmap_cache_attributes((ppnum_t
) atop(cur_phys_addr
));
2148 if ((cur_wimg_bits
& VM_WIMG_MASK
) != VM_WIMG_DEFAULT
) {
2153 return cur_phys_addr
;
2158 task_t task
, uint64_t addr
, uint64_t *result
, boolean_t try_fault
, uint32_t *kdp_fault_results
)
2160 if (task_has_64BitAddr(task
)) {
2161 return kdp_copyin(task
->map
, addr
, result
, sizeof(uint64_t), try_fault
, kdp_fault_results
);
2164 boolean_t r
= kdp_copyin(task
->map
, addr
, &buf
, sizeof(uint32_t), try_fault
, kdp_fault_results
);
2171 kdp_copyin(vm_map_t map
, uint64_t uaddr
, void *dest
, size_t size
, boolean_t try_fault
, uint32_t *kdp_fault_results
)
2174 char *kvaddr
= dest
;
2177 /* Identify if destination buffer is in panic storage area */
2178 if (panic_stackshot
&& ((vm_offset_t
)dest
>= gPanicBase
) && ((vm_offset_t
)dest
< (gPanicBase
+ gPanicSize
))) {
2179 if (((vm_offset_t
)dest
+ size
) > (gPanicBase
+ gPanicSize
)) {
2186 uint64_t phys_src
= kdp_find_phys(map
, uaddr
, try_fault
, kdp_fault_results
);
2187 uint64_t phys_dest
= kvtophys((vm_offset_t
)kvaddr
);
2188 uint64_t src_rem
= PAGE_SIZE
- (phys_src
& PAGE_MASK
);
2189 uint64_t dst_rem
= PAGE_SIZE
- (phys_dest
& PAGE_MASK
);
2190 size_t cur_size
= (uint32_t) MIN(src_rem
, dst_rem
);
2191 cur_size
= MIN(cur_size
, rem
);
2193 if (phys_src
&& phys_dest
) {
2196 * On embedded the panic buffer is mapped as device memory and doesn't allow
2197 * unaligned accesses. To prevent these, we copy over bytes individually here.
2199 if (panic_stackshot
)
2200 stackshot_memcpy(kvaddr
, (const void *)phystokv(phys_src
), cur_size
);
2202 #endif /* CONFIG_EMBEDDED */
2203 bcopy_phys(phys_src
, phys_dest
, cur_size
);
2217 do_stackshot(void *context
)
2219 #pragma unused(context)
2222 stack_snapshot_ret
= kdp_stackshot_kcdata_format(stack_snapshot_pid
,
2223 stack_snapshot_flags
,
2224 &stack_snapshot_bytes_traced
);
2227 return stack_snapshot_ret
;
2231 * A fantastical routine that tries to be fast about returning
2232 * translations. Caches the last page we found a translation
2233 * for, so that we can be quick about multiple queries to the
2234 * same page. It turns out this is exactly the workflow
2235 * machine_trace_thread and its relatives tend to throw at us.
2237 * Please zero the nasty global this uses after a bulk lookup;
2238 * this isn't safe across a switch of the map or changes
2241 * This also means that if zero is a valid KVA, we are
2242 * screwed. Sucks to be us. Fortunately, this should never
2246 machine_trace_thread_get_kva(vm_offset_t cur_target_addr
, vm_map_t map
, uint32_t *thread_trace_flags
)
2248 vm_offset_t cur_target_page
;
2249 vm_offset_t cur_phys_addr
;
2250 vm_offset_t kern_virt_target_addr
;
2251 uint32_t kdp_fault_results
= 0;
2253 cur_target_page
= atop(cur_target_addr
);
2255 if ((cur_target_page
!= prev_target_page
) || validate_next_addr
) {
2258 * Alright; it wasn't our previous page. So
2259 * we must validate that there is a page
2260 * table entry for this address under the
2261 * current pmap, and that it has default
2262 * cache attributes (otherwise it may not be
2263 * safe to access it).
2265 cur_phys_addr
= kdp_find_phys(map
, cur_target_addr
, stack_enable_faulting
, &kdp_fault_results
);
2266 if (thread_trace_flags
) {
2267 if (kdp_fault_results
& KDP_FAULT_RESULT_PAGED_OUT
) {
2268 *thread_trace_flags
|= kThreadTruncatedBT
;
2271 if (kdp_fault_results
& KDP_FAULT_RESULT_TRIED_FAULT
) {
2272 *thread_trace_flags
|= kThreadTriedFaultBT
;
2275 if (kdp_fault_results
& KDP_FAULT_RESULT_FAULTED_IN
) {
2276 *thread_trace_flags
|= kThreadFaultedBT
;
2280 if (cur_phys_addr
== 0) {
2284 kern_virt_target_addr
= (vm_offset_t
) PHYSMAP_PTOV(cur_phys_addr
);
2285 #elif __arm__ || __arm64__
2286 kern_virt_target_addr
= phystokv(cur_phys_addr
);
2288 #error Oh come on... we should really unify the physical -> kernel virtual interface
2290 prev_target_page
= cur_target_page
;
2291 prev_target_kva
= (kern_virt_target_addr
& ~PAGE_MASK
);
2292 validate_next_addr
= FALSE
;
2294 /* We found a translation, so stash this page */
2295 kern_virt_target_addr
= prev_target_kva
+ (cur_target_addr
& PAGE_MASK
);
2299 kasan_notify_address(kern_virt_target_addr
, sizeof(uint64_t));
2301 return kern_virt_target_addr
;
2305 machine_trace_thread_clear_validation_cache(void)
2307 validate_next_addr
= TRUE
;
2311 stackshot_thread_is_idle_worker_unsafe(thread_t thread
)
2313 /* When the pthread kext puts a worker thread to sleep, it will
2314 * set kThreadWaitParkedWorkQueue in the block_hint of the thread
2315 * struct. See parkit() in kern/kern_support.c in libpthread.
2317 return (thread
->state
& TH_WAIT
) &&
2318 (thread
->block_hint
== kThreadWaitParkedWorkQueue
);
2321 #if CONFIG_COALITIONS
2323 stackshot_coalition_jetsam_count(void *arg
, int i
, coalition_t coal
)
2325 #pragma unused(i, coal)
2326 unsigned int *coalition_count
= (unsigned int*)arg
;
2327 (*coalition_count
)++;
2331 stackshot_coalition_jetsam_snapshot(void *arg
, int i
, coalition_t coal
)
2333 if (coalition_type(coal
) != COALITION_TYPE_JETSAM
)
2336 struct jetsam_coalition_snapshot
*coalitions
= (struct jetsam_coalition_snapshot
*)arg
;
2337 struct jetsam_coalition_snapshot
*jcs
= &coalitions
[i
];
2338 task_t leader
= TASK_NULL
;
2339 jcs
->jcs_id
= coalition_id(coal
);
2342 if (coalition_term_requested(coal
))
2343 jcs
->jcs_flags
|= kCoalitionTermRequested
;
2344 if (coalition_is_terminated(coal
))
2345 jcs
->jcs_flags
|= kCoalitionTerminated
;
2346 if (coalition_is_reaped(coal
))
2347 jcs
->jcs_flags
|= kCoalitionReaped
;
2348 if (coalition_is_privileged(coal
))
2349 jcs
->jcs_flags
|= kCoalitionPrivileged
;
2352 leader
= kdp_coalition_get_leader(coal
);
2354 jcs
->jcs_leader_task_uniqueid
= get_task_uniqueid(leader
);
2356 jcs
->jcs_leader_task_uniqueid
= 0;
2358 #endif /* CONFIG_COALITIONS */
2361 /* Determine if a thread has waitinfo that stackshot can provide */
2363 stackshot_thread_has_valid_waitinfo(thread_t thread
)
2365 if (!(thread
->state
& TH_WAIT
))
2368 switch (thread
->block_hint
) {
2369 // If set to None or is a parked work queue, ignore it
2370 case kThreadWaitParkedWorkQueue
:
2371 case kThreadWaitNone
:
2373 // There is a short window where the pthread kext removes a thread
2374 // from its ksyn wait queue before waking the thread up
2375 case kThreadWaitPThreadMutex
:
2376 case kThreadWaitPThreadRWLockRead
:
2377 case kThreadWaitPThreadRWLockWrite
:
2378 case kThreadWaitPThreadCondVar
:
2379 return (kdp_pthread_get_thread_kwq(thread
) != NULL
);
2380 // All other cases are valid block hints if in a wait state
2387 stackshot_thread_wait_owner_info(thread_t thread
, thread_waitinfo_t
*waitinfo
)
2389 waitinfo
->waiter
= thread_tid(thread
);
2390 waitinfo
->wait_type
= thread
->block_hint
;
2391 switch (waitinfo
->wait_type
) {
2392 case kThreadWaitKernelMutex
:
2393 kdp_lck_mtx_find_owner(thread
->waitq
, thread
->wait_event
, waitinfo
);
2395 case kThreadWaitPortReceive
:
2396 kdp_mqueue_recv_find_owner(thread
->waitq
, thread
->wait_event
, waitinfo
);
2398 case kThreadWaitPortSend
:
2399 kdp_mqueue_send_find_owner(thread
->waitq
, thread
->wait_event
, waitinfo
);
2401 case kThreadWaitSemaphore
:
2402 kdp_sema_find_owner(thread
->waitq
, thread
->wait_event
, waitinfo
);
2404 case kThreadWaitUserLock
:
2405 kdp_ulock_find_owner(thread
->waitq
, thread
->wait_event
, waitinfo
);
2407 case kThreadWaitKernelRWLockRead
:
2408 case kThreadWaitKernelRWLockWrite
:
2409 case kThreadWaitKernelRWLockUpgrade
:
2410 kdp_rwlck_find_owner(thread
->waitq
, thread
->wait_event
, waitinfo
);
2412 case kThreadWaitPThreadMutex
:
2413 case kThreadWaitPThreadRWLockRead
:
2414 case kThreadWaitPThreadRWLockWrite
:
2415 case kThreadWaitPThreadCondVar
:
2416 kdp_pthread_find_owner(thread
, waitinfo
);
2418 case kThreadWaitWorkloopSyncWait
:
2419 kdp_workloop_sync_wait_find_owner(thread
, thread
->wait_event
, waitinfo
);
2422 waitinfo
->owner
= 0;
2423 waitinfo
->context
= 0;