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 void telemetry_take_sample(thread_t thread
, uint8_t microsnapshot_flags
);
71 #define TELEMETRY_DEFAULT_SAMPLE_RATE (1) /* 1 sample every 1 second */
72 #define TELEMETRY_DEFAULT_BUFFER_SIZE (16*1024)
73 #define TELEMETRY_MAX_BUFFER_SIZE (64*1024)
75 #define TELEMETRY_DEFAULT_NOTIFY_LEEWAY (4*1024) // Userland gets 4k of leeway to collect data after notification
77 uint32_t telemetry_sample_rate
= 0;
78 volatile boolean_t telemetry_needs_record
= FALSE
;
79 volatile boolean_t telemetry_needs_timer_arming_record
= FALSE
;
82 * If TRUE, record micro-stackshot samples for all tasks.
83 * If FALSE, only sample tasks which are marked for telemetry.
85 boolean_t telemetry_sample_all_tasks
= FALSE
;
86 uint32_t telemetry_active_tasks
= 0; // Number of tasks opted into telemetry
88 uint32_t telemetry_timestamp
= 0;
90 vm_offset_t telemetry_buffer
= 0;
91 uint32_t telemetry_buffer_size
= 0;
92 uint32_t telemetry_buffer_current_position
= 0;
93 uint32_t telemetry_buffer_end_point
= 0; // If we've wrapped, where does the last record end?
94 int telemetry_bytes_since_last_mark
= -1; // How much data since buf was last marked?
95 int telemetry_buffer_notify_at
= 0;
97 lck_grp_t telemetry_lck_grp
;
98 lck_mtx_t telemetry_mtx
;
100 #define TELEMETRY_LOCK() do { lck_mtx_lock(&telemetry_mtx); } while(0)
101 #define TELEMETRY_TRY_SPIN_LOCK() lck_mtx_try_lock_spin(&telemetry_mtx)
102 #define TELEMETRY_UNLOCK() do { lck_mtx_unlock(&telemetry_mtx); } while(0)
104 void telemetry_init(void)
107 uint32_t telemetry_notification_leeway
;
109 lck_grp_init(&telemetry_lck_grp
, "telemetry group", LCK_GRP_ATTR_NULL
);
110 lck_mtx_init(&telemetry_mtx
, &telemetry_lck_grp
, LCK_ATTR_NULL
);
112 if (!PE_parse_boot_argn("telemetry_buffer_size", &telemetry_buffer_size
, sizeof(telemetry_buffer_size
))) {
113 telemetry_buffer_size
= TELEMETRY_DEFAULT_BUFFER_SIZE
;
116 if (telemetry_buffer_size
> TELEMETRY_MAX_BUFFER_SIZE
)
117 telemetry_buffer_size
= TELEMETRY_MAX_BUFFER_SIZE
;
119 ret
= kmem_alloc(kernel_map
, &telemetry_buffer
, telemetry_buffer_size
);
120 if (ret
!= KERN_SUCCESS
) {
121 kprintf("Telemetry: Allocation failed: %d\n", ret
);
125 if (!PE_parse_boot_argn("telemetry_notification_leeway", &telemetry_notification_leeway
, sizeof(telemetry_notification_leeway
))) {
127 * By default, notify the user to collect the buffer when there is this much space left in the buffer.
129 telemetry_notification_leeway
= TELEMETRY_DEFAULT_NOTIFY_LEEWAY
;
131 if (telemetry_notification_leeway
>= telemetry_buffer_size
) {
132 printf("telemetry: nonsensical telemetry_notification_leeway boot-arg %d changed to %d\n",
133 telemetry_notification_leeway
, TELEMETRY_DEFAULT_NOTIFY_LEEWAY
);
134 telemetry_notification_leeway
= TELEMETRY_DEFAULT_NOTIFY_LEEWAY
;
136 telemetry_buffer_notify_at
= telemetry_buffer_size
- telemetry_notification_leeway
;
138 if (!PE_parse_boot_argn("telemetry_sample_rate", &telemetry_sample_rate
, sizeof(telemetry_sample_rate
))) {
139 telemetry_sample_rate
= TELEMETRY_DEFAULT_SAMPLE_RATE
;
143 * To enable telemetry for all tasks, include "telemetry_sample_all_tasks=1" in boot-args.
145 if (!PE_parse_boot_argn("telemetry_sample_all_tasks", &telemetry_sample_all_tasks
, sizeof(telemetry_sample_all_tasks
))) {
147 telemetry_sample_all_tasks
= TRUE
;
151 kprintf("Telemetry: Sampling %stasks once per %u second%s\n",
152 (telemetry_sample_all_tasks
) ? "all " : "",
153 telemetry_sample_rate
, telemetry_sample_rate
== 1 ? "" : "s");
157 * Enable or disable global microstackshots (ie telemetry_sample_all_tasks).
159 * enable_disable == 1: turn it on
160 * enable_disable == 0: turn it off
163 telemetry_global_ctl(int enable_disable
)
165 if (enable_disable
== 1) {
166 telemetry_sample_all_tasks
= TRUE
;
168 telemetry_sample_all_tasks
= FALSE
;
173 * Opt the given task into or out of the telemetry stream.
175 * Supported reasons (callers may use any or all of):
179 * enable_disable == 1: turn it on
180 * enable_disable == 0: turn it off
183 telemetry_task_ctl(task_t task
, uint32_t reasons
, int enable_disable
)
186 telemetry_task_ctl_locked(task
, reasons
, enable_disable
);
191 telemetry_task_ctl_locked(task_t task
, uint32_t reasons
, int enable_disable
)
195 assert((reasons
!= 0) && ((reasons
| TF_TELEMETRY
) == TF_TELEMETRY
));
197 task_lock_assert_owned(task
);
199 origflags
= task
->t_flags
;
201 if (enable_disable
== 1) {
202 task
->t_flags
|= reasons
;
203 if ((origflags
& TF_TELEMETRY
) == 0) {
204 OSIncrementAtomic(&telemetry_active_tasks
);
206 printf("%s: telemetry OFF -> ON (%d active)\n", proc_name_address(task
->bsd_info
), telemetry_active_tasks
);
210 task
->t_flags
&= ~reasons
;
211 if (((origflags
& TF_TELEMETRY
) != 0) && ((task
->t_flags
& TF_TELEMETRY
) == 0)) {
213 * If this task went from having at least one telemetry bit to having none,
214 * the net change was to disable telemetry for the task.
216 OSDecrementAtomic(&telemetry_active_tasks
);
218 printf("%s: telemetry ON -> OFF (%d active)\n", proc_name_address(task
->bsd_info
), telemetry_active_tasks
);
225 * Determine if the current thread is eligible for telemetry:
227 * telemetry_sample_all_tasks: All threads are eligible. This takes precedence.
228 * telemetry_active_tasks: Count of tasks opted in.
229 * task->t_flags & TF_TELEMETRY: This task is opted in.
232 telemetry_is_active(thread_t thread
)
234 if (telemetry_sample_all_tasks
== TRUE
) {
238 if ((telemetry_active_tasks
> 0) && ((thread
->task
->t_flags
& TF_TELEMETRY
) != 0)) {
246 * Userland is arming a timer. If we are eligible for such a record,
247 * sample now. No need to do this one at the AST because we're already at
248 * a safe place in this system call.
250 int telemetry_timer_event(__unused
uint64_t deadline
, __unused
uint64_t interval
, __unused
uint64_t leeway
)
252 if (telemetry_needs_timer_arming_record
== TRUE
) {
253 telemetry_needs_timer_arming_record
= FALSE
;
254 telemetry_take_sample(current_thread(), kTimerArmingRecord
| kUserMode
);
261 * Mark the current thread for an interrupt-based
262 * telemetry record, to be sampled at the next AST boundary.
264 void telemetry_mark_curthread(boolean_t interrupted_userspace
)
266 thread_t thread
= current_thread();
269 * If telemetry isn't active for this thread, return and try
272 if (telemetry_is_active(thread
) == FALSE
) {
276 telemetry_needs_record
= FALSE
;
277 thread_ast_set(thread
, interrupted_userspace
? AST_TELEMETRY_USER
: AST_TELEMETRY_KERNEL
);
278 ast_propagate(thread
->ast
);
281 void compute_telemetry(void *arg __unused
)
283 if (telemetry_sample_all_tasks
|| (telemetry_active_tasks
> 0)) {
284 if ((++telemetry_timestamp
) % telemetry_sample_rate
== 0) {
286 * To avoid overloading the system with telemetry ASTs, make
287 * sure we don't add more requests while existing ones
290 if (TELEMETRY_TRY_SPIN_LOCK()) {
291 telemetry_needs_record
= TRUE
;
292 telemetry_needs_timer_arming_record
= TRUE
;
300 * If userland has registered a port for telemetry notifications, send one now.
303 telemetry_notify_user(void)
305 mach_port_t user_port
;
309 error
= host_get_telemetry_port(host_priv_self(), &user_port
);
310 if ((error
!= KERN_SUCCESS
) || !IPC_PORT_VALID(user_port
)) {
314 telemetry_notification(user_port
, flags
);
317 void telemetry_ast(thread_t thread
, boolean_t interrupted_userspace
)
319 uint8_t microsnapshot_flags
= kInterruptRecord
;
321 if (interrupted_userspace
)
322 microsnapshot_flags
|= kUserMode
;
324 telemetry_take_sample(thread
, microsnapshot_flags
);
327 void telemetry_take_sample(thread_t thread
, uint8_t microsnapshot_flags
)
331 struct kperf_context ctx
;
333 uint32_t btcount
, bti
;
334 struct micro_snapshot
*msnap
;
335 struct task_snapshot
*tsnap
;
336 struct thread_snapshot
*thsnap
;
340 uint32_t current_record_start
;
342 boolean_t notify
= FALSE
;
344 if (thread
== THREAD_NULL
)
348 if ((task
== TASK_NULL
) || (task
== kernel_task
))
351 /* telemetry_XXX accessed outside of lock for instrumentation only */
352 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_STACKSHOT
, MICROSTACKSHOT_RECORD
) | DBG_FUNC_START
, microsnapshot_flags
, telemetry_bytes_since_last_mark
, 0, 0, 0);
354 p
= get_bsdtask_info(task
);
356 ctx
.cur_thread
= thread
;
357 ctx
.cur_pid
= proc_pid(p
);
360 * Gather up the data we'll need for this sample. The sample is written into the kernel
361 * buffer with the global telemetry lock held -- so we must do our (possibly faulting)
362 * copies from userland here, before taking the lock.
364 kperf_ucallstack_sample(&cs
, &ctx
);
365 if (!(cs
.flags
& CALLSTACK_VALID
))
369 * Find the actual [slid] address of the shared cache's UUID, and copy it in from userland.
371 int shared_cache_uuid_valid
= 0;
372 uint64_t shared_cache_base_address
;
373 struct _dyld_cache_header shared_cache_header
;
374 uint64_t shared_cache_slide
;
377 * Don't copy in the entire shared cache header; we only need the UUID. Calculate the
378 * offset of that one field.
380 int sc_header_uuid_offset
= (char *)&shared_cache_header
.uuid
- (char *)&shared_cache_header
;
381 vm_shared_region_t sr
= vm_shared_region_get(task
);
383 if ((vm_shared_region_start_address(sr
, &shared_cache_base_address
) == KERN_SUCCESS
) &&
384 (copyin(shared_cache_base_address
+ sc_header_uuid_offset
, (char *)&shared_cache_header
.uuid
,
385 sizeof (shared_cache_header
.uuid
)) == 0)) {
386 shared_cache_uuid_valid
= 1;
387 shared_cache_slide
= vm_shared_region_get_slide(sr
);
389 // vm_shared_region_get() gave us a reference on the shared region.
390 vm_shared_region_deallocate(sr
);
394 * Retrieve the array of UUID's for binaries used by this task.
395 * We reach down into DYLD's data structures to find the array.
397 * XXX - make this common with kdp?
399 uint32_t uuid_info_count
= 0;
400 mach_vm_address_t uuid_info_addr
= 0;
401 if (task_has_64BitAddr(task
)) {
402 struct user64_dyld_all_image_infos task_image_infos
;
403 if (copyin(task
->all_image_info_addr
, (char *)&task_image_infos
, sizeof(task_image_infos
)) == 0) {
404 uuid_info_count
= (uint32_t)task_image_infos
.uuidArrayCount
;
405 uuid_info_addr
= task_image_infos
.uuidArray
;
408 struct user32_dyld_all_image_infos task_image_infos
;
409 if (copyin(task
->all_image_info_addr
, (char *)&task_image_infos
, sizeof(task_image_infos
)) == 0) {
410 uuid_info_count
= task_image_infos
.uuidArrayCount
;
411 uuid_info_addr
= task_image_infos
.uuidArray
;
416 * If we get a NULL uuid_info_addr (which can happen when we catch dyld in the middle of updating
417 * this data structure), we zero the uuid_info_count so that we won't even try to save load info
420 if (!uuid_info_addr
) {
424 uint32_t uuid_info_size
= (uint32_t)(task_has_64BitAddr(thread
->task
) ? sizeof(struct user64_dyld_uuid_info
) : sizeof(struct user32_dyld_uuid_info
));
425 uint32_t uuid_info_array_size
= uuid_info_count
* uuid_info_size
;
426 char *uuid_info_array
= NULL
;
428 if (uuid_info_count
> 0) {
429 if ((uuid_info_array
= (char *)kalloc(uuid_info_array_size
)) == NULL
) {
434 * Copy in the UUID info array.
435 * It may be nonresident, in which case just fix up nloadinfos to 0 in the task snapshot.
437 if (copyin(uuid_info_addr
, uuid_info_array
, uuid_info_array_size
) != 0) {
438 kfree(uuid_info_array
, uuid_info_array_size
);
439 uuid_info_array
= NULL
;
440 uuid_info_array_size
= 0;
445 * Look for a dispatch queue serial number, and copy it in from userland if present.
447 uint64_t dqserialnum
= 0;
448 int dqserialnum_valid
= 0;
450 uint64_t dqkeyaddr
= thread_dispatchqaddr(thread
);
451 if (dqkeyaddr
!= 0) {
453 uint64_t dq_serialno_offset
= get_dispatchqueue_serialno_offset_from_proc(task
->bsd_info
);
454 if ((copyin(dqkeyaddr
, (char *)&dqaddr
, (task_has_64BitAddr(task
) ? 8 : 4)) == 0) &&
455 (dqaddr
!= 0) && (dq_serialno_offset
!= 0)) {
456 uint64_t dqserialnumaddr
= dqaddr
+ dq_serialno_offset
;
457 if (copyin(dqserialnumaddr
, (char *)&dqserialnum
, (task_has_64BitAddr(task
) ? 8 : 4)) == 0) {
458 dqserialnum_valid
= 1;
463 clock_get_calendar_microtime(&secs
, &usecs
);
468 * We do the bulk of the operation under the telemetry lock, on assumption that
469 * any page faults during execution will not cause another AST_TELEMETRY_ALL
470 * to deadlock; they will just block until we finish. This makes it easier
471 * to copy into the buffer directly. As soon as we unlock, userspace can copy
477 current_record_start
= telemetry_buffer_current_position
;
479 if ((telemetry_buffer_size
- telemetry_buffer_current_position
) < sizeof(struct micro_snapshot
)) {
481 * We can't fit a record in the space available, so wrap around to the beginning.
482 * Save the current position as the known end point of valid data.
484 telemetry_buffer_end_point
= current_record_start
;
485 telemetry_buffer_current_position
= 0;
489 msnap
= (struct micro_snapshot
*)(uintptr_t)(telemetry_buffer
+ telemetry_buffer_current_position
);
490 msnap
->snapshot_magic
= STACKSHOT_MICRO_SNAPSHOT_MAGIC
;
491 msnap
->ms_flags
= microsnapshot_flags
;
492 msnap
->ms_opaque_flags
= 0; /* namespace managed by userspace */
493 msnap
->ms_cpu
= 0; /* XXX - does this field make sense for a micro-stackshot? */
494 msnap
->ms_time
= secs
;
495 msnap
->ms_time_microsecs
= usecs
;
497 telemetry_buffer_current_position
+= sizeof(struct micro_snapshot
);
499 if ((telemetry_buffer_size
- telemetry_buffer_current_position
) < sizeof(struct task_snapshot
)) {
500 telemetry_buffer_end_point
= current_record_start
;
501 telemetry_buffer_current_position
= 0;
505 tsnap
= (struct task_snapshot
*)(uintptr_t)(telemetry_buffer
+ telemetry_buffer_current_position
);
506 bzero(tsnap
, sizeof(*tsnap
));
507 tsnap
->snapshot_magic
= STACKSHOT_TASK_SNAPSHOT_MAGIC
;
508 tsnap
->pid
= proc_pid(p
);
509 tsnap
->uniqueid
= proc_uniqueid(p
);
510 tsnap
->user_time_in_terminated_threads
= task
->total_user_time
;
511 tsnap
->system_time_in_terminated_threads
= task
->total_system_time
;
512 tsnap
->suspend_count
= task
->suspend_count
;
513 tsnap
->task_size
= pmap_resident_count(task
->map
->pmap
);
514 tsnap
->faults
= task
->faults
;
515 tsnap
->pageins
= task
->pageins
;
516 tsnap
->cow_faults
= task
->cow_faults
;
518 * The throttling counters are maintained as 64-bit counters in the proc
519 * structure. However, we reserve 32-bits (each) for them in the task_snapshot
520 * struct to save space and since we do not expect them to overflow 32-bits. If we
521 * find these values overflowing in the future, the fix would be to simply
522 * upgrade these counters to 64-bit in the task_snapshot struct
524 tsnap
->was_throttled
= (uint32_t) proc_was_throttled(p
);
525 tsnap
->did_throttle
= (uint32_t) proc_did_throttle(p
);
527 if (task
->t_flags
& TF_TELEMETRY
) {
528 tsnap
->ss_flags
|= kTaskRsrcFlagged
;
531 proc_get_darwinbgstate(task
, &tmp
);
533 if (tmp
& PROC_FLAG_DARWINBG
) {
534 tsnap
->ss_flags
|= kTaskDarwinBG
;
536 if (tmp
& PROC_FLAG_EXT_DARWINBG
) {
537 tsnap
->ss_flags
|= kTaskExtDarwinBG
;
540 if (task
->requested_policy
.t_role
== TASK_FOREGROUND_APPLICATION
) {
541 tsnap
->ss_flags
|= kTaskIsForeground
;
544 if (tmp
& PROC_FLAG_ADAPTIVE_IMPORTANT
) {
545 tsnap
->ss_flags
|= kTaskIsBoosted
;
548 if (tmp
& PROC_FLAG_SUPPRESSED
) {
549 tsnap
->ss_flags
|= kTaskIsSuppressed
;
552 tsnap
->latency_qos
= task_grab_latency_qos(task
);
554 strlcpy(tsnap
->p_comm
, proc_name_address(p
), sizeof(tsnap
->p_comm
));
555 if (task_has_64BitAddr(thread
->task
)) {
556 tsnap
->ss_flags
|= kUser64_p
;
559 if (shared_cache_uuid_valid
) {
560 tsnap
->shared_cache_slide
= shared_cache_slide
;
561 bcopy(shared_cache_header
.uuid
, tsnap
->shared_cache_identifier
, sizeof (shared_cache_header
.uuid
));
564 telemetry_buffer_current_position
+= sizeof(struct task_snapshot
);
567 * Directly after the task snapshot, place the array of UUID's corresponding to the binaries
570 if ((telemetry_buffer_size
- telemetry_buffer_current_position
) < uuid_info_array_size
) {
571 telemetry_buffer_end_point
= current_record_start
;
572 telemetry_buffer_current_position
= 0;
577 * Copy the UUID info array into our sample.
579 if (uuid_info_array_size
> 0) {
580 bcopy(uuid_info_array
, (char *)(telemetry_buffer
+ telemetry_buffer_current_position
), uuid_info_array_size
);
581 tsnap
->nloadinfos
= uuid_info_count
;
584 telemetry_buffer_current_position
+= uuid_info_array_size
;
587 * After the task snapshot & list of binary UUIDs, we place a thread snapshot.
590 if ((telemetry_buffer_size
- telemetry_buffer_current_position
) < sizeof(struct thread_snapshot
)) {
591 /* wrap and overwrite */
592 telemetry_buffer_end_point
= current_record_start
;
593 telemetry_buffer_current_position
= 0;
597 thsnap
= (struct thread_snapshot
*)(uintptr_t)(telemetry_buffer
+ telemetry_buffer_current_position
);
598 bzero(thsnap
, sizeof(*thsnap
));
600 thsnap
->snapshot_magic
= STACKSHOT_THREAD_SNAPSHOT_MAGIC
;
601 thsnap
->thread_id
= thread_tid(thread
);
602 thsnap
->state
= thread
->state
;
603 thsnap
->priority
= thread
->priority
;
604 thsnap
->sched_pri
= thread
->sched_pri
;
605 thsnap
->sched_flags
= thread
->sched_flags
;
606 thsnap
->ss_flags
|= kStacksPCOnly
;
608 if (thread
->effective_policy
.darwinbg
) {
609 thsnap
->ss_flags
|= kThreadDarwinBG
;
612 thsnap
->user_time
= timer_grab(&thread
->user_timer
);
614 uint64_t tval
= timer_grab(&thread
->system_timer
);
616 if (thread
->precise_user_kernel_time
) {
617 thsnap
->system_time
= tval
;
619 thsnap
->user_time
+= tval
;
620 thsnap
->system_time
= 0;
623 telemetry_buffer_current_position
+= sizeof(struct thread_snapshot
);
626 * If this thread has a dispatch queue serial number, include it here.
628 if (dqserialnum_valid
) {
629 if ((telemetry_buffer_size
- telemetry_buffer_current_position
) < sizeof(dqserialnum
)) {
630 /* wrap and overwrite */
631 telemetry_buffer_end_point
= current_record_start
;
632 telemetry_buffer_current_position
= 0;
636 thsnap
->ss_flags
|= kHasDispatchSerial
;
637 bcopy(&dqserialnum
, (char *)telemetry_buffer
+ telemetry_buffer_current_position
, sizeof (dqserialnum
));
638 telemetry_buffer_current_position
+= sizeof (dqserialnum
);
641 if (task_has_64BitAddr(task
)) {
643 thsnap
->ss_flags
|= kUser64_p
;
648 btcount
= cs
.nframes
;
651 * If we can't fit this entire stacktrace then cancel this record, wrap to the beginning,
652 * and start again there so that we always store a full record.
654 if ((telemetry_buffer_size
- telemetry_buffer_current_position
)/framesize
< btcount
) {
655 telemetry_buffer_end_point
= current_record_start
;
656 telemetry_buffer_current_position
= 0;
660 for (bti
=0; bti
< btcount
; bti
++, telemetry_buffer_current_position
+= framesize
) {
661 if (framesize
== 8) {
662 *(uint64_t *)(uintptr_t)(telemetry_buffer
+ telemetry_buffer_current_position
) = cs
.frames
[bti
];
664 *(uint32_t *)(uintptr_t)(telemetry_buffer
+ telemetry_buffer_current_position
) = (uint32_t)cs
.frames
[bti
];
668 if (telemetry_buffer_end_point
< telemetry_buffer_current_position
) {
670 * Each time the cursor wraps around to the beginning, we leave a
671 * differing amount of unused space at the end of the buffer. Make
672 * sure the cursor pushes the end point in case we're making use of
673 * more of the buffer than we did the last time we wrapped.
675 telemetry_buffer_end_point
= telemetry_buffer_current_position
;
678 thsnap
->nuser_frames
= btcount
;
680 telemetry_bytes_since_last_mark
+= (telemetry_buffer_current_position
- current_record_start
);
681 if (telemetry_bytes_since_last_mark
> telemetry_buffer_notify_at
) {
687 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_STACKSHOT
, MICROSTACKSHOT_RECORD
) | DBG_FUNC_END
, notify
, telemetry_bytes_since_last_mark
, telemetry_buffer_current_position
, telemetry_buffer_end_point
, 0);
690 telemetry_notify_user();
693 if (uuid_info_array
!= NULL
) {
694 kfree(uuid_info_array
, uuid_info_array_size
);
700 log_telemetry_output(vm_offset_t buf
, uint32_t pos
, uint32_t sz
)
702 struct micro_snapshot
*p
;
705 printf("Copying out %d bytes of telemetry at offset %d\n", sz
, pos
);
710 * Find and log each timestamp in this chunk of buffer.
712 for (offset
= 0; offset
< sz
; offset
++) {
713 p
= (struct micro_snapshot
*)(buf
+ offset
);
714 if (p
->snapshot_magic
== STACKSHOT_MICRO_SNAPSHOT_MAGIC
) {
715 printf("telemetry timestamp: %lld\n", p
->ms_time
);
721 int telemetry_gather(user_addr_t buffer
, uint32_t *length
, boolean_t mark
)
724 uint32_t oldest_record_offset
;
726 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_STACKSHOT
, MICROSTACKSHOT_GATHER
) | DBG_FUNC_START
, mark
, telemetry_bytes_since_last_mark
, 0, 0, 0);
730 if (telemetry_buffer
== 0) {
735 if (*length
< telemetry_buffer_size
) {
736 result
= KERN_NO_SPACE
;
741 * Copy the ring buffer out to userland in order sorted by time: least recent to most recent.
742 * First, we need to search forward from the cursor to find the oldest record in our buffer.
744 oldest_record_offset
= telemetry_buffer_current_position
;
746 if ((oldest_record_offset
== telemetry_buffer_size
) ||
747 (oldest_record_offset
== telemetry_buffer_end_point
)) {
749 if (*(uint32_t *)(uintptr_t)(telemetry_buffer
) == 0) {
751 * There is no magic number at the start of the buffer, which means
752 * it's empty; nothing to see here yet.
758 * We've looked through the end of the active buffer without finding a valid
759 * record; that means all valid records are in a single chunk, beginning at
760 * the very start of the buffer.
763 oldest_record_offset
= 0;
764 assert(*(uint32_t *)(uintptr_t)(telemetry_buffer
) == STACKSHOT_MICRO_SNAPSHOT_MAGIC
);
768 if (*(uint32_t *)(uintptr_t)(telemetry_buffer
+ oldest_record_offset
) == STACKSHOT_MICRO_SNAPSHOT_MAGIC
)
772 * There are no alignment guarantees for micro-stackshot records, so we must search at each
775 oldest_record_offset
++;
776 } while (oldest_record_offset
!= telemetry_buffer_current_position
);
779 * If needed, copyout in two chunks: from the oldest record to the end of the buffer, and then
780 * from the beginning of the buffer up to the current position.
782 if (oldest_record_offset
!= 0) {
784 log_telemetry_output(telemetry_buffer
, oldest_record_offset
,
785 telemetry_buffer_end_point
- oldest_record_offset
);
787 if ((result
= copyout((void *)(telemetry_buffer
+ oldest_record_offset
), buffer
,
788 telemetry_buffer_end_point
- oldest_record_offset
)) != 0) {
792 *length
= telemetry_buffer_end_point
- oldest_record_offset
;
798 log_telemetry_output(telemetry_buffer
, 0, telemetry_buffer_current_position
);
800 if ((result
= copyout((void *)telemetry_buffer
, buffer
+ *length
,
801 telemetry_buffer_current_position
)) != 0) {
805 *length
+= (uint32_t)telemetry_buffer_current_position
;
809 if (mark
&& (*length
> 0)) {
810 telemetry_bytes_since_last_mark
= 0;
815 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_STACKSHOT
, MICROSTACKSHOT_GATHER
) | DBG_FUNC_END
, telemetry_buffer_current_position
, *length
, telemetry_buffer_end_point
, 0, 0);
820 /************************/
821 /* BOOT PROFILE SUPPORT */
822 /************************/
826 * The boot-profiling support is a mechanism to sample activity happening on the
827 * system during boot. This mechanism sets up a periodic timer and on every timer fire,
828 * captures a full backtrace into the boot profiling buffer. This buffer can be pulled
829 * out and analyzed from user-space. It is turned on using the following boot-args:
830 * "bootprofile_buffer_size" specifies the size of the boot profile buffer
831 * "bootprofile_interval_ms" specifies the interval for the profiling timer
833 * Process Specific Boot Profiling
835 * The boot-arg "bootprofile_proc_name" can be used to specify a certain
836 * process that needs to profiled during boot. Setting this boot-arg changes
837 * the way stackshots are captured. At every timer fire, the code looks at the
838 * currently running process and takes a stackshot only if the requested process
839 * is on-core (which makes it unsuitable for MP systems).
843 #define BOOTPROFILE_MAX_BUFFER_SIZE (64*1024*1024) /* see also COPYSIZELIMIT_PANIC */
845 vm_offset_t bootprofile_buffer
= 0;
846 uint32_t bootprofile_buffer_size
= 0;
847 uint32_t bootprofile_buffer_current_position
= 0;
848 uint32_t bootprofile_interval_ms
= 0;
849 uint64_t bootprofile_interval_abs
= 0;
850 uint64_t bootprofile_next_deadline
= 0;
851 uint32_t bootprofile_all_procs
= 0;
852 char bootprofile_proc_name
[17];
854 lck_grp_t bootprofile_lck_grp
;
855 lck_mtx_t bootprofile_mtx
;
857 static timer_call_data_t bootprofile_timer_call_entry
;
859 #define BOOTPROFILE_LOCK() do { lck_mtx_lock(&bootprofile_mtx); } while(0)
860 #define BOOTPROFILE_TRY_SPIN_LOCK() lck_mtx_try_lock_spin(&bootprofile_mtx)
861 #define BOOTPROFILE_UNLOCK() do { lck_mtx_unlock(&bootprofile_mtx); } while(0)
863 static void bootprofile_timer_call(
864 timer_call_param_t param0
,
865 timer_call_param_t param1
);
868 stack_snapshot_from_kernel(int pid
, void *buf
, uint32_t size
, uint32_t flags
, unsigned *retbytes
);
870 void bootprofile_init(void)
874 lck_grp_init(&bootprofile_lck_grp
, "bootprofile group", LCK_GRP_ATTR_NULL
);
875 lck_mtx_init(&bootprofile_mtx
, &bootprofile_lck_grp
, LCK_ATTR_NULL
);
877 if (!PE_parse_boot_argn("bootprofile_buffer_size", &bootprofile_buffer_size
, sizeof(bootprofile_buffer_size
))) {
878 bootprofile_buffer_size
= 0;
881 if (bootprofile_buffer_size
> BOOTPROFILE_MAX_BUFFER_SIZE
)
882 bootprofile_buffer_size
= BOOTPROFILE_MAX_BUFFER_SIZE
;
884 if (!PE_parse_boot_argn("bootprofile_interval_ms", &bootprofile_interval_ms
, sizeof(bootprofile_interval_ms
))) {
885 bootprofile_interval_ms
= 0;
888 if (!PE_parse_boot_argn("bootprofile_proc_name", &bootprofile_proc_name
, sizeof(bootprofile_proc_name
))) {
889 bootprofile_all_procs
= 1;
890 bootprofile_proc_name
[0] = '\0';
893 clock_interval_to_absolutetime_interval(bootprofile_interval_ms
, NSEC_PER_MSEC
, &bootprofile_interval_abs
);
895 /* Both boot args must be set to enable */
896 if ((bootprofile_buffer_size
== 0) || (bootprofile_interval_abs
== 0)) {
900 ret
= kmem_alloc(kernel_map
, &bootprofile_buffer
, bootprofile_buffer_size
);
901 if (ret
!= KERN_SUCCESS
) {
902 kprintf("Boot profile: Allocation failed: %d\n", ret
);
906 kprintf("Boot profile: Sampling %s once per %u ms\n", bootprofile_all_procs
? "all procs" : bootprofile_proc_name
, bootprofile_interval_ms
);
908 timer_call_setup(&bootprofile_timer_call_entry
,
909 bootprofile_timer_call
,
912 bootprofile_next_deadline
= mach_absolute_time() + bootprofile_interval_abs
;
913 timer_call_enter_with_leeway(&bootprofile_timer_call_entry
,
915 bootprofile_next_deadline
,
917 TIMER_CALL_SYS_NORMAL
,
921 static void bootprofile_timer_call(
922 timer_call_param_t param0 __unused
,
923 timer_call_param_t param1 __unused
)
925 unsigned retbytes
= 0;
926 int pid_to_profile
= -1;
928 if (!BOOTPROFILE_TRY_SPIN_LOCK()) {
932 /* Check if process-specific boot profiling is turned on */
933 if (!bootprofile_all_procs
) {
935 * Since boot profiling initializes really early in boot, it is
936 * possible that at this point, the task/proc is not initialized.
937 * Nothing to do in that case.
940 if ((current_task() != NULL
) && (current_task()->bsd_info
!= NULL
) &&
941 (0 == strncmp(bootprofile_proc_name
, proc_name_address(current_task()->bsd_info
), 17))) {
942 pid_to_profile
= proc_selfpid();
946 * Process-specific boot profiling requested but the on-core process is
947 * something else. Nothing to do here.
949 BOOTPROFILE_UNLOCK();
954 /* initiate a stackshot with whatever portion of the buffer is left */
955 if (bootprofile_buffer_current_position
< bootprofile_buffer_size
) {
956 stack_snapshot_from_kernel(
958 (void *)(bootprofile_buffer
+ bootprofile_buffer_current_position
),
959 bootprofile_buffer_size
- bootprofile_buffer_current_position
,
960 STACKSHOT_SAVE_LOADINFO
| STACKSHOT_SAVE_KEXT_LOADINFO
| STACKSHOT_GET_GLOBAL_MEM_STATS
,
964 bootprofile_buffer_current_position
+= retbytes
;
967 BOOTPROFILE_UNLOCK();
969 /* If we didn't get any data or have run out of buffer space, stop profiling */
970 if ((retbytes
== 0) || (bootprofile_buffer_current_position
== bootprofile_buffer_size
)) {
976 /* If the user gathered the buffer, no need to keep profiling */
977 if (bootprofile_interval_abs
== 0) {
981 clock_deadline_for_periodic_event(bootprofile_interval_abs
,
982 mach_absolute_time(),
983 &bootprofile_next_deadline
);
984 timer_call_enter_with_leeway(&bootprofile_timer_call_entry
,
986 bootprofile_next_deadline
,
988 TIMER_CALL_SYS_NORMAL
,
992 int bootprofile_gather(user_addr_t buffer
, uint32_t *length
)
998 if (bootprofile_buffer
== 0) {
1003 if (*length
< bootprofile_buffer_current_position
) {
1004 result
= KERN_NO_SPACE
;
1008 if ((result
= copyout((void *)bootprofile_buffer
, buffer
,
1009 bootprofile_buffer_current_position
)) != 0) {
1013 *length
= bootprofile_buffer_current_position
;
1015 /* cancel future timers */
1016 bootprofile_interval_abs
= 0;
1020 BOOTPROFILE_UNLOCK();