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>
46 #include <pexpert/pexpert.h>
48 #include <vm/vm_kern.h>
49 #include <vm/vm_shared_region.h>
51 #include <kperf/kperf.h>
52 #include <kperf/context.h>
53 #include <kperf/callstack.h>
55 #include <sys/kdebug.h>
56 #include <uuid/uuid.h>
57 #include <kdp/kdp_dyld.h>
59 #define TELEMETRY_DEBUG 0
61 extern int proc_pid(void *);
62 extern char *proc_name_address(void *p
);
63 extern uint64_t proc_uniqueid(void *p
);
64 extern uint64_t proc_was_throttled(void *p
);
65 extern uint64_t proc_did_throttle(void *p
);
66 extern uint64_t get_dispatchqueue_serialno_offset_from_proc(void *p
);
67 extern int proc_selfpid(void);
69 struct micro_snapshot_buffer
{
72 uint32_t current_position
;
76 void telemetry_take_sample(thread_t thread
, uint8_t microsnapshot_flags
, struct micro_snapshot_buffer
* current_buffer
);
77 int telemetry_buffer_gather(user_addr_t buffer
, uint32_t *length
, boolean_t mark
, struct micro_snapshot_buffer
* current_buffer
);
79 #define TELEMETRY_DEFAULT_SAMPLE_RATE (1) /* 1 sample every 1 second */
80 #define TELEMETRY_DEFAULT_WINDOW_BUFFER_SIZE (512*1024) /* Should hopefully provide 10 seconds worth of samples */
81 #define TELEMETRY_DEFAULT_BUFFER_SIZE (16*1024)
82 #define TELEMETRY_MAX_BUFFER_SIZE (64*1024)
84 #define TELEMETRY_DEFAULT_NOTIFY_LEEWAY (4*1024) // Userland gets 4k of leeway to collect data after notification
85 #define TELEMETRY_MAX_UUID_COUNT (128) // Max of 128 non-shared-cache UUIDs to log for symbolication
87 uint32_t telemetry_sample_rate
= 0;
88 volatile boolean_t telemetry_needs_record
= FALSE
;
89 volatile boolean_t telemetry_windowed_record
= FALSE
;
90 volatile boolean_t telemetry_needs_timer_arming_record
= FALSE
;
93 * Tells the scheduler that we want it to invoke
94 * compute_telemetry_windowed(); it is still our responsibility
95 * to ensure that we do not panic if someone disables the window
96 * buffer immediately after the scheduler does so.
98 volatile boolean_t telemetry_window_enabled
= FALSE
;
101 * If TRUE, record micro-stackshot samples for all tasks.
102 * If FALSE, only sample tasks which are marked for telemetry.
104 boolean_t telemetry_sample_all_tasks
= FALSE
;
105 uint32_t telemetry_active_tasks
= 0; // Number of tasks opted into telemetry
107 uint32_t telemetry_timestamp
= 0;
110 * We have two buffers. The telemetry_buffer is responsible
111 * for timer samples and interrupt samples that are driven by
112 * compute_averages(). It will notify its client (if one
113 * exists) when it has enough data to be worth flushing.
115 * The window_buffer contains only interrupt_samples that are
116 * driven by the scheduler. Its intent is to provide a
117 * window of recent activity on the cpu(s).
119 struct micro_snapshot_buffer telemetry_buffer
= {0, 0, 0, 0};
120 struct micro_snapshot_buffer window_buffer
= {0, 0, 0, 0};
122 int telemetry_bytes_since_last_mark
= -1; // How much data since buf was last marked?
123 int telemetry_buffer_notify_at
= 0;
125 lck_grp_t telemetry_lck_grp
;
126 lck_mtx_t telemetry_mtx
;
128 #define TELEMETRY_LOCK() do { lck_mtx_lock(&telemetry_mtx); } while(0)
129 #define TELEMETRY_TRY_SPIN_LOCK() lck_mtx_try_lock_spin(&telemetry_mtx)
130 #define TELEMETRY_UNLOCK() do { lck_mtx_unlock(&telemetry_mtx); } while(0)
132 void telemetry_init(void)
135 uint32_t telemetry_notification_leeway
;
137 lck_grp_init(&telemetry_lck_grp
, "telemetry group", LCK_GRP_ATTR_NULL
);
138 lck_mtx_init(&telemetry_mtx
, &telemetry_lck_grp
, LCK_ATTR_NULL
);
140 if (!PE_parse_boot_argn("telemetry_buffer_size", &telemetry_buffer
.size
, sizeof(telemetry_buffer
.size
))) {
141 telemetry_buffer
.size
= TELEMETRY_DEFAULT_BUFFER_SIZE
;
144 if (telemetry_buffer
.size
> TELEMETRY_MAX_BUFFER_SIZE
)
145 telemetry_buffer
.size
= TELEMETRY_MAX_BUFFER_SIZE
;
147 ret
= kmem_alloc(kernel_map
, &telemetry_buffer
.buffer
, telemetry_buffer
.size
, VM_KERN_MEMORY_DIAG
);
148 if (ret
!= KERN_SUCCESS
) {
149 kprintf("Telemetry: Allocation failed: %d\n", ret
);
152 bzero((void *) telemetry_buffer
.buffer
, telemetry_buffer
.size
);
154 if (!PE_parse_boot_argn("telemetry_notification_leeway", &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", &telemetry_sample_rate
, sizeof(telemetry_sample_rate
))) {
168 telemetry_sample_rate
= TELEMETRY_DEFAULT_SAMPLE_RATE
;
172 * To enable telemetry for all tasks, include "telemetry_sample_all_tasks=1" in boot-args.
174 if (!PE_parse_boot_argn("telemetry_sample_all_tasks", &telemetry_sample_all_tasks
, sizeof(telemetry_sample_all_tasks
))) {
176 telemetry_sample_all_tasks
= TRUE
;
180 kprintf("Telemetry: Sampling %stasks once per %u second%s\n",
181 (telemetry_sample_all_tasks
) ? "all " : "",
182 telemetry_sample_rate
, telemetry_sample_rate
== 1 ? "" : "s");
186 * Enable or disable global microstackshots (ie telemetry_sample_all_tasks).
188 * enable_disable == 1: turn it on
189 * enable_disable == 0: turn it off
192 telemetry_global_ctl(int enable_disable
)
194 if (enable_disable
== 1) {
195 telemetry_sample_all_tasks
= TRUE
;
197 telemetry_sample_all_tasks
= FALSE
;
202 * Opt the given task into or out of the telemetry stream.
204 * Supported reasons (callers may use any or all of):
208 * enable_disable == 1: turn it on
209 * enable_disable == 0: turn it off
212 telemetry_task_ctl(task_t task
, uint32_t reasons
, int enable_disable
)
215 telemetry_task_ctl_locked(task
, reasons
, enable_disable
);
220 telemetry_task_ctl_locked(task_t task
, uint32_t reasons
, int enable_disable
)
224 assert((reasons
!= 0) && ((reasons
| TF_TELEMETRY
) == TF_TELEMETRY
));
226 task_lock_assert_owned(task
);
228 origflags
= task
->t_flags
;
230 if (enable_disable
== 1) {
231 task
->t_flags
|= reasons
;
232 if ((origflags
& TF_TELEMETRY
) == 0) {
233 OSIncrementAtomic(&telemetry_active_tasks
);
235 printf("%s: telemetry OFF -> ON (%d active)\n", proc_name_address(task
->bsd_info
), telemetry_active_tasks
);
239 task
->t_flags
&= ~reasons
;
240 if (((origflags
& TF_TELEMETRY
) != 0) && ((task
->t_flags
& TF_TELEMETRY
) == 0)) {
242 * If this task went from having at least one telemetry bit to having none,
243 * the net change was to disable telemetry for the task.
245 OSDecrementAtomic(&telemetry_active_tasks
);
247 printf("%s: telemetry ON -> OFF (%d active)\n", proc_name_address(task
->bsd_info
), telemetry_active_tasks
);
254 * Enable the window_buffer, and do any associated setup.
257 telemetry_enable_window(void)
259 kern_return_t ret
= KERN_SUCCESS
;
260 vm_offset_t kern_buffer
= 0;
261 vm_size_t kern_buffer_size
= TELEMETRY_DEFAULT_WINDOW_BUFFER_SIZE
;
264 * We have no guarantee we won't allocate the buffer, take
265 * the lock, and then discover someone beat us to the punch,
266 * but we would prefer to avoid blocking while holding the
269 ret
= kmem_alloc(kernel_map
, &kern_buffer
, kern_buffer_size
, VM_KERN_MEMORY_DIAG
);
273 if (!window_buffer
.buffer
) {
274 if (ret
== KERN_SUCCESS
) {
275 /* No existing buffer was found, so... */
276 window_buffer
.end_point
= 0;
277 window_buffer
.current_position
= 0;
279 /* Hand off the buffer, and... */
280 window_buffer
.size
= (uint32_t) kern_buffer_size
;
281 window_buffer
.buffer
= kern_buffer
;
283 kern_buffer_size
= 0;
284 bzero((void *) window_buffer
.buffer
, window_buffer
.size
);
286 /* Let the scheduler know it should drive windowed samples */
287 telemetry_window_enabled
= TRUE
;
290 /* We already have a buffer, so we have "succeeded" */
297 kmem_free(kernel_map
, kern_buffer
, kern_buffer_size
);
303 * Disable the window_buffer, and do any associated teardown.
306 telemetry_disable_window(void)
308 vm_offset_t kern_buffer
= 0;
309 vm_size_t kern_buffer_size
= 0;
313 if (window_buffer
.buffer
) {
314 /* We have a window buffer, so tear it down */
315 telemetry_window_enabled
= FALSE
;
316 kern_buffer
= window_buffer
.buffer
;
317 kern_buffer_size
= window_buffer
.size
;
318 window_buffer
.buffer
= 0;
319 window_buffer
.size
= 0;
320 window_buffer
.current_position
= 0;
321 window_buffer
.end_point
= 0;
327 kmem_free(kernel_map
, kern_buffer
, kern_buffer_size
);
331 * Determine if the current thread is eligible for telemetry:
333 * telemetry_sample_all_tasks: All threads are eligible. This takes precedence.
334 * telemetry_active_tasks: Count of tasks opted in.
335 * task->t_flags & TF_TELEMETRY: This task is opted in.
338 telemetry_is_active(thread_t thread
)
340 task_t task
= thread
->task
;
342 if (task
== kernel_task
) {
343 /* Kernel threads never return to an AST boundary, and are ineligible */
347 if (telemetry_sample_all_tasks
== TRUE
) {
351 if ((telemetry_active_tasks
> 0) && ((thread
->task
->t_flags
& TF_TELEMETRY
) != 0)) {
359 * Userland is arming a timer. If we are eligible for such a record,
360 * sample now. No need to do this one at the AST because we're already at
361 * a safe place in this system call.
363 int telemetry_timer_event(__unused
uint64_t deadline
, __unused
uint64_t interval
, __unused
uint64_t leeway
)
365 if (telemetry_needs_timer_arming_record
== TRUE
) {
366 telemetry_needs_timer_arming_record
= FALSE
;
367 telemetry_take_sample(current_thread(), kTimerArmingRecord
| kUserMode
, &telemetry_buffer
);
374 * Mark the current thread for an interrupt-based
375 * telemetry record, to be sampled at the next AST boundary.
377 void telemetry_mark_curthread(boolean_t interrupted_userspace
)
379 uint32_t ast_bits
= 0;
380 thread_t thread
= current_thread();
383 * If telemetry isn't active for this thread, return and try
386 if (telemetry_is_active(thread
) == FALSE
) {
390 ast_bits
|= (interrupted_userspace
? AST_TELEMETRY_USER
: AST_TELEMETRY_KERNEL
);
392 if (telemetry_windowed_record
) {
393 ast_bits
|= AST_TELEMETRY_WINDOWED
;
396 telemetry_windowed_record
= FALSE
;
397 telemetry_needs_record
= FALSE
;
398 thread_ast_set(thread
, ast_bits
);
399 ast_propagate(thread
->ast
);
402 void 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
;
412 void compute_telemetry_windowed(void)
414 if (telemetry_sample_all_tasks
|| (telemetry_active_tasks
> 0)) {
416 * Due to the relationship between the two fields here,
417 * a request for a windowed record will "squash" a
418 * request for a regular interrupt record. We hedge
419 * against this by doing a quick check for an existing
420 * request. compute_telemetry doesn't hedge because
421 * a regular request cannot squash a windowed request
422 * (due to the implementation).
424 * If we really want to do this properly, we could make
425 * telemetry_needs_record a bitfield, and process one
426 * request per telemetry_mark_curthread... but that
427 * would be more expensive (atomics). This should be
428 * robust enough for now (although it biases in favor
429 * of the regular records).
431 if (!telemetry_needs_record
) {
432 telemetry_needs_record
= TRUE
;
433 telemetry_windowed_record
= TRUE
;
439 * If userland has registered a port for telemetry notifications, send one now.
442 telemetry_notify_user(void)
444 mach_port_t user_port
;
448 error
= host_get_telemetry_port(host_priv_self(), &user_port
);
449 if ((error
!= KERN_SUCCESS
) || !IPC_PORT_VALID(user_port
)) {
453 telemetry_notification(user_port
, flags
);
456 void telemetry_ast(thread_t thread
, boolean_t interrupted_userspace
, boolean_t is_windowed
)
458 uint8_t microsnapshot_flags
= kInterruptRecord
;
460 if (interrupted_userspace
)
461 microsnapshot_flags
|= kUserMode
;
464 telemetry_take_sample(thread
, microsnapshot_flags
, &window_buffer
);
466 telemetry_take_sample(thread
, microsnapshot_flags
, &telemetry_buffer
);
470 void telemetry_take_sample(thread_t thread
, uint8_t microsnapshot_flags
, struct micro_snapshot_buffer
* current_buffer
)
474 struct kperf_context ctx
;
476 uint32_t btcount
, bti
;
477 struct micro_snapshot
*msnap
;
478 struct task_snapshot
*tsnap
;
479 struct thread_snapshot
*thsnap
;
483 uint32_t current_record_start
;
485 boolean_t notify
= FALSE
;
487 if (thread
== THREAD_NULL
)
491 if ((task
== TASK_NULL
) || (task
== kernel_task
))
495 * To avoid overloading the system with telemetry requests, make
496 * sure we don't add more requests while existing ones are
497 * in-flight. Attempt this by checking if we can grab the lock.
499 * This concerns me a little; this working as intended is
500 * contingent on the workload being done in the context of the
501 * telemetry lock being the expensive part of telemetry. This
502 * includes populating the buffer and the client gathering it,
503 * but excludes the copyin overhead.
505 if (!TELEMETRY_TRY_SPIN_LOCK())
510 /* telemetry_XXX accessed outside of lock for instrumentation only */
512 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_STACKSHOT
, MICROSTACKSHOT_RECORD
) | DBG_FUNC_START
, microsnapshot_flags
, telemetry_bytes_since_last_mark
, 0, 0, (&telemetry_buffer
!= current_buffer
));
514 p
= get_bsdtask_info(task
);
516 ctx
.cur_thread
= thread
;
517 ctx
.cur_pid
= proc_pid(p
);
520 * Gather up the data we'll need for this sample. The sample is written into the kernel
521 * buffer with the global telemetry lock held -- so we must do our (possibly faulting)
522 * copies from userland here, before taking the lock.
524 kperf_ucallstack_sample(&cs
, &ctx
);
525 if (!(cs
.flags
& CALLSTACK_VALID
))
529 * Find the actual [slid] address of the shared cache's UUID, and copy it in from userland.
531 int shared_cache_uuid_valid
= 0;
532 uint64_t shared_cache_base_address
;
533 struct _dyld_cache_header shared_cache_header
;
534 uint64_t shared_cache_slide
;
537 * Don't copy in the entire shared cache header; we only need the UUID. Calculate the
538 * offset of that one field.
540 int sc_header_uuid_offset
= (char *)&shared_cache_header
.uuid
- (char *)&shared_cache_header
;
541 vm_shared_region_t sr
= vm_shared_region_get(task
);
543 if ((vm_shared_region_start_address(sr
, &shared_cache_base_address
) == KERN_SUCCESS
) &&
544 (copyin(shared_cache_base_address
+ sc_header_uuid_offset
, (char *)&shared_cache_header
.uuid
,
545 sizeof (shared_cache_header
.uuid
)) == 0)) {
546 shared_cache_uuid_valid
= 1;
547 shared_cache_slide
= vm_shared_region_get_slide(sr
);
549 // vm_shared_region_get() gave us a reference on the shared region.
550 vm_shared_region_deallocate(sr
);
554 * Retrieve the array of UUID's for binaries used by this task.
555 * We reach down into DYLD's data structures to find the array.
557 * XXX - make this common with kdp?
559 uint32_t uuid_info_count
= 0;
560 mach_vm_address_t uuid_info_addr
= 0;
561 if (task_has_64BitAddr(task
)) {
562 struct user64_dyld_all_image_infos task_image_infos
;
563 if (copyin(task
->all_image_info_addr
, (char *)&task_image_infos
, sizeof(task_image_infos
)) == 0) {
564 uuid_info_count
= (uint32_t)task_image_infos
.uuidArrayCount
;
565 uuid_info_addr
= task_image_infos
.uuidArray
;
568 struct user32_dyld_all_image_infos task_image_infos
;
569 if (copyin(task
->all_image_info_addr
, (char *)&task_image_infos
, sizeof(task_image_infos
)) == 0) {
570 uuid_info_count
= task_image_infos
.uuidArrayCount
;
571 uuid_info_addr
= task_image_infos
.uuidArray
;
576 * If we get a NULL uuid_info_addr (which can happen when we catch dyld in the middle of updating
577 * this data structure), we zero the uuid_info_count so that we won't even try to save load info
580 if (!uuid_info_addr
) {
585 * Don't copy in an unbounded amount of memory. The main binary and interesting
586 * non-shared-cache libraries should be in the first few images.
588 if (uuid_info_count
> TELEMETRY_MAX_UUID_COUNT
) {
589 uuid_info_count
= TELEMETRY_MAX_UUID_COUNT
;
592 uint32_t uuid_info_size
= (uint32_t)(task_has_64BitAddr(thread
->task
) ? sizeof(struct user64_dyld_uuid_info
) : sizeof(struct user32_dyld_uuid_info
));
593 uint32_t uuid_info_array_size
= uuid_info_count
* uuid_info_size
;
594 char *uuid_info_array
= NULL
;
596 if (uuid_info_count
> 0) {
597 if ((uuid_info_array
= (char *)kalloc(uuid_info_array_size
)) == NULL
) {
602 * Copy in the UUID info array.
603 * It may be nonresident, in which case just fix up nloadinfos to 0 in the task snapshot.
605 if (copyin(uuid_info_addr
, uuid_info_array
, uuid_info_array_size
) != 0) {
606 kfree(uuid_info_array
, uuid_info_array_size
);
607 uuid_info_array
= NULL
;
608 uuid_info_array_size
= 0;
613 * Look for a dispatch queue serial number, and copy it in from userland if present.
615 uint64_t dqserialnum
= 0;
616 int dqserialnum_valid
= 0;
618 uint64_t dqkeyaddr
= thread_dispatchqaddr(thread
);
619 if (dqkeyaddr
!= 0) {
621 uint64_t dq_serialno_offset
= get_dispatchqueue_serialno_offset_from_proc(task
->bsd_info
);
622 if ((copyin(dqkeyaddr
, (char *)&dqaddr
, (task_has_64BitAddr(task
) ? 8 : 4)) == 0) &&
623 (dqaddr
!= 0) && (dq_serialno_offset
!= 0)) {
624 uint64_t dqserialnumaddr
= dqaddr
+ dq_serialno_offset
;
625 if (copyin(dqserialnumaddr
, (char *)&dqserialnum
, (task_has_64BitAddr(task
) ? 8 : 4)) == 0) {
626 dqserialnum_valid
= 1;
631 clock_get_calendar_microtime(&secs
, &usecs
);
636 * For the benefit of the window buffer; if our buffer is not backed by anything,
637 * then we cannot take the sample. Meant to allow us to deallocate the window
638 * buffer if it is disabled.
640 if (!current_buffer
->buffer
)
644 * We do the bulk of the operation under the telemetry lock, on assumption that
645 * any page faults during execution will not cause another AST_TELEMETRY_ALL
646 * to deadlock; they will just block until we finish. This makes it easier
647 * to copy into the buffer directly. As soon as we unlock, userspace can copy
653 current_record_start
= current_buffer
->current_position
;
655 if ((current_buffer
->size
- current_buffer
->current_position
) < sizeof(struct micro_snapshot
)) {
657 * We can't fit a record in the space available, so wrap around to the beginning.
658 * Save the current position as the known end point of valid data.
660 current_buffer
->end_point
= current_record_start
;
661 current_buffer
->current_position
= 0;
662 if (current_record_start
== 0) {
663 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
669 msnap
= (struct micro_snapshot
*)(uintptr_t)(current_buffer
->buffer
+ current_buffer
->current_position
);
670 msnap
->snapshot_magic
= STACKSHOT_MICRO_SNAPSHOT_MAGIC
;
671 msnap
->ms_flags
= microsnapshot_flags
;
672 msnap
->ms_opaque_flags
= 0; /* namespace managed by userspace */
673 msnap
->ms_cpu
= 0; /* XXX - does this field make sense for a micro-stackshot? */
674 msnap
->ms_time
= secs
;
675 msnap
->ms_time_microsecs
= usecs
;
677 current_buffer
->current_position
+= sizeof(struct micro_snapshot
);
679 if ((current_buffer
->size
- current_buffer
->current_position
) < sizeof(struct task_snapshot
)) {
680 current_buffer
->end_point
= current_record_start
;
681 current_buffer
->current_position
= 0;
682 if (current_record_start
== 0) {
683 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
689 tsnap
= (struct task_snapshot
*)(uintptr_t)(current_buffer
->buffer
+ current_buffer
->current_position
);
690 bzero(tsnap
, sizeof(*tsnap
));
691 tsnap
->snapshot_magic
= STACKSHOT_TASK_SNAPSHOT_MAGIC
;
692 tsnap
->pid
= proc_pid(p
);
693 tsnap
->uniqueid
= proc_uniqueid(p
);
694 tsnap
->user_time_in_terminated_threads
= task
->total_user_time
;
695 tsnap
->system_time_in_terminated_threads
= task
->total_system_time
;
696 tsnap
->suspend_count
= task
->suspend_count
;
697 tsnap
->task_size
= pmap_resident_count(task
->map
->pmap
);
698 tsnap
->faults
= task
->faults
;
699 tsnap
->pageins
= task
->pageins
;
700 tsnap
->cow_faults
= task
->cow_faults
;
702 * The throttling counters are maintained as 64-bit counters in the proc
703 * structure. However, we reserve 32-bits (each) for them in the task_snapshot
704 * struct to save space and since we do not expect them to overflow 32-bits. If we
705 * find these values overflowing in the future, the fix would be to simply
706 * upgrade these counters to 64-bit in the task_snapshot struct
708 tsnap
->was_throttled
= (uint32_t) proc_was_throttled(p
);
709 tsnap
->did_throttle
= (uint32_t) proc_did_throttle(p
);
711 if (task
->t_flags
& TF_TELEMETRY
) {
712 tsnap
->ss_flags
|= kTaskRsrcFlagged
;
715 if (task
->effective_policy
.darwinbg
== 1) {
716 tsnap
->ss_flags
|= kTaskDarwinBG
;
719 proc_get_darwinbgstate(task
, &tmp
);
721 if (task
->requested_policy
.t_role
== TASK_FOREGROUND_APPLICATION
) {
722 tsnap
->ss_flags
|= kTaskIsForeground
;
725 if (tmp
& PROC_FLAG_ADAPTIVE_IMPORTANT
) {
726 tsnap
->ss_flags
|= kTaskIsBoosted
;
729 if (tmp
& PROC_FLAG_SUPPRESSED
) {
730 tsnap
->ss_flags
|= kTaskIsSuppressed
;
733 tsnap
->latency_qos
= task_grab_latency_qos(task
);
735 strlcpy(tsnap
->p_comm
, proc_name_address(p
), sizeof(tsnap
->p_comm
));
736 if (task_has_64BitAddr(thread
->task
)) {
737 tsnap
->ss_flags
|= kUser64_p
;
740 if (shared_cache_uuid_valid
) {
741 tsnap
->shared_cache_slide
= shared_cache_slide
;
742 bcopy(shared_cache_header
.uuid
, tsnap
->shared_cache_identifier
, sizeof (shared_cache_header
.uuid
));
745 current_buffer
->current_position
+= sizeof(struct task_snapshot
);
748 * Directly after the task snapshot, place the array of UUID's corresponding to the binaries
751 if ((current_buffer
->size
- current_buffer
->current_position
) < uuid_info_array_size
) {
752 current_buffer
->end_point
= current_record_start
;
753 current_buffer
->current_position
= 0;
754 if (current_record_start
== 0) {
755 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
762 * Copy the UUID info array into our sample.
764 if (uuid_info_array_size
> 0) {
765 bcopy(uuid_info_array
, (char *)(current_buffer
->buffer
+ current_buffer
->current_position
), uuid_info_array_size
);
766 tsnap
->nloadinfos
= uuid_info_count
;
769 current_buffer
->current_position
+= uuid_info_array_size
;
772 * After the task snapshot & list of binary UUIDs, we place a thread snapshot.
775 if ((current_buffer
->size
- current_buffer
->current_position
) < sizeof(struct thread_snapshot
)) {
776 /* wrap and overwrite */
777 current_buffer
->end_point
= current_record_start
;
778 current_buffer
->current_position
= 0;
779 if (current_record_start
== 0) {
780 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
786 thsnap
= (struct thread_snapshot
*)(uintptr_t)(current_buffer
->buffer
+ current_buffer
->current_position
);
787 bzero(thsnap
, sizeof(*thsnap
));
789 thsnap
->snapshot_magic
= STACKSHOT_THREAD_SNAPSHOT_MAGIC
;
790 thsnap
->thread_id
= thread_tid(thread
);
791 thsnap
->state
= thread
->state
;
792 thsnap
->priority
= thread
->base_pri
;
793 thsnap
->sched_pri
= thread
->sched_pri
;
794 thsnap
->sched_flags
= thread
->sched_flags
;
795 thsnap
->ss_flags
|= kStacksPCOnly
;
796 thsnap
->ts_qos
= thread
->effective_policy
.thep_qos
;
797 thsnap
->ts_rqos
= thread
->requested_policy
.thrp_qos
;
798 thsnap
->ts_rqos_override
= thread
->requested_policy
.thrp_qos_override
;
800 if (thread
->effective_policy
.darwinbg
) {
801 thsnap
->ss_flags
|= kThreadDarwinBG
;
804 thsnap
->user_time
= timer_grab(&thread
->user_timer
);
806 uint64_t tval
= timer_grab(&thread
->system_timer
);
808 if (thread
->precise_user_kernel_time
) {
809 thsnap
->system_time
= tval
;
811 thsnap
->user_time
+= tval
;
812 thsnap
->system_time
= 0;
815 current_buffer
->current_position
+= sizeof(struct thread_snapshot
);
818 * If this thread has a dispatch queue serial number, include it here.
820 if (dqserialnum_valid
) {
821 if ((current_buffer
->size
- current_buffer
->current_position
) < sizeof(dqserialnum
)) {
822 /* wrap and overwrite */
823 current_buffer
->end_point
= current_record_start
;
824 current_buffer
->current_position
= 0;
825 if (current_record_start
== 0) {
826 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
832 thsnap
->ss_flags
|= kHasDispatchSerial
;
833 bcopy(&dqserialnum
, (char *)current_buffer
->buffer
+ current_buffer
->current_position
, sizeof (dqserialnum
));
834 current_buffer
->current_position
+= sizeof (dqserialnum
);
837 if (task_has_64BitAddr(task
)) {
839 thsnap
->ss_flags
|= kUser64_p
;
844 btcount
= cs
.nframes
;
847 * If we can't fit this entire stacktrace then cancel this record, wrap to the beginning,
848 * and start again there so that we always store a full record.
850 if ((current_buffer
->size
- current_buffer
->current_position
)/framesize
< btcount
) {
851 current_buffer
->end_point
= current_record_start
;
852 current_buffer
->current_position
= 0;
853 if (current_record_start
== 0) {
854 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
860 for (bti
=0; bti
< btcount
; bti
++, current_buffer
->current_position
+= framesize
) {
861 if (framesize
== 8) {
862 *(uint64_t *)(uintptr_t)(current_buffer
->buffer
+ current_buffer
->current_position
) = cs
.frames
[bti
];
864 *(uint32_t *)(uintptr_t)(current_buffer
->buffer
+ current_buffer
->current_position
) = (uint32_t)cs
.frames
[bti
];
868 if (current_buffer
->end_point
< current_buffer
->current_position
) {
870 * Each time the cursor wraps around to the beginning, we leave a
871 * differing amount of unused space at the end of the buffer. Make
872 * sure the cursor pushes the end point in case we're making use of
873 * more of the buffer than we did the last time we wrapped.
875 current_buffer
->end_point
= current_buffer
->current_position
;
878 thsnap
->nuser_frames
= btcount
;
881 * Now THIS is a hack.
883 if (current_buffer
== &telemetry_buffer
) {
884 telemetry_bytes_since_last_mark
+= (current_buffer
->current_position
- current_record_start
);
885 if (telemetry_bytes_since_last_mark
> telemetry_buffer_notify_at
) {
895 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_STACKSHOT
, MICROSTACKSHOT_RECORD
) | DBG_FUNC_END
, notify
, telemetry_bytes_since_last_mark
, current_buffer
->current_position
, current_buffer
->end_point
, (&telemetry_buffer
!= current_buffer
));
898 telemetry_notify_user();
901 if (uuid_info_array
!= NULL
) {
902 kfree(uuid_info_array
, uuid_info_array_size
);
908 log_telemetry_output(vm_offset_t buf
, uint32_t pos
, uint32_t sz
)
910 struct micro_snapshot
*p
;
913 printf("Copying out %d bytes of telemetry at offset %d\n", sz
, pos
);
918 * Find and log each timestamp in this chunk of buffer.
920 for (offset
= 0; offset
< sz
; offset
++) {
921 p
= (struct micro_snapshot
*)(buf
+ offset
);
922 if (p
->snapshot_magic
== STACKSHOT_MICRO_SNAPSHOT_MAGIC
) {
923 printf("telemetry timestamp: %lld\n", p
->ms_time
);
929 int telemetry_gather(user_addr_t buffer
, uint32_t *length
, boolean_t mark
)
931 return telemetry_buffer_gather(buffer
, length
, mark
, &telemetry_buffer
);
934 int telemetry_gather_windowed(user_addr_t buffer
, uint32_t *length
)
936 return telemetry_buffer_gather(buffer
, length
, 0, &window_buffer
);
939 int telemetry_buffer_gather(user_addr_t buffer
, uint32_t *length
, boolean_t mark
, struct micro_snapshot_buffer
* current_buffer
)
942 uint32_t oldest_record_offset
;
945 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_STACKSHOT
, MICROSTACKSHOT_GATHER
) | DBG_FUNC_START
, mark
, telemetry_bytes_since_last_mark
, 0, 0, (&telemetry_buffer
!= current_buffer
));
949 if (current_buffer
->buffer
== 0) {
954 if (*length
< current_buffer
->size
) {
955 result
= KERN_NO_SPACE
;
960 * Copy the ring buffer out to userland in order sorted by time: least recent to most recent.
961 * First, we need to search forward from the cursor to find the oldest record in our buffer.
963 oldest_record_offset
= current_buffer
->current_position
;
965 if (((oldest_record_offset
+ sizeof(uint32_t)) > current_buffer
->size
) ||
966 ((oldest_record_offset
+ sizeof(uint32_t)) > current_buffer
->end_point
)) {
968 if (*(uint32_t *)(uintptr_t)(current_buffer
->buffer
) == 0) {
970 * There is no magic number at the start of the buffer, which means
971 * it's empty; nothing to see here yet.
977 * We've looked through the end of the active buffer without finding a valid
978 * record; that means all valid records are in a single chunk, beginning at
979 * the very start of the buffer.
982 oldest_record_offset
= 0;
983 assert(*(uint32_t *)(uintptr_t)(current_buffer
->buffer
) == STACKSHOT_MICRO_SNAPSHOT_MAGIC
);
987 if (*(uint32_t *)(uintptr_t)(current_buffer
->buffer
+ oldest_record_offset
) == STACKSHOT_MICRO_SNAPSHOT_MAGIC
)
991 * There are no alignment guarantees for micro-stackshot records, so we must search at each
994 oldest_record_offset
++;
995 } while (oldest_record_offset
!= current_buffer
->current_position
);
998 * If needed, copyout in two chunks: from the oldest record to the end of the buffer, and then
999 * from the beginning of the buffer up to the current position.
1001 if (oldest_record_offset
!= 0) {
1003 log_telemetry_output(current_buffer
->buffer
, oldest_record_offset
,
1004 current_buffer
->end_point
- oldest_record_offset
);
1006 if ((result
= copyout((void *)(current_buffer
->buffer
+ oldest_record_offset
), buffer
,
1007 current_buffer
->end_point
- oldest_record_offset
)) != 0) {
1011 *length
= current_buffer
->end_point
- oldest_record_offset
;
1017 log_telemetry_output(current_buffer
->buffer
, 0, current_buffer
->current_position
);
1019 if ((result
= copyout((void *)current_buffer
->buffer
, buffer
+ *length
,
1020 current_buffer
->current_position
)) != 0) {
1024 *length
+= (uint32_t)current_buffer
->current_position
;
1028 if (mark
&& (*length
> 0)) {
1029 telemetry_bytes_since_last_mark
= 0;
1034 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_STACKSHOT
, MICROSTACKSHOT_GATHER
) | DBG_FUNC_END
, current_buffer
->current_position
, *length
, current_buffer
->end_point
, 0, (&telemetry_buffer
!= current_buffer
));
1039 /************************/
1040 /* BOOT PROFILE SUPPORT */
1041 /************************/
1045 * The boot-profiling support is a mechanism to sample activity happening on the
1046 * system during boot. This mechanism sets up a periodic timer and on every timer fire,
1047 * captures a full backtrace into the boot profiling buffer. This buffer can be pulled
1048 * out and analyzed from user-space. It is turned on using the following boot-args:
1049 * "bootprofile_buffer_size" specifies the size of the boot profile buffer
1050 * "bootprofile_interval_ms" specifies the interval for the profiling timer
1052 * Process Specific Boot Profiling
1054 * The boot-arg "bootprofile_proc_name" can be used to specify a certain
1055 * process that needs to profiled during boot. Setting this boot-arg changes
1056 * the way stackshots are captured. At every timer fire, the code looks at the
1057 * currently running process and takes a stackshot only if the requested process
1058 * is on-core (which makes it unsuitable for MP systems).
1062 * The boot-arg "bootprofile_type=boot" starts the timer during early boot. Using
1063 * "wake" starts the timer at AP wake from suspend-to-RAM.
1066 #define BOOTPROFILE_MAX_BUFFER_SIZE (64*1024*1024) /* see also COPYSIZELIMIT_PANIC */
1068 vm_offset_t bootprofile_buffer
= 0;
1069 uint32_t bootprofile_buffer_size
= 0;
1070 uint32_t bootprofile_buffer_current_position
= 0;
1071 uint32_t bootprofile_interval_ms
= 0;
1072 uint64_t bootprofile_interval_abs
= 0;
1073 uint64_t bootprofile_next_deadline
= 0;
1074 uint32_t bootprofile_all_procs
= 0;
1075 char bootprofile_proc_name
[17];
1077 lck_grp_t bootprofile_lck_grp
;
1078 lck_mtx_t bootprofile_mtx
;
1081 kBootProfileDisabled
= 0,
1082 kBootProfileStartTimerAtBoot
,
1083 kBootProfileStartTimerAtWake
1084 } bootprofile_type
= kBootProfileDisabled
;
1087 static timer_call_data_t bootprofile_timer_call_entry
;
1089 #define BOOTPROFILE_LOCK() do { lck_mtx_lock(&bootprofile_mtx); } while(0)
1090 #define BOOTPROFILE_TRY_SPIN_LOCK() lck_mtx_try_lock_spin(&bootprofile_mtx)
1091 #define BOOTPROFILE_UNLOCK() do { lck_mtx_unlock(&bootprofile_mtx); } while(0)
1093 static void bootprofile_timer_call(
1094 timer_call_param_t param0
,
1095 timer_call_param_t param1
);
1098 stack_snapshot_from_kernel(int pid
, void *buf
, uint32_t size
, uint32_t flags
, unsigned *retbytes
);
1100 void bootprofile_init(void)
1105 lck_grp_init(&bootprofile_lck_grp
, "bootprofile group", LCK_GRP_ATTR_NULL
);
1106 lck_mtx_init(&bootprofile_mtx
, &bootprofile_lck_grp
, LCK_ATTR_NULL
);
1108 if (!PE_parse_boot_argn("bootprofile_buffer_size", &bootprofile_buffer_size
, sizeof(bootprofile_buffer_size
))) {
1109 bootprofile_buffer_size
= 0;
1112 if (bootprofile_buffer_size
> BOOTPROFILE_MAX_BUFFER_SIZE
)
1113 bootprofile_buffer_size
= BOOTPROFILE_MAX_BUFFER_SIZE
;
1115 if (!PE_parse_boot_argn("bootprofile_interval_ms", &bootprofile_interval_ms
, sizeof(bootprofile_interval_ms
))) {
1116 bootprofile_interval_ms
= 0;
1119 if (!PE_parse_boot_argn("bootprofile_proc_name", &bootprofile_proc_name
, sizeof(bootprofile_proc_name
))) {
1120 bootprofile_all_procs
= 1;
1121 bootprofile_proc_name
[0] = '\0';
1124 if (PE_parse_boot_argn("bootprofile_type", type
, sizeof(type
))) {
1125 if (0 == strcmp(type
, "boot")) {
1126 bootprofile_type
= kBootProfileStartTimerAtBoot
;
1127 } else if (0 == strcmp(type
, "wake")) {
1128 bootprofile_type
= kBootProfileStartTimerAtWake
;
1130 bootprofile_type
= kBootProfileDisabled
;
1133 bootprofile_type
= kBootProfileDisabled
;
1136 clock_interval_to_absolutetime_interval(bootprofile_interval_ms
, NSEC_PER_MSEC
, &bootprofile_interval_abs
);
1138 /* Both boot args must be set to enable */
1139 if ((bootprofile_type
== kBootProfileDisabled
) || (bootprofile_buffer_size
== 0) || (bootprofile_interval_abs
== 0)) {
1143 ret
= kmem_alloc(kernel_map
, &bootprofile_buffer
, bootprofile_buffer_size
, VM_KERN_MEMORY_DIAG
);
1144 if (ret
!= KERN_SUCCESS
) {
1145 kprintf("Boot profile: Allocation failed: %d\n", ret
);
1148 bzero((void *) bootprofile_buffer
, bootprofile_buffer_size
);
1150 kprintf("Boot profile: Sampling %s once per %u ms at %s\n", bootprofile_all_procs
? "all procs" : bootprofile_proc_name
, bootprofile_interval_ms
,
1151 bootprofile_type
== kBootProfileStartTimerAtBoot
? "boot" : (bootprofile_type
== kBootProfileStartTimerAtWake
? "wake" : "unknown"));
1153 timer_call_setup(&bootprofile_timer_call_entry
,
1154 bootprofile_timer_call
,
1157 if (bootprofile_type
== kBootProfileStartTimerAtBoot
) {
1158 bootprofile_next_deadline
= mach_absolute_time() + bootprofile_interval_abs
;
1159 timer_call_enter_with_leeway(&bootprofile_timer_call_entry
,
1161 bootprofile_next_deadline
,
1163 TIMER_CALL_SYS_NORMAL
,
1169 bootprofile_wake_from_sleep(void)
1171 if (bootprofile_type
== kBootProfileStartTimerAtWake
) {
1172 bootprofile_next_deadline
= mach_absolute_time() + bootprofile_interval_abs
;
1173 timer_call_enter_with_leeway(&bootprofile_timer_call_entry
,
1175 bootprofile_next_deadline
,
1177 TIMER_CALL_SYS_NORMAL
,
1183 static void bootprofile_timer_call(
1184 timer_call_param_t param0 __unused
,
1185 timer_call_param_t param1 __unused
)
1187 unsigned retbytes
= 0;
1188 int pid_to_profile
= -1;
1190 if (!BOOTPROFILE_TRY_SPIN_LOCK()) {
1194 /* Check if process-specific boot profiling is turned on */
1195 if (!bootprofile_all_procs
) {
1197 * Since boot profiling initializes really early in boot, it is
1198 * possible that at this point, the task/proc is not initialized.
1199 * Nothing to do in that case.
1202 if ((current_task() != NULL
) && (current_task()->bsd_info
!= NULL
) &&
1203 (0 == strncmp(bootprofile_proc_name
, proc_name_address(current_task()->bsd_info
), 17))) {
1204 pid_to_profile
= proc_selfpid();
1208 * Process-specific boot profiling requested but the on-core process is
1209 * something else. Nothing to do here.
1211 BOOTPROFILE_UNLOCK();
1216 /* initiate a stackshot with whatever portion of the buffer is left */
1217 if (bootprofile_buffer_current_position
< bootprofile_buffer_size
) {
1218 stack_snapshot_from_kernel(
1220 (void *)(bootprofile_buffer
+ bootprofile_buffer_current_position
),
1221 bootprofile_buffer_size
- bootprofile_buffer_current_position
,
1222 STACKSHOT_SAVE_LOADINFO
| STACKSHOT_SAVE_KEXT_LOADINFO
| STACKSHOT_GET_GLOBAL_MEM_STATS
,
1226 bootprofile_buffer_current_position
+= retbytes
;
1229 BOOTPROFILE_UNLOCK();
1231 /* If we didn't get any data or have run out of buffer space, stop profiling */
1232 if ((retbytes
== 0) || (bootprofile_buffer_current_position
== bootprofile_buffer_size
)) {
1238 /* If the user gathered the buffer, no need to keep profiling */
1239 if (bootprofile_interval_abs
== 0) {
1243 clock_deadline_for_periodic_event(bootprofile_interval_abs
,
1244 mach_absolute_time(),
1245 &bootprofile_next_deadline
);
1246 timer_call_enter_with_leeway(&bootprofile_timer_call_entry
,
1248 bootprofile_next_deadline
,
1250 TIMER_CALL_SYS_NORMAL
,
1254 int bootprofile_gather(user_addr_t buffer
, uint32_t *length
)
1260 if (bootprofile_buffer
== 0) {
1265 if (*length
< bootprofile_buffer_current_position
) {
1266 result
= KERN_NO_SPACE
;
1270 if ((result
= copyout((void *)bootprofile_buffer
, buffer
,
1271 bootprofile_buffer_current_position
)) != 0) {
1275 *length
= bootprofile_buffer_current_position
;
1277 /* cancel future timers */
1278 bootprofile_interval_abs
= 0;
1282 BOOTPROFILE_UNLOCK();