2 * Copyright (c) 2012-2020 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
28 #include <mach/host_priv.h>
29 #include <mach/host_special_ports.h>
30 #include <mach/mach_types.h>
31 #include <mach/telemetry_notification_server.h>
33 #include <kern/assert.h>
34 #include <kern/clock.h>
35 #include <kern/debug.h>
36 #include <kern/host.h>
37 #include <kern/kalloc.h>
38 #include <kern/kern_types.h>
39 #include <kern/locks.h>
40 #include <kern/misc_protos.h>
41 #include <kern/sched.h>
42 #include <kern/sched_prim.h>
43 #include <kern/telemetry.h>
44 #include <kern/timer_call.h>
45 #include <kern/policy_internal.h>
46 #include <kern/kcdata.h>
48 #include <pexpert/pexpert.h>
50 #include <vm/vm_kern.h>
51 #include <vm/vm_shared_region.h>
53 #include <kperf/callstack.h>
54 #include <kern/backtrace.h>
55 #include <kern/monotonic.h>
57 #include <sys/kdebug.h>
58 #include <uuid/uuid.h>
59 #include <kdp/kdp_dyld.h>
61 #define TELEMETRY_DEBUG 0
64 extern int proc_pid(struct proc
*);
65 extern char *proc_name_address(void *p
);
66 extern uint64_t proc_uniqueid(void *p
);
67 extern uint64_t proc_was_throttled(void *p
);
68 extern uint64_t proc_did_throttle(void *p
);
69 extern int proc_selfpid(void);
70 extern boolean_t
task_did_exec(task_t task
);
71 extern boolean_t
task_is_exec_copy(task_t task
);
73 struct micro_snapshot_buffer
{
76 uint32_t current_position
;
80 void telemetry_take_sample(thread_t thread
, uint8_t microsnapshot_flags
, struct micro_snapshot_buffer
* current_buffer
);
81 int telemetry_buffer_gather(user_addr_t buffer
, uint32_t *length
, boolean_t mark
, struct micro_snapshot_buffer
* current_buffer
);
83 #define TELEMETRY_DEFAULT_SAMPLE_RATE (1) /* 1 sample every 1 second */
84 #define TELEMETRY_DEFAULT_BUFFER_SIZE (16*1024)
85 #define TELEMETRY_MAX_BUFFER_SIZE (64*1024)
87 #define TELEMETRY_DEFAULT_NOTIFY_LEEWAY (4*1024) // Userland gets 4k of leeway to collect data after notification
88 #define TELEMETRY_MAX_UUID_COUNT (128) // Max of 128 non-shared-cache UUIDs to log for symbolication
90 uint32_t telemetry_sample_rate
= 0;
91 volatile boolean_t telemetry_needs_record
= FALSE
;
92 volatile boolean_t telemetry_needs_timer_arming_record
= FALSE
;
95 * If TRUE, record micro-stackshot samples for all tasks.
96 * If FALSE, only sample tasks which are marked for telemetry.
98 boolean_t telemetry_sample_all_tasks
= FALSE
;
99 boolean_t telemetry_sample_pmis
= FALSE
;
100 uint32_t telemetry_active_tasks
= 0; // Number of tasks opted into telemetry
102 uint32_t telemetry_timestamp
= 0;
105 * The telemetry_buffer is responsible
106 * for timer samples and interrupt samples that are driven by
107 * compute_averages(). It will notify its client (if one
108 * exists) when it has enough data to be worth flushing.
110 struct micro_snapshot_buffer telemetry_buffer
= {
113 .current_position
= 0,
117 int telemetry_bytes_since_last_mark
= -1; // How much data since buf was last marked?
118 int telemetry_buffer_notify_at
= 0;
120 LCK_GRP_DECLARE(telemetry_lck_grp
, "telemetry group");
121 LCK_MTX_DECLARE(telemetry_mtx
, &telemetry_lck_grp
);
122 LCK_MTX_DECLARE(telemetry_pmi_mtx
, &telemetry_lck_grp
);
124 #define TELEMETRY_LOCK() do { lck_mtx_lock(&telemetry_mtx); } while (0)
125 #define TELEMETRY_TRY_SPIN_LOCK() lck_mtx_try_lock_spin(&telemetry_mtx)
126 #define TELEMETRY_UNLOCK() do { lck_mtx_unlock(&telemetry_mtx); } while (0)
128 #define TELEMETRY_PMI_LOCK() do { lck_mtx_lock(&telemetry_pmi_mtx); } while (0)
129 #define TELEMETRY_PMI_UNLOCK() do { lck_mtx_unlock(&telemetry_pmi_mtx); } while (0)
135 uint32_t telemetry_notification_leeway
;
137 if (!PE_parse_boot_argn("telemetry_buffer_size",
138 &telemetry_buffer
.size
, sizeof(telemetry_buffer
.size
))) {
139 telemetry_buffer
.size
= TELEMETRY_DEFAULT_BUFFER_SIZE
;
142 if (telemetry_buffer
.size
> TELEMETRY_MAX_BUFFER_SIZE
) {
143 telemetry_buffer
.size
= TELEMETRY_MAX_BUFFER_SIZE
;
146 ret
= kmem_alloc(kernel_map
, &telemetry_buffer
.buffer
, telemetry_buffer
.size
, VM_KERN_MEMORY_DIAG
);
147 if (ret
!= KERN_SUCCESS
) {
148 kprintf("Telemetry: Allocation failed: %d\n", ret
);
151 bzero((void *) telemetry_buffer
.buffer
, telemetry_buffer
.size
);
153 if (!PE_parse_boot_argn("telemetry_notification_leeway",
154 &telemetry_notification_leeway
, sizeof(telemetry_notification_leeway
))) {
156 * By default, notify the user to collect the buffer when there is this much space left in the buffer.
158 telemetry_notification_leeway
= TELEMETRY_DEFAULT_NOTIFY_LEEWAY
;
160 if (telemetry_notification_leeway
>= telemetry_buffer
.size
) {
161 printf("telemetry: nonsensical telemetry_notification_leeway boot-arg %d changed to %d\n",
162 telemetry_notification_leeway
, TELEMETRY_DEFAULT_NOTIFY_LEEWAY
);
163 telemetry_notification_leeway
= TELEMETRY_DEFAULT_NOTIFY_LEEWAY
;
165 telemetry_buffer_notify_at
= telemetry_buffer
.size
- telemetry_notification_leeway
;
167 if (!PE_parse_boot_argn("telemetry_sample_rate",
168 &telemetry_sample_rate
, sizeof(telemetry_sample_rate
))) {
169 telemetry_sample_rate
= TELEMETRY_DEFAULT_SAMPLE_RATE
;
173 * To enable telemetry for all tasks, include "telemetry_sample_all_tasks=1" in boot-args.
175 if (!PE_parse_boot_argn("telemetry_sample_all_tasks",
176 &telemetry_sample_all_tasks
, sizeof(telemetry_sample_all_tasks
))) {
177 #if !defined(XNU_TARGET_OS_OSX) && !(DEVELOPMENT || DEBUG)
178 telemetry_sample_all_tasks
= FALSE
;
180 telemetry_sample_all_tasks
= TRUE
;
181 #endif /* !defined(XNU_TARGET_OS_OSX) && !(DEVELOPMENT || DEBUG) */
184 kprintf("Telemetry: Sampling %stasks once per %u second%s\n",
185 (telemetry_sample_all_tasks
) ? "all " : "",
186 telemetry_sample_rate
, telemetry_sample_rate
== 1 ? "" : "s");
190 * Enable or disable global microstackshots (ie telemetry_sample_all_tasks).
192 * enable_disable == 1: turn it on
193 * enable_disable == 0: turn it off
196 telemetry_global_ctl(int enable_disable
)
198 if (enable_disable
== 1) {
199 telemetry_sample_all_tasks
= TRUE
;
201 telemetry_sample_all_tasks
= FALSE
;
206 * Opt the given task into or out of the telemetry stream.
208 * Supported reasons (callers may use any or all of):
212 * enable_disable == 1: turn it on
213 * enable_disable == 0: turn it off
216 telemetry_task_ctl(task_t task
, uint32_t reasons
, int enable_disable
)
219 telemetry_task_ctl_locked(task
, reasons
, enable_disable
);
224 telemetry_task_ctl_locked(task_t task
, uint32_t reasons
, int enable_disable
)
228 assert((reasons
!= 0) && ((reasons
| TF_TELEMETRY
) == TF_TELEMETRY
));
230 task_lock_assert_owned(task
);
232 origflags
= task
->t_flags
;
234 if (enable_disable
== 1) {
235 task
->t_flags
|= reasons
;
236 if ((origflags
& TF_TELEMETRY
) == 0) {
237 OSIncrementAtomic(&telemetry_active_tasks
);
239 printf("%s: telemetry OFF -> ON (%d active)\n", proc_name_address(task
->bsd_info
), telemetry_active_tasks
);
243 task
->t_flags
&= ~reasons
;
244 if (((origflags
& TF_TELEMETRY
) != 0) && ((task
->t_flags
& TF_TELEMETRY
) == 0)) {
246 * If this task went from having at least one telemetry bit to having none,
247 * the net change was to disable telemetry for the task.
249 OSDecrementAtomic(&telemetry_active_tasks
);
251 printf("%s: telemetry ON -> OFF (%d active)\n", proc_name_address(task
->bsd_info
), telemetry_active_tasks
);
258 * Determine if the current thread is eligible for telemetry:
260 * telemetry_sample_all_tasks: All threads are eligible. This takes precedence.
261 * telemetry_active_tasks: Count of tasks opted in.
262 * task->t_flags & TF_TELEMETRY: This task is opted in.
265 telemetry_is_active(thread_t thread
)
267 task_t task
= thread
->task
;
269 if (task
== kernel_task
) {
270 /* Kernel threads never return to an AST boundary, and are ineligible */
274 if (telemetry_sample_all_tasks
|| telemetry_sample_pmis
) {
278 if ((telemetry_active_tasks
> 0) && ((thread
->task
->t_flags
& TF_TELEMETRY
) != 0)) {
286 * Userland is arming a timer. If we are eligible for such a record,
287 * sample now. No need to do this one at the AST because we're already at
288 * a safe place in this system call.
291 telemetry_timer_event(__unused
uint64_t deadline
, __unused
uint64_t interval
, __unused
uint64_t leeway
)
293 if (telemetry_needs_timer_arming_record
== TRUE
) {
294 telemetry_needs_timer_arming_record
= FALSE
;
295 telemetry_take_sample(current_thread(), kTimerArmingRecord
| kUserMode
, &telemetry_buffer
);
301 #if defined(MT_CORE_INSTRS) && defined(MT_CORE_CYCLES)
303 telemetry_pmi_handler(bool user_mode
, __unused
void *ctx
)
305 telemetry_mark_curthread(user_mode
, TRUE
);
307 #endif /* defined(MT_CORE_INSTRS) && defined(MT_CORE_CYCLES) */
310 telemetry_pmi_setup(enum telemetry_pmi pmi_ctr
, uint64_t period
)
312 #if defined(MT_CORE_INSTRS) && defined(MT_CORE_CYCLES)
313 static boolean_t sample_all_tasks_aside
= FALSE
;
314 static uint32_t active_tasks_aside
= FALSE
;
316 const char *name
= "?";
318 unsigned int ctr
= 0;
320 TELEMETRY_PMI_LOCK();
323 case TELEMETRY_PMI_NONE
:
324 if (!telemetry_sample_pmis
) {
329 telemetry_sample_pmis
= FALSE
;
330 telemetry_sample_all_tasks
= sample_all_tasks_aside
;
331 telemetry_active_tasks
= active_tasks_aside
;
332 error
= mt_microstackshot_stop();
334 printf("telemetry: disabling ustackshot on PMI\n");
338 case TELEMETRY_PMI_INSTRS
:
339 ctr
= MT_CORE_INSTRS
;
340 name
= "instructions";
343 case TELEMETRY_PMI_CYCLES
:
344 ctr
= MT_CORE_CYCLES
;
353 telemetry_sample_pmis
= TRUE
;
354 sample_all_tasks_aside
= telemetry_sample_all_tasks
;
355 active_tasks_aside
= telemetry_active_tasks
;
356 telemetry_sample_all_tasks
= FALSE
;
357 telemetry_active_tasks
= 0;
359 error
= mt_microstackshot_start(ctr
, period
, telemetry_pmi_handler
, NULL
);
361 printf("telemetry: ustackshot every %llu %s\n", period
, name
);
365 TELEMETRY_PMI_UNLOCK();
367 #else /* defined(MT_CORE_INSTRS) && defined(MT_CORE_CYCLES) */
368 #pragma unused(pmi_ctr, period)
370 #endif /* !defined(MT_CORE_INSTRS) || !defined(MT_CORE_CYCLES) */
374 * Mark the current thread for an interrupt-based
375 * telemetry record, to be sampled at the next AST boundary.
378 telemetry_mark_curthread(boolean_t interrupted_userspace
, boolean_t pmi
)
380 uint32_t ast_bits
= 0;
381 thread_t thread
= current_thread();
384 * If telemetry isn't active for this thread, return and try
387 if (telemetry_is_active(thread
) == FALSE
) {
391 ast_bits
|= (interrupted_userspace
? AST_TELEMETRY_USER
: AST_TELEMETRY_KERNEL
);
393 ast_bits
|= AST_TELEMETRY_PMI
;
396 telemetry_needs_record
= FALSE
;
397 thread_ast_set(thread
, ast_bits
);
398 ast_propagate(thread
);
402 compute_telemetry(void *arg __unused
)
404 if (telemetry_sample_all_tasks
|| (telemetry_active_tasks
> 0)) {
405 if ((++telemetry_timestamp
) % telemetry_sample_rate
== 0) {
406 telemetry_needs_record
= TRUE
;
407 telemetry_needs_timer_arming_record
= TRUE
;
413 * If userland has registered a port for telemetry notifications, send one now.
416 telemetry_notify_user(void)
418 mach_port_t user_port
= MACH_PORT_NULL
;
420 kern_return_t kr
= host_get_telemetry_port(host_priv_self(), &user_port
);
421 if ((kr
!= KERN_SUCCESS
) || !IPC_PORT_VALID(user_port
)) {
425 telemetry_notification(user_port
, 0);
426 ipc_port_release_send(user_port
);
430 telemetry_ast(thread_t thread
, ast_t reasons
)
432 assert((reasons
& AST_TELEMETRY_ALL
) != 0);
434 uint8_t record_type
= 0;
435 if (reasons
& AST_TELEMETRY_IO
) {
436 record_type
|= kIORecord
;
438 if (reasons
& (AST_TELEMETRY_USER
| AST_TELEMETRY_KERNEL
)) {
439 record_type
|= (reasons
& AST_TELEMETRY_PMI
) ? kPMIRecord
:
443 uint8_t user_telemetry
= (reasons
& AST_TELEMETRY_USER
) ? kUserMode
: 0;
445 uint8_t microsnapshot_flags
= record_type
| user_telemetry
;
447 telemetry_take_sample(thread
, microsnapshot_flags
, &telemetry_buffer
);
451 telemetry_take_sample(thread_t thread
, uint8_t microsnapshot_flags
, struct micro_snapshot_buffer
* current_buffer
)
455 uint32_t btcount
= 0, bti
;
456 struct micro_snapshot
*msnap
;
457 struct task_snapshot
*tsnap
;
458 struct thread_snapshot
*thsnap
;
462 uint32_t current_record_start
;
464 boolean_t notify
= FALSE
;
466 if (thread
== THREAD_NULL
) {
471 if ((task
== TASK_NULL
) || (task
== kernel_task
) || task_did_exec(task
) || task_is_exec_copy(task
)) {
475 /* telemetry_XXX accessed outside of lock for instrumentation only */
476 KDBG(MACHDBG_CODE(DBG_MACH_STACKSHOT
, MICROSTACKSHOT_RECORD
) | DBG_FUNC_START
,
477 microsnapshot_flags
, telemetry_bytes_since_last_mark
, 0,
478 (&telemetry_buffer
!= current_buffer
));
480 p
= get_bsdtask_info(task
);
483 * Gather up the data we'll need for this sample. The sample is written into the kernel
484 * buffer with the global telemetry lock held -- so we must do our (possibly faulting)
485 * copies from userland here, before taking the lock.
488 uintptr_t frames
[128];
489 bool user64_regs
= false;
491 btcount
= backtrace_user(frames
,
492 sizeof(frames
) / sizeof(frames
[0]), &bterror
, &user64_regs
, NULL
);
496 bool user64_va
= task_has_64Bit_addr(task
);
499 * Find the actual [slid] address of the shared cache's UUID, and copy it in from userland.
501 int shared_cache_uuid_valid
= 0;
502 uint64_t shared_cache_base_address
= 0;
503 struct _dyld_cache_header shared_cache_header
= {};
504 uint64_t shared_cache_slide
= 0;
507 * Don't copy in the entire shared cache header; we only need the UUID. Calculate the
508 * offset of that one field.
510 int sc_header_uuid_offset
= (char *)&shared_cache_header
.uuid
- (char *)&shared_cache_header
;
511 vm_shared_region_t sr
= vm_shared_region_get(task
);
513 if ((vm_shared_region_start_address(sr
, &shared_cache_base_address
) == KERN_SUCCESS
) &&
514 (copyin(shared_cache_base_address
+ sc_header_uuid_offset
, (char *)&shared_cache_header
.uuid
,
515 sizeof(shared_cache_header
.uuid
)) == 0)) {
516 shared_cache_uuid_valid
= 1;
517 shared_cache_slide
= sr
->sr_slide
;
519 // vm_shared_region_get() gave us a reference on the shared region.
520 vm_shared_region_deallocate(sr
);
524 * Retrieve the array of UUID's for binaries used by this task.
525 * We reach down into DYLD's data structures to find the array.
527 * XXX - make this common with kdp?
529 uint32_t uuid_info_count
= 0;
530 mach_vm_address_t uuid_info_addr
= 0;
531 uint32_t uuid_info_size
= 0;
533 uuid_info_size
= sizeof(struct user64_dyld_uuid_info
);
534 struct user64_dyld_all_image_infos task_image_infos
;
535 if (copyin(task
->all_image_info_addr
, (char *)&task_image_infos
, sizeof(task_image_infos
)) == 0) {
536 uuid_info_count
= (uint32_t)task_image_infos
.uuidArrayCount
;
537 uuid_info_addr
= task_image_infos
.uuidArray
;
540 uuid_info_size
= sizeof(struct user32_dyld_uuid_info
);
541 struct user32_dyld_all_image_infos task_image_infos
;
542 if (copyin(task
->all_image_info_addr
, (char *)&task_image_infos
, sizeof(task_image_infos
)) == 0) {
543 uuid_info_count
= task_image_infos
.uuidArrayCount
;
544 uuid_info_addr
= task_image_infos
.uuidArray
;
549 * If we get a NULL uuid_info_addr (which can happen when we catch dyld in the middle of updating
550 * this data structure), we zero the uuid_info_count so that we won't even try to save load info
553 if (!uuid_info_addr
) {
558 * Don't copy in an unbounded amount of memory. The main binary and interesting
559 * non-shared-cache libraries should be in the first few images.
561 if (uuid_info_count
> TELEMETRY_MAX_UUID_COUNT
) {
562 uuid_info_count
= TELEMETRY_MAX_UUID_COUNT
;
565 uint32_t uuid_info_array_size
= uuid_info_count
* uuid_info_size
;
566 char *uuid_info_array
= NULL
;
568 if (uuid_info_count
> 0) {
569 uuid_info_array
= kheap_alloc(KHEAP_TEMP
,
570 uuid_info_array_size
, Z_WAITOK
);
571 if (uuid_info_array
== NULL
) {
576 * Copy in the UUID info array.
577 * It may be nonresident, in which case just fix up nloadinfos to 0 in the task snapshot.
579 if (copyin(uuid_info_addr
, uuid_info_array
, uuid_info_array_size
) != 0) {
580 kheap_free(KHEAP_TEMP
, uuid_info_array
, uuid_info_array_size
);
581 uuid_info_array
= NULL
;
582 uuid_info_array_size
= 0;
587 * Look for a dispatch queue serial number, and copy it in from userland if present.
589 uint64_t dqserialnum
= 0;
590 int dqserialnum_valid
= 0;
592 uint64_t dqkeyaddr
= thread_dispatchqaddr(thread
);
593 if (dqkeyaddr
!= 0) {
595 uint64_t dq_serialno_offset
= get_task_dispatchqueue_serialno_offset(task
);
596 if ((copyin(dqkeyaddr
, (char *)&dqaddr
, (user64_va
? 8 : 4)) == 0) &&
597 (dqaddr
!= 0) && (dq_serialno_offset
!= 0)) {
598 uint64_t dqserialnumaddr
= dqaddr
+ dq_serialno_offset
;
599 if (copyin(dqserialnumaddr
, (char *)&dqserialnum
, (user64_va
? 8 : 4)) == 0) {
600 dqserialnum_valid
= 1;
605 clock_get_calendar_microtime(&secs
, &usecs
);
610 * If our buffer is not backed by anything,
611 * then we cannot take the sample. Meant to allow us to deallocate the window
612 * buffer if it is disabled.
614 if (!current_buffer
->buffer
) {
619 * We do the bulk of the operation under the telemetry lock, on assumption that
620 * any page faults during execution will not cause another AST_TELEMETRY_ALL
621 * to deadlock; they will just block until we finish. This makes it easier
622 * to copy into the buffer directly. As soon as we unlock, userspace can copy
628 current_record_start
= current_buffer
->current_position
;
630 if ((current_buffer
->size
- current_buffer
->current_position
) < sizeof(struct micro_snapshot
)) {
632 * We can't fit a record in the space available, so wrap around to the beginning.
633 * Save the current position as the known end point of valid data.
635 current_buffer
->end_point
= current_record_start
;
636 current_buffer
->current_position
= 0;
637 if (current_record_start
== 0) {
638 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
644 msnap
= (struct micro_snapshot
*)(uintptr_t)(current_buffer
->buffer
+ current_buffer
->current_position
);
645 msnap
->snapshot_magic
= STACKSHOT_MICRO_SNAPSHOT_MAGIC
;
646 msnap
->ms_flags
= microsnapshot_flags
;
647 msnap
->ms_opaque_flags
= 0; /* namespace managed by userspace */
648 msnap
->ms_cpu
= cpu_number();
649 msnap
->ms_time
= secs
;
650 msnap
->ms_time_microsecs
= usecs
;
652 current_buffer
->current_position
+= sizeof(struct micro_snapshot
);
654 if ((current_buffer
->size
- current_buffer
->current_position
) < sizeof(struct task_snapshot
)) {
655 current_buffer
->end_point
= current_record_start
;
656 current_buffer
->current_position
= 0;
657 if (current_record_start
== 0) {
658 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
664 tsnap
= (struct task_snapshot
*)(uintptr_t)(current_buffer
->buffer
+ current_buffer
->current_position
);
665 bzero(tsnap
, sizeof(*tsnap
));
666 tsnap
->snapshot_magic
= STACKSHOT_TASK_SNAPSHOT_MAGIC
;
667 tsnap
->pid
= proc_pid(p
);
668 tsnap
->uniqueid
= proc_uniqueid(p
);
669 tsnap
->user_time_in_terminated_threads
= task
->total_user_time
;
670 tsnap
->system_time_in_terminated_threads
= task
->total_system_time
;
671 tsnap
->suspend_count
= task
->suspend_count
;
672 tsnap
->task_size
= (typeof(tsnap
->task_size
))(get_task_phys_footprint(task
) / PAGE_SIZE
);
673 tsnap
->faults
= task
->faults
;
674 tsnap
->pageins
= task
->pageins
;
675 tsnap
->cow_faults
= task
->cow_faults
;
677 * The throttling counters are maintained as 64-bit counters in the proc
678 * structure. However, we reserve 32-bits (each) for them in the task_snapshot
679 * struct to save space and since we do not expect them to overflow 32-bits. If we
680 * find these values overflowing in the future, the fix would be to simply
681 * upgrade these counters to 64-bit in the task_snapshot struct
683 tsnap
->was_throttled
= (uint32_t) proc_was_throttled(p
);
684 tsnap
->did_throttle
= (uint32_t) proc_did_throttle(p
);
686 if (task
->t_flags
& TF_TELEMETRY
) {
687 tsnap
->ss_flags
|= kTaskRsrcFlagged
;
690 if (proc_get_effective_task_policy(task
, TASK_POLICY_DARWIN_BG
)) {
691 tsnap
->ss_flags
|= kTaskDarwinBG
;
694 proc_get_darwinbgstate(task
, &tmp
);
696 if (proc_get_effective_task_policy(task
, TASK_POLICY_ROLE
) == TASK_FOREGROUND_APPLICATION
) {
697 tsnap
->ss_flags
|= kTaskIsForeground
;
700 if (tmp
& PROC_FLAG_ADAPTIVE_IMPORTANT
) {
701 tsnap
->ss_flags
|= kTaskIsBoosted
;
704 if (tmp
& PROC_FLAG_SUPPRESSED
) {
705 tsnap
->ss_flags
|= kTaskIsSuppressed
;
709 tsnap
->latency_qos
= task_grab_latency_qos(task
);
711 strlcpy(tsnap
->p_comm
, proc_name_address(p
), sizeof(tsnap
->p_comm
));
713 tsnap
->ss_flags
|= kUser64_p
;
716 if (shared_cache_uuid_valid
) {
717 tsnap
->shared_cache_slide
= shared_cache_slide
;
718 bcopy(shared_cache_header
.uuid
, tsnap
->shared_cache_identifier
, sizeof(shared_cache_header
.uuid
));
721 current_buffer
->current_position
+= sizeof(struct task_snapshot
);
724 * Directly after the task snapshot, place the array of UUID's corresponding to the binaries
727 if ((current_buffer
->size
- current_buffer
->current_position
) < uuid_info_array_size
) {
728 current_buffer
->end_point
= current_record_start
;
729 current_buffer
->current_position
= 0;
730 if (current_record_start
== 0) {
731 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
738 * Copy the UUID info array into our sample.
740 if (uuid_info_array_size
> 0) {
741 bcopy(uuid_info_array
, (char *)(current_buffer
->buffer
+ current_buffer
->current_position
), uuid_info_array_size
);
742 tsnap
->nloadinfos
= uuid_info_count
;
745 current_buffer
->current_position
+= uuid_info_array_size
;
748 * After the task snapshot & list of binary UUIDs, we place a thread snapshot.
751 if ((current_buffer
->size
- current_buffer
->current_position
) < sizeof(struct thread_snapshot
)) {
752 /* wrap and overwrite */
753 current_buffer
->end_point
= current_record_start
;
754 current_buffer
->current_position
= 0;
755 if (current_record_start
== 0) {
756 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
762 thsnap
= (struct thread_snapshot
*)(uintptr_t)(current_buffer
->buffer
+ current_buffer
->current_position
);
763 bzero(thsnap
, sizeof(*thsnap
));
765 thsnap
->snapshot_magic
= STACKSHOT_THREAD_SNAPSHOT_MAGIC
;
766 thsnap
->thread_id
= thread_tid(thread
);
767 thsnap
->state
= thread
->state
;
768 thsnap
->priority
= thread
->base_pri
;
769 thsnap
->sched_pri
= thread
->sched_pri
;
770 thsnap
->sched_flags
= thread
->sched_flags
;
771 thsnap
->ss_flags
|= kStacksPCOnly
;
772 thsnap
->ts_qos
= thread
->effective_policy
.thep_qos
;
773 thsnap
->ts_rqos
= thread
->requested_policy
.thrp_qos
;
774 thsnap
->ts_rqos_override
= MAX(thread
->requested_policy
.thrp_qos_override
,
775 thread
->requested_policy
.thrp_qos_workq_override
);
777 if (proc_get_effective_thread_policy(thread
, TASK_POLICY_DARWIN_BG
)) {
778 thsnap
->ss_flags
|= kThreadDarwinBG
;
781 thsnap
->user_time
= timer_grab(&thread
->user_timer
);
783 uint64_t tval
= timer_grab(&thread
->system_timer
);
785 if (thread
->precise_user_kernel_time
) {
786 thsnap
->system_time
= tval
;
788 thsnap
->user_time
+= tval
;
789 thsnap
->system_time
= 0;
792 current_buffer
->current_position
+= sizeof(struct thread_snapshot
);
795 * If this thread has a dispatch queue serial number, include it here.
797 if (dqserialnum_valid
) {
798 if ((current_buffer
->size
- current_buffer
->current_position
) < sizeof(dqserialnum
)) {
799 /* wrap and overwrite */
800 current_buffer
->end_point
= current_record_start
;
801 current_buffer
->current_position
= 0;
802 if (current_record_start
== 0) {
803 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
809 thsnap
->ss_flags
|= kHasDispatchSerial
;
810 bcopy(&dqserialnum
, (char *)current_buffer
->buffer
+ current_buffer
->current_position
, sizeof(dqserialnum
));
811 current_buffer
->current_position
+= sizeof(dqserialnum
);
816 thsnap
->ss_flags
|= kUser64_p
;
822 * If we can't fit this entire stacktrace then cancel this record, wrap to the beginning,
823 * and start again there so that we always store a full record.
825 if ((current_buffer
->size
- current_buffer
->current_position
) / framesize
< btcount
) {
826 current_buffer
->end_point
= current_record_start
;
827 current_buffer
->current_position
= 0;
828 if (current_record_start
== 0) {
829 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
835 for (bti
= 0; bti
< btcount
; bti
++, current_buffer
->current_position
+= framesize
) {
836 if (framesize
== 8) {
837 *(uint64_t *)(uintptr_t)(current_buffer
->buffer
+ current_buffer
->current_position
) = frames
[bti
];
839 *(uint32_t *)(uintptr_t)(current_buffer
->buffer
+ current_buffer
->current_position
) = (uint32_t)frames
[bti
];
843 if (current_buffer
->end_point
< current_buffer
->current_position
) {
845 * Each time the cursor wraps around to the beginning, we leave a
846 * differing amount of unused space at the end of the buffer. Make
847 * sure the cursor pushes the end point in case we're making use of
848 * more of the buffer than we did the last time we wrapped.
850 current_buffer
->end_point
= current_buffer
->current_position
;
853 thsnap
->nuser_frames
= btcount
;
856 * Now THIS is a hack.
858 if (current_buffer
== &telemetry_buffer
) {
859 telemetry_bytes_since_last_mark
+= (current_buffer
->current_position
- current_record_start
);
860 if (telemetry_bytes_since_last_mark
> telemetry_buffer_notify_at
) {
868 KDBG(MACHDBG_CODE(DBG_MACH_STACKSHOT
, MICROSTACKSHOT_RECORD
) | DBG_FUNC_END
,
869 notify
, telemetry_bytes_since_last_mark
,
870 current_buffer
->current_position
, current_buffer
->end_point
);
873 telemetry_notify_user();
876 if (uuid_info_array
!= NULL
) {
877 kheap_free(KHEAP_TEMP
, uuid_info_array
, uuid_info_array_size
);
883 log_telemetry_output(vm_offset_t buf
, uint32_t pos
, uint32_t sz
)
885 struct micro_snapshot
*p
;
888 printf("Copying out %d bytes of telemetry at offset %d\n", sz
, pos
);
893 * Find and log each timestamp in this chunk of buffer.
895 for (offset
= 0; offset
< sz
; offset
++) {
896 p
= (struct micro_snapshot
*)(buf
+ offset
);
897 if (p
->snapshot_magic
== STACKSHOT_MICRO_SNAPSHOT_MAGIC
) {
898 printf("telemetry timestamp: %lld\n", p
->ms_time
);
905 telemetry_gather(user_addr_t buffer
, uint32_t *length
, boolean_t mark
)
907 return telemetry_buffer_gather(buffer
, length
, mark
, &telemetry_buffer
);
911 telemetry_buffer_gather(user_addr_t buffer
, uint32_t *length
, boolean_t mark
, struct micro_snapshot_buffer
* current_buffer
)
914 uint32_t oldest_record_offset
;
916 KDBG(MACHDBG_CODE(DBG_MACH_STACKSHOT
, MICROSTACKSHOT_GATHER
) | DBG_FUNC_START
,
917 mark
, telemetry_bytes_since_last_mark
, 0,
918 (&telemetry_buffer
!= current_buffer
));
922 if (current_buffer
->buffer
== 0) {
927 if (*length
< current_buffer
->size
) {
928 result
= KERN_NO_SPACE
;
933 * Copy the ring buffer out to userland in order sorted by time: least recent to most recent.
934 * First, we need to search forward from the cursor to find the oldest record in our buffer.
936 oldest_record_offset
= current_buffer
->current_position
;
938 if (((oldest_record_offset
+ sizeof(uint32_t)) > current_buffer
->size
) ||
939 ((oldest_record_offset
+ sizeof(uint32_t)) > current_buffer
->end_point
)) {
940 if (*(uint32_t *)(uintptr_t)(current_buffer
->buffer
) == 0) {
942 * There is no magic number at the start of the buffer, which means
943 * it's empty; nothing to see here yet.
949 * We've looked through the end of the active buffer without finding a valid
950 * record; that means all valid records are in a single chunk, beginning at
951 * the very start of the buffer.
954 oldest_record_offset
= 0;
955 assert(*(uint32_t *)(uintptr_t)(current_buffer
->buffer
) == STACKSHOT_MICRO_SNAPSHOT_MAGIC
);
959 if (*(uint32_t *)(uintptr_t)(current_buffer
->buffer
+ oldest_record_offset
) == STACKSHOT_MICRO_SNAPSHOT_MAGIC
) {
964 * There are no alignment guarantees for micro-stackshot records, so we must search at each
967 oldest_record_offset
++;
968 } while (oldest_record_offset
!= current_buffer
->current_position
);
971 * If needed, copyout in two chunks: from the oldest record to the end of the buffer, and then
972 * from the beginning of the buffer up to the current position.
974 if (oldest_record_offset
!= 0) {
976 log_telemetry_output(current_buffer
->buffer
, oldest_record_offset
,
977 current_buffer
->end_point
- oldest_record_offset
);
979 if ((result
= copyout((void *)(current_buffer
->buffer
+ oldest_record_offset
), buffer
,
980 current_buffer
->end_point
- oldest_record_offset
)) != 0) {
984 *length
= current_buffer
->end_point
- oldest_record_offset
;
990 log_telemetry_output(current_buffer
->buffer
, 0, current_buffer
->current_position
);
992 if ((result
= copyout((void *)current_buffer
->buffer
, buffer
+ *length
,
993 current_buffer
->current_position
)) != 0) {
997 *length
+= (uint32_t)current_buffer
->current_position
;
1001 if (mark
&& (*length
> 0)) {
1002 telemetry_bytes_since_last_mark
= 0;
1007 KDBG(MACHDBG_CODE(DBG_MACH_STACKSHOT
, MICROSTACKSHOT_GATHER
) | DBG_FUNC_END
,
1008 current_buffer
->current_position
, *length
,
1009 current_buffer
->end_point
, (&telemetry_buffer
!= current_buffer
));
1014 /************************/
1015 /* BOOT PROFILE SUPPORT */
1016 /************************/
1020 * The boot-profiling support is a mechanism to sample activity happening on the
1021 * system during boot. This mechanism sets up a periodic timer and on every timer fire,
1022 * captures a full backtrace into the boot profiling buffer. This buffer can be pulled
1023 * out and analyzed from user-space. It is turned on using the following boot-args:
1024 * "bootprofile_buffer_size" specifies the size of the boot profile buffer
1025 * "bootprofile_interval_ms" specifies the interval for the profiling timer
1027 * Process Specific Boot Profiling
1029 * The boot-arg "bootprofile_proc_name" can be used to specify a certain
1030 * process that needs to profiled during boot. Setting this boot-arg changes
1031 * the way stackshots are captured. At every timer fire, the code looks at the
1032 * currently running process and takes a stackshot only if the requested process
1033 * is on-core (which makes it unsuitable for MP systems).
1037 * The boot-arg "bootprofile_type=boot" starts the timer during early boot. Using
1038 * "wake" starts the timer at AP wake from suspend-to-RAM.
1041 #define BOOTPROFILE_MAX_BUFFER_SIZE (64*1024*1024) /* see also COPYSIZELIMIT_PANIC */
1043 vm_offset_t bootprofile_buffer
= 0;
1044 uint32_t bootprofile_buffer_size
= 0;
1045 uint32_t bootprofile_buffer_current_position
= 0;
1046 uint32_t bootprofile_interval_ms
= 0;
1047 uint64_t bootprofile_stackshot_flags
= 0;
1048 uint64_t bootprofile_interval_abs
= 0;
1049 uint64_t bootprofile_next_deadline
= 0;
1050 uint32_t bootprofile_all_procs
= 0;
1051 char bootprofile_proc_name
[17];
1052 uint64_t bootprofile_delta_since_timestamp
= 0;
1053 LCK_GRP_DECLARE(bootprofile_lck_grp
, "bootprofile_group");
1054 LCK_MTX_DECLARE(bootprofile_mtx
, &bootprofile_lck_grp
);
1058 kBootProfileDisabled
= 0,
1059 kBootProfileStartTimerAtBoot
,
1060 kBootProfileStartTimerAtWake
1061 } bootprofile_type
= kBootProfileDisabled
;
1064 static timer_call_data_t bootprofile_timer_call_entry
;
1066 #define BOOTPROFILE_LOCK() do { lck_mtx_lock(&bootprofile_mtx); } while(0)
1067 #define BOOTPROFILE_TRY_SPIN_LOCK() lck_mtx_try_lock_spin(&bootprofile_mtx)
1068 #define BOOTPROFILE_UNLOCK() do { lck_mtx_unlock(&bootprofile_mtx); } while(0)
1070 static void bootprofile_timer_call(
1071 timer_call_param_t param0
,
1072 timer_call_param_t param1
);
1075 bootprofile_init(void)
1080 if (!PE_parse_boot_argn("bootprofile_buffer_size",
1081 &bootprofile_buffer_size
, sizeof(bootprofile_buffer_size
))) {
1082 bootprofile_buffer_size
= 0;
1085 if (bootprofile_buffer_size
> BOOTPROFILE_MAX_BUFFER_SIZE
) {
1086 bootprofile_buffer_size
= BOOTPROFILE_MAX_BUFFER_SIZE
;
1089 if (!PE_parse_boot_argn("bootprofile_interval_ms",
1090 &bootprofile_interval_ms
, sizeof(bootprofile_interval_ms
))) {
1091 bootprofile_interval_ms
= 0;
1094 if (!PE_parse_boot_argn("bootprofile_stackshot_flags",
1095 &bootprofile_stackshot_flags
, sizeof(bootprofile_stackshot_flags
))) {
1096 bootprofile_stackshot_flags
= 0;
1099 if (!PE_parse_boot_argn("bootprofile_proc_name",
1100 &bootprofile_proc_name
, sizeof(bootprofile_proc_name
))) {
1101 bootprofile_all_procs
= 1;
1102 bootprofile_proc_name
[0] = '\0';
1105 if (PE_parse_boot_argn("bootprofile_type", type
, sizeof(type
))) {
1106 if (0 == strcmp(type
, "boot")) {
1107 bootprofile_type
= kBootProfileStartTimerAtBoot
;
1108 } else if (0 == strcmp(type
, "wake")) {
1109 bootprofile_type
= kBootProfileStartTimerAtWake
;
1111 bootprofile_type
= kBootProfileDisabled
;
1114 bootprofile_type
= kBootProfileDisabled
;
1117 clock_interval_to_absolutetime_interval(bootprofile_interval_ms
, NSEC_PER_MSEC
, &bootprofile_interval_abs
);
1119 /* Both boot args must be set to enable */
1120 if ((bootprofile_type
== kBootProfileDisabled
) || (bootprofile_buffer_size
== 0) || (bootprofile_interval_abs
== 0)) {
1124 ret
= kmem_alloc(kernel_map
, &bootprofile_buffer
, bootprofile_buffer_size
, VM_KERN_MEMORY_DIAG
);
1125 if (ret
!= KERN_SUCCESS
) {
1126 kprintf("Boot profile: Allocation failed: %d\n", ret
);
1129 bzero((void *) bootprofile_buffer
, bootprofile_buffer_size
);
1131 kprintf("Boot profile: Sampling %s once per %u ms at %s\n",
1132 bootprofile_all_procs
? "all procs" : bootprofile_proc_name
, bootprofile_interval_ms
,
1133 bootprofile_type
== kBootProfileStartTimerAtBoot
? "boot" : (bootprofile_type
== kBootProfileStartTimerAtWake
? "wake" : "unknown"));
1135 timer_call_setup(&bootprofile_timer_call_entry
,
1136 bootprofile_timer_call
,
1139 if (bootprofile_type
== kBootProfileStartTimerAtBoot
) {
1140 bootprofile_next_deadline
= mach_absolute_time() + bootprofile_interval_abs
;
1141 timer_call_enter_with_leeway(&bootprofile_timer_call_entry
,
1143 bootprofile_next_deadline
,
1145 TIMER_CALL_SYS_NORMAL
,
1151 bootprofile_wake_from_sleep(void)
1153 if (bootprofile_type
== kBootProfileStartTimerAtWake
) {
1154 bootprofile_next_deadline
= mach_absolute_time() + bootprofile_interval_abs
;
1155 timer_call_enter_with_leeway(&bootprofile_timer_call_entry
,
1157 bootprofile_next_deadline
,
1159 TIMER_CALL_SYS_NORMAL
,
1166 bootprofile_timer_call(
1167 timer_call_param_t param0 __unused
,
1168 timer_call_param_t param1 __unused
)
1170 unsigned retbytes
= 0;
1171 int pid_to_profile
= -1;
1173 if (!BOOTPROFILE_TRY_SPIN_LOCK()) {
1177 /* Check if process-specific boot profiling is turned on */
1178 if (!bootprofile_all_procs
) {
1180 * Since boot profiling initializes really early in boot, it is
1181 * possible that at this point, the task/proc is not initialized.
1182 * Nothing to do in that case.
1185 if ((current_task() != NULL
) && (current_task()->bsd_info
!= NULL
) &&
1186 (0 == strncmp(bootprofile_proc_name
, proc_name_address(current_task()->bsd_info
), 17))) {
1187 pid_to_profile
= proc_selfpid();
1190 * Process-specific boot profiling requested but the on-core process is
1191 * something else. Nothing to do here.
1193 BOOTPROFILE_UNLOCK();
1198 /* initiate a stackshot with whatever portion of the buffer is left */
1199 if (bootprofile_buffer_current_position
< bootprofile_buffer_size
) {
1200 uint64_t flags
= STACKSHOT_KCDATA_FORMAT
| STACKSHOT_TRYLOCK
| STACKSHOT_SAVE_LOADINFO
1201 | STACKSHOT_GET_GLOBAL_MEM_STATS
;
1202 #if defined(XNU_TARGET_OS_OSX)
1203 flags
|= STACKSHOT_SAVE_KEXT_LOADINFO
;
1207 /* OR on flags specified in boot-args */
1208 flags
|= bootprofile_stackshot_flags
;
1209 if ((flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
) && (bootprofile_delta_since_timestamp
== 0)) {
1210 /* Can't take deltas until the first one */
1211 flags
&= ~STACKSHOT_COLLECT_DELTA_SNAPSHOT
;
1214 uint64_t timestamp
= 0;
1215 if (bootprofile_stackshot_flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
) {
1216 timestamp
= mach_absolute_time();
1219 kern_return_t r
= stack_snapshot_from_kernel(
1220 pid_to_profile
, (void *)(bootprofile_buffer
+ bootprofile_buffer_current_position
),
1221 bootprofile_buffer_size
- bootprofile_buffer_current_position
,
1222 flags
, bootprofile_delta_since_timestamp
, 0, &retbytes
);
1225 * We call with STACKSHOT_TRYLOCK because the stackshot lock is coarser
1226 * than the bootprofile lock. If someone else has the lock we'll just
1230 if (r
== KERN_LOCK_OWNED
) {
1231 BOOTPROFILE_UNLOCK();
1235 if (bootprofile_stackshot_flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
&&
1236 r
== KERN_SUCCESS
) {
1237 bootprofile_delta_since_timestamp
= timestamp
;
1240 bootprofile_buffer_current_position
+= retbytes
;
1243 BOOTPROFILE_UNLOCK();
1245 /* If we didn't get any data or have run out of buffer space, stop profiling */
1246 if ((retbytes
== 0) || (bootprofile_buffer_current_position
== bootprofile_buffer_size
)) {
1252 /* If the user gathered the buffer, no need to keep profiling */
1253 if (bootprofile_interval_abs
== 0) {
1257 clock_deadline_for_periodic_event(bootprofile_interval_abs
,
1258 mach_absolute_time(),
1259 &bootprofile_next_deadline
);
1260 timer_call_enter_with_leeway(&bootprofile_timer_call_entry
,
1262 bootprofile_next_deadline
,
1264 TIMER_CALL_SYS_NORMAL
,
1269 bootprofile_get(void **buffer
, uint32_t *length
)
1272 *buffer
= (void*) bootprofile_buffer
;
1273 *length
= bootprofile_buffer_current_position
;
1274 BOOTPROFILE_UNLOCK();
1278 bootprofile_gather(user_addr_t buffer
, uint32_t *length
)
1284 if (bootprofile_buffer
== 0) {
1289 if (*length
< bootprofile_buffer_current_position
) {
1290 result
= KERN_NO_SPACE
;
1294 if ((result
= copyout((void *)bootprofile_buffer
, buffer
,
1295 bootprofile_buffer_current_position
)) != 0) {
1299 *length
= bootprofile_buffer_current_position
;
1301 /* cancel future timers */
1302 bootprofile_interval_abs
= 0;
1306 BOOTPROFILE_UNLOCK();