2 * Copyright (c) 2012-2013 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
63 extern int proc_pid(void *);
64 extern char *proc_name_address(void *p
);
65 extern uint64_t proc_uniqueid(void *p
);
66 extern uint64_t proc_was_throttled(void *p
);
67 extern uint64_t proc_did_throttle(void *p
);
68 extern int proc_selfpid(void);
69 extern boolean_t
task_did_exec(task_t task
);
70 extern boolean_t
task_is_exec_copy(task_t task
);
72 struct micro_snapshot_buffer
{
75 uint32_t current_position
;
79 void telemetry_take_sample(thread_t thread
, uint8_t microsnapshot_flags
, struct micro_snapshot_buffer
* current_buffer
);
80 int telemetry_buffer_gather(user_addr_t buffer
, uint32_t *length
, boolean_t mark
, struct micro_snapshot_buffer
* current_buffer
);
82 #define TELEMETRY_DEFAULT_SAMPLE_RATE (1) /* 1 sample every 1 second */
83 #define TELEMETRY_DEFAULT_BUFFER_SIZE (16*1024)
84 #define TELEMETRY_MAX_BUFFER_SIZE (64*1024)
86 #define TELEMETRY_DEFAULT_NOTIFY_LEEWAY (4*1024) // Userland gets 4k of leeway to collect data after notification
87 #define TELEMETRY_MAX_UUID_COUNT (128) // Max of 128 non-shared-cache UUIDs to log for symbolication
89 uint32_t telemetry_sample_rate
= 0;
90 volatile boolean_t telemetry_needs_record
= FALSE
;
91 volatile boolean_t telemetry_needs_timer_arming_record
= FALSE
;
94 * If TRUE, record micro-stackshot samples for all tasks.
95 * If FALSE, only sample tasks which are marked for telemetry.
97 boolean_t telemetry_sample_all_tasks
= FALSE
;
98 boolean_t telemetry_sample_pmis
= FALSE
;
99 uint32_t telemetry_active_tasks
= 0; // Number of tasks opted into telemetry
101 uint32_t telemetry_timestamp
= 0;
104 * The telemetry_buffer is responsible
105 * for timer samples and interrupt samples that are driven by
106 * compute_averages(). It will notify its client (if one
107 * exists) when it has enough data to be worth flushing.
109 struct micro_snapshot_buffer telemetry_buffer
= {0, 0, 0, 0};
111 int telemetry_bytes_since_last_mark
= -1; // How much data since buf was last marked?
112 int telemetry_buffer_notify_at
= 0;
114 lck_grp_t telemetry_lck_grp
;
115 lck_mtx_t telemetry_mtx
;
116 lck_mtx_t telemetry_pmi_mtx
;
118 #define TELEMETRY_LOCK() do { lck_mtx_lock(&telemetry_mtx); } while (0)
119 #define TELEMETRY_TRY_SPIN_LOCK() lck_mtx_try_lock_spin(&telemetry_mtx)
120 #define TELEMETRY_UNLOCK() do { lck_mtx_unlock(&telemetry_mtx); } while (0)
122 #define TELEMETRY_PMI_LOCK() do { lck_mtx_lock(&telemetry_pmi_mtx); } while (0)
123 #define TELEMETRY_PMI_UNLOCK() do { lck_mtx_unlock(&telemetry_pmi_mtx); } while (0)
129 uint32_t telemetry_notification_leeway
;
131 lck_grp_init(&telemetry_lck_grp
, "telemetry group", LCK_GRP_ATTR_NULL
);
132 lck_mtx_init(&telemetry_mtx
, &telemetry_lck_grp
, LCK_ATTR_NULL
);
133 lck_mtx_init(&telemetry_pmi_mtx
, &telemetry_lck_grp
, LCK_ATTR_NULL
);
135 if (!PE_parse_boot_argn("telemetry_buffer_size", &telemetry_buffer
.size
, sizeof(telemetry_buffer
.size
))) {
136 telemetry_buffer
.size
= TELEMETRY_DEFAULT_BUFFER_SIZE
;
139 if (telemetry_buffer
.size
> TELEMETRY_MAX_BUFFER_SIZE
) {
140 telemetry_buffer
.size
= TELEMETRY_MAX_BUFFER_SIZE
;
143 ret
= kmem_alloc(kernel_map
, &telemetry_buffer
.buffer
, telemetry_buffer
.size
, VM_KERN_MEMORY_DIAG
);
144 if (ret
!= KERN_SUCCESS
) {
145 kprintf("Telemetry: Allocation failed: %d\n", ret
);
148 bzero((void *) telemetry_buffer
.buffer
, telemetry_buffer
.size
);
150 if (!PE_parse_boot_argn("telemetry_notification_leeway", &telemetry_notification_leeway
, sizeof(telemetry_notification_leeway
))) {
152 * By default, notify the user to collect the buffer when there is this much space left in the buffer.
154 telemetry_notification_leeway
= TELEMETRY_DEFAULT_NOTIFY_LEEWAY
;
156 if (telemetry_notification_leeway
>= telemetry_buffer
.size
) {
157 printf("telemetry: nonsensical telemetry_notification_leeway boot-arg %d changed to %d\n",
158 telemetry_notification_leeway
, TELEMETRY_DEFAULT_NOTIFY_LEEWAY
);
159 telemetry_notification_leeway
= TELEMETRY_DEFAULT_NOTIFY_LEEWAY
;
161 telemetry_buffer_notify_at
= telemetry_buffer
.size
- telemetry_notification_leeway
;
163 if (!PE_parse_boot_argn("telemetry_sample_rate", &telemetry_sample_rate
, sizeof(telemetry_sample_rate
))) {
164 telemetry_sample_rate
= TELEMETRY_DEFAULT_SAMPLE_RATE
;
168 * To enable telemetry for all tasks, include "telemetry_sample_all_tasks=1" in boot-args.
170 if (!PE_parse_boot_argn("telemetry_sample_all_tasks", &telemetry_sample_all_tasks
, sizeof(telemetry_sample_all_tasks
))) {
171 #if CONFIG_EMBEDDED && !(DEVELOPMENT || DEBUG)
172 telemetry_sample_all_tasks
= FALSE
;
174 telemetry_sample_all_tasks
= TRUE
;
175 #endif /* CONFIG_EMBEDDED && !(DEVELOPMENT || DEBUG) */
178 kprintf("Telemetry: Sampling %stasks once per %u second%s\n",
179 (telemetry_sample_all_tasks
) ? "all " : "",
180 telemetry_sample_rate
, telemetry_sample_rate
== 1 ? "" : "s");
184 * Enable or disable global microstackshots (ie telemetry_sample_all_tasks).
186 * enable_disable == 1: turn it on
187 * enable_disable == 0: turn it off
190 telemetry_global_ctl(int enable_disable
)
192 if (enable_disable
== 1) {
193 telemetry_sample_all_tasks
= TRUE
;
195 telemetry_sample_all_tasks
= FALSE
;
200 * Opt the given task into or out of the telemetry stream.
202 * Supported reasons (callers may use any or all of):
206 * enable_disable == 1: turn it on
207 * enable_disable == 0: turn it off
210 telemetry_task_ctl(task_t task
, uint32_t reasons
, int enable_disable
)
213 telemetry_task_ctl_locked(task
, reasons
, enable_disable
);
218 telemetry_task_ctl_locked(task_t task
, uint32_t reasons
, int enable_disable
)
222 assert((reasons
!= 0) && ((reasons
| TF_TELEMETRY
) == TF_TELEMETRY
));
224 task_lock_assert_owned(task
);
226 origflags
= task
->t_flags
;
228 if (enable_disable
== 1) {
229 task
->t_flags
|= reasons
;
230 if ((origflags
& TF_TELEMETRY
) == 0) {
231 OSIncrementAtomic(&telemetry_active_tasks
);
233 printf("%s: telemetry OFF -> ON (%d active)\n", proc_name_address(task
->bsd_info
), telemetry_active_tasks
);
237 task
->t_flags
&= ~reasons
;
238 if (((origflags
& TF_TELEMETRY
) != 0) && ((task
->t_flags
& TF_TELEMETRY
) == 0)) {
240 * If this task went from having at least one telemetry bit to having none,
241 * the net change was to disable telemetry for the task.
243 OSDecrementAtomic(&telemetry_active_tasks
);
245 printf("%s: telemetry ON -> OFF (%d active)\n", proc_name_address(task
->bsd_info
), telemetry_active_tasks
);
252 * Determine if the current thread is eligible for telemetry:
254 * telemetry_sample_all_tasks: All threads are eligible. This takes precedence.
255 * telemetry_active_tasks: Count of tasks opted in.
256 * task->t_flags & TF_TELEMETRY: This task is opted in.
259 telemetry_is_active(thread_t thread
)
261 task_t task
= thread
->task
;
263 if (task
== kernel_task
) {
264 /* Kernel threads never return to an AST boundary, and are ineligible */
268 if (telemetry_sample_all_tasks
|| telemetry_sample_pmis
) {
272 if ((telemetry_active_tasks
> 0) && ((thread
->task
->t_flags
& TF_TELEMETRY
) != 0)) {
280 * Userland is arming a timer. If we are eligible for such a record,
281 * sample now. No need to do this one at the AST because we're already at
282 * a safe place in this system call.
285 telemetry_timer_event(__unused
uint64_t deadline
, __unused
uint64_t interval
, __unused
uint64_t leeway
)
287 if (telemetry_needs_timer_arming_record
== TRUE
) {
288 telemetry_needs_timer_arming_record
= FALSE
;
289 telemetry_take_sample(current_thread(), kTimerArmingRecord
| kUserMode
, &telemetry_buffer
);
295 #if defined(MT_CORE_INSTRS) && defined(MT_CORE_CYCLES)
297 telemetry_pmi_handler(bool user_mode
, __unused
void *ctx
)
299 telemetry_mark_curthread(user_mode
, TRUE
);
301 #endif /* defined(MT_CORE_INSTRS) && defined(MT_CORE_CYCLES) */
304 telemetry_pmi_setup(enum telemetry_pmi pmi_ctr
, uint64_t period
)
306 #if defined(MT_CORE_INSTRS) && defined(MT_CORE_CYCLES)
307 static boolean_t sample_all_tasks_aside
= FALSE
;
308 static uint32_t active_tasks_aside
= FALSE
;
310 const char *name
= "?";
312 unsigned int ctr
= 0;
314 TELEMETRY_PMI_LOCK();
317 case TELEMETRY_PMI_NONE
:
318 if (!telemetry_sample_pmis
) {
323 telemetry_sample_pmis
= FALSE
;
324 telemetry_sample_all_tasks
= sample_all_tasks_aside
;
325 telemetry_active_tasks
= active_tasks_aside
;
326 error
= mt_microstackshot_stop();
328 printf("telemetry: disabling ustackshot on PMI\n");
332 case TELEMETRY_PMI_INSTRS
:
333 ctr
= MT_CORE_INSTRS
;
334 name
= "instructions";
337 case TELEMETRY_PMI_CYCLES
:
338 ctr
= MT_CORE_CYCLES
;
347 telemetry_sample_pmis
= TRUE
;
348 sample_all_tasks_aside
= telemetry_sample_all_tasks
;
349 active_tasks_aside
= telemetry_active_tasks
;
350 telemetry_sample_all_tasks
= FALSE
;
351 telemetry_active_tasks
= 0;
353 error
= mt_microstackshot_start(ctr
, period
, telemetry_pmi_handler
, NULL
);
355 printf("telemetry: ustackshot every %llu %s\n", period
, name
);
359 TELEMETRY_PMI_UNLOCK();
361 #else /* defined(MT_CORE_INSTRS) && defined(MT_CORE_CYCLES) */
362 #pragma unused(pmi_ctr, period)
364 #endif /* !defined(MT_CORE_INSTRS) || !defined(MT_CORE_CYCLES) */
368 * Mark the current thread for an interrupt-based
369 * telemetry record, to be sampled at the next AST boundary.
372 telemetry_mark_curthread(boolean_t interrupted_userspace
, boolean_t pmi
)
374 uint32_t ast_bits
= 0;
375 thread_t thread
= current_thread();
378 * If telemetry isn't active for this thread, return and try
381 if (telemetry_is_active(thread
) == FALSE
) {
385 ast_bits
|= (interrupted_userspace
? AST_TELEMETRY_USER
: AST_TELEMETRY_KERNEL
);
387 ast_bits
|= AST_TELEMETRY_PMI
;
390 telemetry_needs_record
= FALSE
;
391 thread_ast_set(thread
, ast_bits
);
392 ast_propagate(thread
);
396 compute_telemetry(void *arg __unused
)
398 if (telemetry_sample_all_tasks
|| (telemetry_active_tasks
> 0)) {
399 if ((++telemetry_timestamp
) % telemetry_sample_rate
== 0) {
400 telemetry_needs_record
= TRUE
;
401 telemetry_needs_timer_arming_record
= TRUE
;
407 * If userland has registered a port for telemetry notifications, send one now.
410 telemetry_notify_user(void)
412 mach_port_t user_port
= MACH_PORT_NULL
;
414 kern_return_t kr
= host_get_telemetry_port(host_priv_self(), &user_port
);
415 if ((kr
!= KERN_SUCCESS
) || !IPC_PORT_VALID(user_port
)) {
419 telemetry_notification(user_port
, 0);
420 ipc_port_release_send(user_port
);
424 telemetry_ast(thread_t thread
, ast_t reasons
)
426 assert((reasons
& AST_TELEMETRY_ALL
) != 0);
428 uint8_t record_type
= 0;
429 if (reasons
& AST_TELEMETRY_IO
) {
430 record_type
|= kIORecord
;
432 if (reasons
& (AST_TELEMETRY_USER
| AST_TELEMETRY_KERNEL
)) {
433 record_type
|= (reasons
& AST_TELEMETRY_PMI
) ? kPMIRecord
:
437 uint8_t user_telemetry
= (reasons
& AST_TELEMETRY_USER
) ? kUserMode
: 0;
439 uint8_t microsnapshot_flags
= record_type
| user_telemetry
;
441 telemetry_take_sample(thread
, microsnapshot_flags
, &telemetry_buffer
);
445 telemetry_take_sample(thread_t thread
, uint8_t microsnapshot_flags
, struct micro_snapshot_buffer
* current_buffer
)
449 uint32_t btcount
= 0, bti
;
450 struct micro_snapshot
*msnap
;
451 struct task_snapshot
*tsnap
;
452 struct thread_snapshot
*thsnap
;
456 uint32_t current_record_start
;
458 boolean_t notify
= FALSE
;
460 if (thread
== THREAD_NULL
) {
465 if ((task
== TASK_NULL
) || (task
== kernel_task
) || task_did_exec(task
) || task_is_exec_copy(task
)) {
469 /* telemetry_XXX accessed outside of lock for instrumentation only */
470 KDBG(MACHDBG_CODE(DBG_MACH_STACKSHOT
, MICROSTACKSHOT_RECORD
) | DBG_FUNC_START
,
471 microsnapshot_flags
, telemetry_bytes_since_last_mark
, 0,
472 (&telemetry_buffer
!= current_buffer
));
474 p
= get_bsdtask_info(task
);
477 * Gather up the data we'll need for this sample. The sample is written into the kernel
478 * buffer with the global telemetry lock held -- so we must do our (possibly faulting)
479 * copies from userland here, before taking the lock.
481 uintptr_t frames
[MAX_CALLSTACK_FRAMES
] = {};
483 int backtrace_error
= backtrace_user(frames
, MAX_CALLSTACK_FRAMES
, &btcount
, &user64
);
484 if (backtrace_error
) {
489 * Find the actual [slid] address of the shared cache's UUID, and copy it in from userland.
491 int shared_cache_uuid_valid
= 0;
492 uint64_t shared_cache_base_address
;
493 struct _dyld_cache_header shared_cache_header
;
494 uint64_t shared_cache_slide
;
497 * Don't copy in the entire shared cache header; we only need the UUID. Calculate the
498 * offset of that one field.
500 int sc_header_uuid_offset
= (char *)&shared_cache_header
.uuid
- (char *)&shared_cache_header
;
501 vm_shared_region_t sr
= vm_shared_region_get(task
);
503 if ((vm_shared_region_start_address(sr
, &shared_cache_base_address
) == KERN_SUCCESS
) &&
504 (copyin(shared_cache_base_address
+ sc_header_uuid_offset
, (char *)&shared_cache_header
.uuid
,
505 sizeof(shared_cache_header
.uuid
)) == 0)) {
506 shared_cache_uuid_valid
= 1;
507 shared_cache_slide
= vm_shared_region_get_slide(sr
);
509 // vm_shared_region_get() gave us a reference on the shared region.
510 vm_shared_region_deallocate(sr
);
514 * Retrieve the array of UUID's for binaries used by this task.
515 * We reach down into DYLD's data structures to find the array.
517 * XXX - make this common with kdp?
519 uint32_t uuid_info_count
= 0;
520 mach_vm_address_t uuid_info_addr
= 0;
521 if (task_has_64Bit_addr(task
)) {
522 struct user64_dyld_all_image_infos task_image_infos
;
523 if (copyin(task
->all_image_info_addr
, (char *)&task_image_infos
, sizeof(task_image_infos
)) == 0) {
524 uuid_info_count
= (uint32_t)task_image_infos
.uuidArrayCount
;
525 uuid_info_addr
= task_image_infos
.uuidArray
;
528 struct user32_dyld_all_image_infos task_image_infos
;
529 if (copyin(task
->all_image_info_addr
, (char *)&task_image_infos
, sizeof(task_image_infos
)) == 0) {
530 uuid_info_count
= task_image_infos
.uuidArrayCount
;
531 uuid_info_addr
= task_image_infos
.uuidArray
;
536 * If we get a NULL uuid_info_addr (which can happen when we catch dyld in the middle of updating
537 * this data structure), we zero the uuid_info_count so that we won't even try to save load info
540 if (!uuid_info_addr
) {
545 * Don't copy in an unbounded amount of memory. The main binary and interesting
546 * non-shared-cache libraries should be in the first few images.
548 if (uuid_info_count
> TELEMETRY_MAX_UUID_COUNT
) {
549 uuid_info_count
= TELEMETRY_MAX_UUID_COUNT
;
552 uint32_t uuid_info_size
= (uint32_t)(task_has_64Bit_addr(thread
->task
) ? sizeof(struct user64_dyld_uuid_info
) : sizeof(struct user32_dyld_uuid_info
));
553 uint32_t uuid_info_array_size
= uuid_info_count
* uuid_info_size
;
554 char *uuid_info_array
= NULL
;
556 if (uuid_info_count
> 0) {
557 if ((uuid_info_array
= (char *)kalloc(uuid_info_array_size
)) == NULL
) {
562 * Copy in the UUID info array.
563 * It may be nonresident, in which case just fix up nloadinfos to 0 in the task snapshot.
565 if (copyin(uuid_info_addr
, uuid_info_array
, uuid_info_array_size
) != 0) {
566 kfree(uuid_info_array
, uuid_info_array_size
);
567 uuid_info_array
= NULL
;
568 uuid_info_array_size
= 0;
573 * Look for a dispatch queue serial number, and copy it in from userland if present.
575 uint64_t dqserialnum
= 0;
576 int dqserialnum_valid
= 0;
578 uint64_t dqkeyaddr
= thread_dispatchqaddr(thread
);
579 if (dqkeyaddr
!= 0) {
581 uint64_t dq_serialno_offset
= get_task_dispatchqueue_serialno_offset(task
);
582 if ((copyin(dqkeyaddr
, (char *)&dqaddr
, (task_has_64Bit_addr(task
) ? 8 : 4)) == 0) &&
583 (dqaddr
!= 0) && (dq_serialno_offset
!= 0)) {
584 uint64_t dqserialnumaddr
= dqaddr
+ dq_serialno_offset
;
585 if (copyin(dqserialnumaddr
, (char *)&dqserialnum
, (task_has_64Bit_addr(task
) ? 8 : 4)) == 0) {
586 dqserialnum_valid
= 1;
591 clock_get_calendar_microtime(&secs
, &usecs
);
596 * If our buffer is not backed by anything,
597 * then we cannot take the sample. Meant to allow us to deallocate the window
598 * buffer if it is disabled.
600 if (!current_buffer
->buffer
) {
605 * We do the bulk of the operation under the telemetry lock, on assumption that
606 * any page faults during execution will not cause another AST_TELEMETRY_ALL
607 * to deadlock; they will just block until we finish. This makes it easier
608 * to copy into the buffer directly. As soon as we unlock, userspace can copy
614 current_record_start
= current_buffer
->current_position
;
616 if ((current_buffer
->size
- current_buffer
->current_position
) < sizeof(struct micro_snapshot
)) {
618 * We can't fit a record in the space available, so wrap around to the beginning.
619 * Save the current position as the known end point of valid data.
621 current_buffer
->end_point
= current_record_start
;
622 current_buffer
->current_position
= 0;
623 if (current_record_start
== 0) {
624 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
630 msnap
= (struct micro_snapshot
*)(uintptr_t)(current_buffer
->buffer
+ current_buffer
->current_position
);
631 msnap
->snapshot_magic
= STACKSHOT_MICRO_SNAPSHOT_MAGIC
;
632 msnap
->ms_flags
= microsnapshot_flags
;
633 msnap
->ms_opaque_flags
= 0; /* namespace managed by userspace */
634 msnap
->ms_cpu
= cpu_number();
635 msnap
->ms_time
= secs
;
636 msnap
->ms_time_microsecs
= usecs
;
638 current_buffer
->current_position
+= sizeof(struct micro_snapshot
);
640 if ((current_buffer
->size
- current_buffer
->current_position
) < sizeof(struct task_snapshot
)) {
641 current_buffer
->end_point
= current_record_start
;
642 current_buffer
->current_position
= 0;
643 if (current_record_start
== 0) {
644 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
650 tsnap
= (struct task_snapshot
*)(uintptr_t)(current_buffer
->buffer
+ current_buffer
->current_position
);
651 bzero(tsnap
, sizeof(*tsnap
));
652 tsnap
->snapshot_magic
= STACKSHOT_TASK_SNAPSHOT_MAGIC
;
653 tsnap
->pid
= proc_pid(p
);
654 tsnap
->uniqueid
= proc_uniqueid(p
);
655 tsnap
->user_time_in_terminated_threads
= task
->total_user_time
;
656 tsnap
->system_time_in_terminated_threads
= task
->total_system_time
;
657 tsnap
->suspend_count
= task
->suspend_count
;
658 tsnap
->task_size
= (typeof(tsnap
->task_size
))(get_task_phys_footprint(task
) / PAGE_SIZE
);
659 tsnap
->faults
= task
->faults
;
660 tsnap
->pageins
= task
->pageins
;
661 tsnap
->cow_faults
= task
->cow_faults
;
663 * The throttling counters are maintained as 64-bit counters in the proc
664 * structure. However, we reserve 32-bits (each) for them in the task_snapshot
665 * struct to save space and since we do not expect them to overflow 32-bits. If we
666 * find these values overflowing in the future, the fix would be to simply
667 * upgrade these counters to 64-bit in the task_snapshot struct
669 tsnap
->was_throttled
= (uint32_t) proc_was_throttled(p
);
670 tsnap
->did_throttle
= (uint32_t) proc_did_throttle(p
);
672 if (task
->t_flags
& TF_TELEMETRY
) {
673 tsnap
->ss_flags
|= kTaskRsrcFlagged
;
676 if (proc_get_effective_task_policy(task
, TASK_POLICY_DARWIN_BG
)) {
677 tsnap
->ss_flags
|= kTaskDarwinBG
;
680 proc_get_darwinbgstate(task
, &tmp
);
682 if (proc_get_effective_task_policy(task
, TASK_POLICY_ROLE
) == TASK_FOREGROUND_APPLICATION
) {
683 tsnap
->ss_flags
|= kTaskIsForeground
;
686 if (tmp
& PROC_FLAG_ADAPTIVE_IMPORTANT
) {
687 tsnap
->ss_flags
|= kTaskIsBoosted
;
690 if (tmp
& PROC_FLAG_SUPPRESSED
) {
691 tsnap
->ss_flags
|= kTaskIsSuppressed
;
694 tsnap
->latency_qos
= task_grab_latency_qos(task
);
696 strlcpy(tsnap
->p_comm
, proc_name_address(p
), sizeof(tsnap
->p_comm
));
697 if (task_has_64Bit_addr(thread
->task
)) {
698 tsnap
->ss_flags
|= kUser64_p
;
701 if (shared_cache_uuid_valid
) {
702 tsnap
->shared_cache_slide
= shared_cache_slide
;
703 bcopy(shared_cache_header
.uuid
, tsnap
->shared_cache_identifier
, sizeof(shared_cache_header
.uuid
));
706 current_buffer
->current_position
+= sizeof(struct task_snapshot
);
709 * Directly after the task snapshot, place the array of UUID's corresponding to the binaries
712 if ((current_buffer
->size
- current_buffer
->current_position
) < uuid_info_array_size
) {
713 current_buffer
->end_point
= current_record_start
;
714 current_buffer
->current_position
= 0;
715 if (current_record_start
== 0) {
716 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
723 * Copy the UUID info array into our sample.
725 if (uuid_info_array_size
> 0) {
726 bcopy(uuid_info_array
, (char *)(current_buffer
->buffer
+ current_buffer
->current_position
), uuid_info_array_size
);
727 tsnap
->nloadinfos
= uuid_info_count
;
730 current_buffer
->current_position
+= uuid_info_array_size
;
733 * After the task snapshot & list of binary UUIDs, we place a thread snapshot.
736 if ((current_buffer
->size
- current_buffer
->current_position
) < sizeof(struct thread_snapshot
)) {
737 /* wrap and overwrite */
738 current_buffer
->end_point
= current_record_start
;
739 current_buffer
->current_position
= 0;
740 if (current_record_start
== 0) {
741 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
747 thsnap
= (struct thread_snapshot
*)(uintptr_t)(current_buffer
->buffer
+ current_buffer
->current_position
);
748 bzero(thsnap
, sizeof(*thsnap
));
750 thsnap
->snapshot_magic
= STACKSHOT_THREAD_SNAPSHOT_MAGIC
;
751 thsnap
->thread_id
= thread_tid(thread
);
752 thsnap
->state
= thread
->state
;
753 thsnap
->priority
= thread
->base_pri
;
754 thsnap
->sched_pri
= thread
->sched_pri
;
755 thsnap
->sched_flags
= thread
->sched_flags
;
756 thsnap
->ss_flags
|= kStacksPCOnly
;
757 thsnap
->ts_qos
= thread
->effective_policy
.thep_qos
;
758 thsnap
->ts_rqos
= thread
->requested_policy
.thrp_qos
;
759 thsnap
->ts_rqos_override
= MAX(thread
->requested_policy
.thrp_qos_override
,
760 thread
->requested_policy
.thrp_qos_workq_override
);
762 if (proc_get_effective_thread_policy(thread
, TASK_POLICY_DARWIN_BG
)) {
763 thsnap
->ss_flags
|= kThreadDarwinBG
;
766 thsnap
->user_time
= timer_grab(&thread
->user_timer
);
768 uint64_t tval
= timer_grab(&thread
->system_timer
);
770 if (thread
->precise_user_kernel_time
) {
771 thsnap
->system_time
= tval
;
773 thsnap
->user_time
+= tval
;
774 thsnap
->system_time
= 0;
777 current_buffer
->current_position
+= sizeof(struct thread_snapshot
);
780 * If this thread has a dispatch queue serial number, include it here.
782 if (dqserialnum_valid
) {
783 if ((current_buffer
->size
- current_buffer
->current_position
) < sizeof(dqserialnum
)) {
784 /* wrap and overwrite */
785 current_buffer
->end_point
= current_record_start
;
786 current_buffer
->current_position
= 0;
787 if (current_record_start
== 0) {
788 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
794 thsnap
->ss_flags
|= kHasDispatchSerial
;
795 bcopy(&dqserialnum
, (char *)current_buffer
->buffer
+ current_buffer
->current_position
, sizeof(dqserialnum
));
796 current_buffer
->current_position
+= sizeof(dqserialnum
);
801 thsnap
->ss_flags
|= kUser64_p
;
807 * If we can't fit this entire stacktrace then cancel this record, wrap to the beginning,
808 * and start again there so that we always store a full record.
810 if ((current_buffer
->size
- current_buffer
->current_position
) / framesize
< btcount
) {
811 current_buffer
->end_point
= current_record_start
;
812 current_buffer
->current_position
= 0;
813 if (current_record_start
== 0) {
814 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
820 for (bti
= 0; bti
< btcount
; bti
++, current_buffer
->current_position
+= framesize
) {
821 if (framesize
== 8) {
822 *(uint64_t *)(uintptr_t)(current_buffer
->buffer
+ current_buffer
->current_position
) = frames
[bti
];
824 *(uint32_t *)(uintptr_t)(current_buffer
->buffer
+ current_buffer
->current_position
) = (uint32_t)frames
[bti
];
828 if (current_buffer
->end_point
< current_buffer
->current_position
) {
830 * Each time the cursor wraps around to the beginning, we leave a
831 * differing amount of unused space at the end of the buffer. Make
832 * sure the cursor pushes the end point in case we're making use of
833 * more of the buffer than we did the last time we wrapped.
835 current_buffer
->end_point
= current_buffer
->current_position
;
838 thsnap
->nuser_frames
= btcount
;
841 * Now THIS is a hack.
843 if (current_buffer
== &telemetry_buffer
) {
844 telemetry_bytes_since_last_mark
+= (current_buffer
->current_position
- current_record_start
);
845 if (telemetry_bytes_since_last_mark
> telemetry_buffer_notify_at
) {
853 KDBG(MACHDBG_CODE(DBG_MACH_STACKSHOT
, MICROSTACKSHOT_RECORD
) | DBG_FUNC_END
,
854 notify
, telemetry_bytes_since_last_mark
,
855 current_buffer
->current_position
, current_buffer
->end_point
);
858 telemetry_notify_user();
861 if (uuid_info_array
!= NULL
) {
862 kfree(uuid_info_array
, uuid_info_array_size
);
868 log_telemetry_output(vm_offset_t buf
, uint32_t pos
, uint32_t sz
)
870 struct micro_snapshot
*p
;
873 printf("Copying out %d bytes of telemetry at offset %d\n", sz
, pos
);
878 * Find and log each timestamp in this chunk of buffer.
880 for (offset
= 0; offset
< sz
; offset
++) {
881 p
= (struct micro_snapshot
*)(buf
+ offset
);
882 if (p
->snapshot_magic
== STACKSHOT_MICRO_SNAPSHOT_MAGIC
) {
883 printf("telemetry timestamp: %lld\n", p
->ms_time
);
890 telemetry_gather(user_addr_t buffer
, uint32_t *length
, boolean_t mark
)
892 return telemetry_buffer_gather(buffer
, length
, mark
, &telemetry_buffer
);
896 telemetry_buffer_gather(user_addr_t buffer
, uint32_t *length
, boolean_t mark
, struct micro_snapshot_buffer
* current_buffer
)
899 uint32_t oldest_record_offset
;
901 KDBG(MACHDBG_CODE(DBG_MACH_STACKSHOT
, MICROSTACKSHOT_GATHER
) | DBG_FUNC_START
,
902 mark
, telemetry_bytes_since_last_mark
, 0,
903 (&telemetry_buffer
!= current_buffer
));
907 if (current_buffer
->buffer
== 0) {
912 if (*length
< current_buffer
->size
) {
913 result
= KERN_NO_SPACE
;
918 * Copy the ring buffer out to userland in order sorted by time: least recent to most recent.
919 * First, we need to search forward from the cursor to find the oldest record in our buffer.
921 oldest_record_offset
= current_buffer
->current_position
;
923 if (((oldest_record_offset
+ sizeof(uint32_t)) > current_buffer
->size
) ||
924 ((oldest_record_offset
+ sizeof(uint32_t)) > current_buffer
->end_point
)) {
925 if (*(uint32_t *)(uintptr_t)(current_buffer
->buffer
) == 0) {
927 * There is no magic number at the start of the buffer, which means
928 * it's empty; nothing to see here yet.
934 * We've looked through the end of the active buffer without finding a valid
935 * record; that means all valid records are in a single chunk, beginning at
936 * the very start of the buffer.
939 oldest_record_offset
= 0;
940 assert(*(uint32_t *)(uintptr_t)(current_buffer
->buffer
) == STACKSHOT_MICRO_SNAPSHOT_MAGIC
);
944 if (*(uint32_t *)(uintptr_t)(current_buffer
->buffer
+ oldest_record_offset
) == STACKSHOT_MICRO_SNAPSHOT_MAGIC
) {
949 * There are no alignment guarantees for micro-stackshot records, so we must search at each
952 oldest_record_offset
++;
953 } while (oldest_record_offset
!= current_buffer
->current_position
);
956 * If needed, copyout in two chunks: from the oldest record to the end of the buffer, and then
957 * from the beginning of the buffer up to the current position.
959 if (oldest_record_offset
!= 0) {
961 log_telemetry_output(current_buffer
->buffer
, oldest_record_offset
,
962 current_buffer
->end_point
- oldest_record_offset
);
964 if ((result
= copyout((void *)(current_buffer
->buffer
+ oldest_record_offset
), buffer
,
965 current_buffer
->end_point
- oldest_record_offset
)) != 0) {
969 *length
= current_buffer
->end_point
- oldest_record_offset
;
975 log_telemetry_output(current_buffer
->buffer
, 0, current_buffer
->current_position
);
977 if ((result
= copyout((void *)current_buffer
->buffer
, buffer
+ *length
,
978 current_buffer
->current_position
)) != 0) {
982 *length
+= (uint32_t)current_buffer
->current_position
;
986 if (mark
&& (*length
> 0)) {
987 telemetry_bytes_since_last_mark
= 0;
992 KDBG(MACHDBG_CODE(DBG_MACH_STACKSHOT
, MICROSTACKSHOT_GATHER
) | DBG_FUNC_END
,
993 current_buffer
->current_position
, *length
,
994 current_buffer
->end_point
, (&telemetry_buffer
!= current_buffer
));
999 /************************/
1000 /* BOOT PROFILE SUPPORT */
1001 /************************/
1005 * The boot-profiling support is a mechanism to sample activity happening on the
1006 * system during boot. This mechanism sets up a periodic timer and on every timer fire,
1007 * captures a full backtrace into the boot profiling buffer. This buffer can be pulled
1008 * out and analyzed from user-space. It is turned on using the following boot-args:
1009 * "bootprofile_buffer_size" specifies the size of the boot profile buffer
1010 * "bootprofile_interval_ms" specifies the interval for the profiling timer
1012 * Process Specific Boot Profiling
1014 * The boot-arg "bootprofile_proc_name" can be used to specify a certain
1015 * process that needs to profiled during boot. Setting this boot-arg changes
1016 * the way stackshots are captured. At every timer fire, the code looks at the
1017 * currently running process and takes a stackshot only if the requested process
1018 * is on-core (which makes it unsuitable for MP systems).
1022 * The boot-arg "bootprofile_type=boot" starts the timer during early boot. Using
1023 * "wake" starts the timer at AP wake from suspend-to-RAM.
1026 #define BOOTPROFILE_MAX_BUFFER_SIZE (64*1024*1024) /* see also COPYSIZELIMIT_PANIC */
1028 vm_offset_t bootprofile_buffer
= 0;
1029 uint32_t bootprofile_buffer_size
= 0;
1030 uint32_t bootprofile_buffer_current_position
= 0;
1031 uint32_t bootprofile_interval_ms
= 0;
1032 uint32_t bootprofile_stackshot_flags
= 0;
1033 uint64_t bootprofile_interval_abs
= 0;
1034 uint64_t bootprofile_next_deadline
= 0;
1035 uint32_t bootprofile_all_procs
= 0;
1036 char bootprofile_proc_name
[17];
1037 uint64_t bootprofile_delta_since_timestamp
= 0;
1038 lck_grp_t bootprofile_lck_grp
;
1039 lck_mtx_t bootprofile_mtx
;
1043 kBootProfileDisabled
= 0,
1044 kBootProfileStartTimerAtBoot
,
1045 kBootProfileStartTimerAtWake
1046 } bootprofile_type
= kBootProfileDisabled
;
1049 static timer_call_data_t bootprofile_timer_call_entry
;
1051 #define BOOTPROFILE_LOCK() do { lck_mtx_lock(&bootprofile_mtx); } while(0)
1052 #define BOOTPROFILE_TRY_SPIN_LOCK() lck_mtx_try_lock_spin(&bootprofile_mtx)
1053 #define BOOTPROFILE_UNLOCK() do { lck_mtx_unlock(&bootprofile_mtx); } while(0)
1055 static void bootprofile_timer_call(
1056 timer_call_param_t param0
,
1057 timer_call_param_t param1
);
1060 bootprofile_init(void)
1065 lck_grp_init(&bootprofile_lck_grp
, "bootprofile group", LCK_GRP_ATTR_NULL
);
1066 lck_mtx_init(&bootprofile_mtx
, &bootprofile_lck_grp
, LCK_ATTR_NULL
);
1068 if (!PE_parse_boot_argn("bootprofile_buffer_size", &bootprofile_buffer_size
, sizeof(bootprofile_buffer_size
))) {
1069 bootprofile_buffer_size
= 0;
1072 if (bootprofile_buffer_size
> BOOTPROFILE_MAX_BUFFER_SIZE
) {
1073 bootprofile_buffer_size
= BOOTPROFILE_MAX_BUFFER_SIZE
;
1076 if (!PE_parse_boot_argn("bootprofile_interval_ms", &bootprofile_interval_ms
, sizeof(bootprofile_interval_ms
))) {
1077 bootprofile_interval_ms
= 0;
1080 if (!PE_parse_boot_argn("bootprofile_stackshot_flags", &bootprofile_stackshot_flags
, sizeof(bootprofile_stackshot_flags
))) {
1081 bootprofile_stackshot_flags
= 0;
1084 if (!PE_parse_boot_argn("bootprofile_proc_name", &bootprofile_proc_name
, sizeof(bootprofile_proc_name
))) {
1085 bootprofile_all_procs
= 1;
1086 bootprofile_proc_name
[0] = '\0';
1089 if (PE_parse_boot_argn("bootprofile_type", type
, sizeof(type
))) {
1090 if (0 == strcmp(type
, "boot")) {
1091 bootprofile_type
= kBootProfileStartTimerAtBoot
;
1092 } else if (0 == strcmp(type
, "wake")) {
1093 bootprofile_type
= kBootProfileStartTimerAtWake
;
1095 bootprofile_type
= kBootProfileDisabled
;
1098 bootprofile_type
= kBootProfileDisabled
;
1101 clock_interval_to_absolutetime_interval(bootprofile_interval_ms
, NSEC_PER_MSEC
, &bootprofile_interval_abs
);
1103 /* Both boot args must be set to enable */
1104 if ((bootprofile_type
== kBootProfileDisabled
) || (bootprofile_buffer_size
== 0) || (bootprofile_interval_abs
== 0)) {
1108 ret
= kmem_alloc(kernel_map
, &bootprofile_buffer
, bootprofile_buffer_size
, VM_KERN_MEMORY_DIAG
);
1109 if (ret
!= KERN_SUCCESS
) {
1110 kprintf("Boot profile: Allocation failed: %d\n", ret
);
1113 bzero((void *) bootprofile_buffer
, bootprofile_buffer_size
);
1115 kprintf("Boot profile: Sampling %s once per %u ms at %s\n", bootprofile_all_procs
? "all procs" : bootprofile_proc_name
, bootprofile_interval_ms
,
1116 bootprofile_type
== kBootProfileStartTimerAtBoot
? "boot" : (bootprofile_type
== kBootProfileStartTimerAtWake
? "wake" : "unknown"));
1118 timer_call_setup(&bootprofile_timer_call_entry
,
1119 bootprofile_timer_call
,
1122 if (bootprofile_type
== kBootProfileStartTimerAtBoot
) {
1123 bootprofile_next_deadline
= mach_absolute_time() + bootprofile_interval_abs
;
1124 timer_call_enter_with_leeway(&bootprofile_timer_call_entry
,
1126 bootprofile_next_deadline
,
1128 TIMER_CALL_SYS_NORMAL
,
1134 bootprofile_wake_from_sleep(void)
1136 if (bootprofile_type
== kBootProfileStartTimerAtWake
) {
1137 bootprofile_next_deadline
= mach_absolute_time() + bootprofile_interval_abs
;
1138 timer_call_enter_with_leeway(&bootprofile_timer_call_entry
,
1140 bootprofile_next_deadline
,
1142 TIMER_CALL_SYS_NORMAL
,
1149 bootprofile_timer_call(
1150 timer_call_param_t param0 __unused
,
1151 timer_call_param_t param1 __unused
)
1153 unsigned retbytes
= 0;
1154 int pid_to_profile
= -1;
1156 if (!BOOTPROFILE_TRY_SPIN_LOCK()) {
1160 /* Check if process-specific boot profiling is turned on */
1161 if (!bootprofile_all_procs
) {
1163 * Since boot profiling initializes really early in boot, it is
1164 * possible that at this point, the task/proc is not initialized.
1165 * Nothing to do in that case.
1168 if ((current_task() != NULL
) && (current_task()->bsd_info
!= NULL
) &&
1169 (0 == strncmp(bootprofile_proc_name
, proc_name_address(current_task()->bsd_info
), 17))) {
1170 pid_to_profile
= proc_selfpid();
1173 * Process-specific boot profiling requested but the on-core process is
1174 * something else. Nothing to do here.
1176 BOOTPROFILE_UNLOCK();
1181 /* initiate a stackshot with whatever portion of the buffer is left */
1182 if (bootprofile_buffer_current_position
< bootprofile_buffer_size
) {
1183 uint32_t flags
= STACKSHOT_KCDATA_FORMAT
| STACKSHOT_TRYLOCK
| STACKSHOT_SAVE_LOADINFO
1184 | STACKSHOT_GET_GLOBAL_MEM_STATS
;
1186 flags
|= STACKSHOT_SAVE_KEXT_LOADINFO
;
1187 #endif /* __x86_64__ */
1190 /* OR on flags specified in boot-args */
1191 flags
|= bootprofile_stackshot_flags
;
1192 if ((flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
) && (bootprofile_delta_since_timestamp
== 0)) {
1193 /* Can't take deltas until the first one */
1194 flags
&= ~STACKSHOT_COLLECT_DELTA_SNAPSHOT
;
1197 uint64_t timestamp
= 0;
1198 if (bootprofile_stackshot_flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
) {
1199 timestamp
= mach_absolute_time();
1202 kern_return_t r
= stack_snapshot_from_kernel(
1203 pid_to_profile
, (void *)(bootprofile_buffer
+ bootprofile_buffer_current_position
),
1204 bootprofile_buffer_size
- bootprofile_buffer_current_position
,
1205 flags
, bootprofile_delta_since_timestamp
, &retbytes
);
1208 * We call with STACKSHOT_TRYLOCK because the stackshot lock is coarser
1209 * than the bootprofile lock. If someone else has the lock we'll just
1213 if (r
== KERN_LOCK_OWNED
) {
1214 BOOTPROFILE_UNLOCK();
1218 if (bootprofile_stackshot_flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
&&
1219 r
== KERN_SUCCESS
) {
1220 bootprofile_delta_since_timestamp
= timestamp
;
1223 bootprofile_buffer_current_position
+= retbytes
;
1226 BOOTPROFILE_UNLOCK();
1228 /* If we didn't get any data or have run out of buffer space, stop profiling */
1229 if ((retbytes
== 0) || (bootprofile_buffer_current_position
== bootprofile_buffer_size
)) {
1235 /* If the user gathered the buffer, no need to keep profiling */
1236 if (bootprofile_interval_abs
== 0) {
1240 clock_deadline_for_periodic_event(bootprofile_interval_abs
,
1241 mach_absolute_time(),
1242 &bootprofile_next_deadline
);
1243 timer_call_enter_with_leeway(&bootprofile_timer_call_entry
,
1245 bootprofile_next_deadline
,
1247 TIMER_CALL_SYS_NORMAL
,
1252 bootprofile_get(void **buffer
, uint32_t *length
)
1255 *buffer
= (void*) bootprofile_buffer
;
1256 *length
= bootprofile_buffer_current_position
;
1257 BOOTPROFILE_UNLOCK();
1261 bootprofile_gather(user_addr_t buffer
, uint32_t *length
)
1267 if (bootprofile_buffer
== 0) {
1272 if (*length
< bootprofile_buffer_current_position
) {
1273 result
= KERN_NO_SPACE
;
1277 if ((result
= copyout((void *)bootprofile_buffer
, buffer
,
1278 bootprofile_buffer_current_position
)) != 0) {
1282 *length
= bootprofile_buffer_current_position
;
1284 /* cancel future timers */
1285 bootprofile_interval_abs
= 0;
1289 BOOTPROFILE_UNLOCK();