]> git.saurik.com Git - apple/xnu.git/blame - osfmk/kern/telemetry.c
xnu-6153.101.6.tar.gz
[apple/xnu.git] / osfmk / kern / telemetry.c
CommitLineData
39236c6e 1/*
cb323159 2 * Copyright (c) 2012-2019 Apple Inc. All rights reserved.
39236c6e
A
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
d9a64523 5 *
39236c6e
A
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.
d9a64523 14 *
39236c6e
A
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
d9a64523 17 *
39236c6e
A
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.
d9a64523 25 *
39236c6e
A
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
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>
32
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>
d9a64523
A
38#include <kern/kern_types.h>
39#include <kern/locks.h>
40#include <kern/misc_protos.h>
39236c6e
A
41#include <kern/sched.h>
42#include <kern/sched_prim.h>
43#include <kern/telemetry.h>
44#include <kern/timer_call.h>
39037602
A
45#include <kern/policy_internal.h>
46#include <kern/kcdata.h>
39236c6e
A
47
48#include <pexpert/pexpert.h>
49
50#include <vm/vm_kern.h>
51#include <vm/vm_shared_region.h>
52
39236c6e 53#include <kperf/callstack.h>
cc8bc92a 54#include <kern/backtrace.h>
d9a64523 55#include <kern/monotonic.h>
39236c6e
A
56
57#include <sys/kdebug.h>
58#include <uuid/uuid.h>
59#include <kdp/kdp_dyld.h>
60
61#define TELEMETRY_DEBUG 0
62
0a7de745
A
63extern int proc_pid(void *);
64extern char *proc_name_address(void *p);
39236c6e
A
65extern uint64_t proc_uniqueid(void *p);
66extern uint64_t proc_was_throttled(void *p);
67extern uint64_t proc_did_throttle(void *p);
0a7de745 68extern int proc_selfpid(void);
743345f9
A
69extern boolean_t task_did_exec(task_t task);
70extern boolean_t task_is_exec_copy(task_t task);
39236c6e 71
fe8ab488 72struct micro_snapshot_buffer {
0a7de745
A
73 vm_offset_t buffer;
74 uint32_t size;
75 uint32_t current_position;
76 uint32_t end_point;
fe8ab488
A
77};
78
79void telemetry_take_sample(thread_t thread, uint8_t microsnapshot_flags, struct micro_snapshot_buffer * current_buffer);
80int telemetry_buffer_gather(user_addr_t buffer, uint32_t *length, boolean_t mark, struct micro_snapshot_buffer * current_buffer);
39236c6e
A
81
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)
85
0a7de745
A
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
39236c6e 88
0a7de745
A
89uint32_t telemetry_sample_rate = 0;
90volatile boolean_t telemetry_needs_record = FALSE;
91volatile boolean_t telemetry_needs_timer_arming_record = FALSE;
39236c6e
A
92
93/*
94 * If TRUE, record micro-stackshot samples for all tasks.
95 * If FALSE, only sample tasks which are marked for telemetry.
96 */
d9a64523
A
97boolean_t telemetry_sample_all_tasks = FALSE;
98boolean_t telemetry_sample_pmis = FALSE;
99uint32_t telemetry_active_tasks = 0; // Number of tasks opted into telemetry
39236c6e 100
d9a64523 101uint32_t telemetry_timestamp = 0;
39236c6e 102
fe8ab488 103/*
39037602 104 * The telemetry_buffer is responsible
fe8ab488
A
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.
fe8ab488 108 */
cb323159
A
109struct micro_snapshot_buffer telemetry_buffer = {
110 .buffer = 0,
111 .size = 0,
112 .current_position = 0,
113 .end_point = 0
114};
fe8ab488 115
0a7de745
A
116int telemetry_bytes_since_last_mark = -1; // How much data since buf was last marked?
117int telemetry_buffer_notify_at = 0;
39236c6e 118
d9a64523
A
119lck_grp_t telemetry_lck_grp;
120lck_mtx_t telemetry_mtx;
121lck_mtx_t telemetry_pmi_mtx;
39236c6e 122
d9a64523 123#define TELEMETRY_LOCK() do { lck_mtx_lock(&telemetry_mtx); } while (0)
39236c6e 124#define TELEMETRY_TRY_SPIN_LOCK() lck_mtx_try_lock_spin(&telemetry_mtx)
d9a64523
A
125#define TELEMETRY_UNLOCK() do { lck_mtx_unlock(&telemetry_mtx); } while (0)
126
127#define TELEMETRY_PMI_LOCK() do { lck_mtx_lock(&telemetry_pmi_mtx); } while (0)
128#define TELEMETRY_PMI_UNLOCK() do { lck_mtx_unlock(&telemetry_pmi_mtx); } while (0)
39236c6e 129
0a7de745
A
130void
131telemetry_init(void)
39236c6e
A
132{
133 kern_return_t ret;
0a7de745 134 uint32_t telemetry_notification_leeway;
39236c6e
A
135
136 lck_grp_init(&telemetry_lck_grp, "telemetry group", LCK_GRP_ATTR_NULL);
137 lck_mtx_init(&telemetry_mtx, &telemetry_lck_grp, LCK_ATTR_NULL);
d9a64523 138 lck_mtx_init(&telemetry_pmi_mtx, &telemetry_lck_grp, LCK_ATTR_NULL);
39236c6e 139
fe8ab488
A
140 if (!PE_parse_boot_argn("telemetry_buffer_size", &telemetry_buffer.size, sizeof(telemetry_buffer.size))) {
141 telemetry_buffer.size = TELEMETRY_DEFAULT_BUFFER_SIZE;
39236c6e
A
142 }
143
0a7de745 144 if (telemetry_buffer.size > TELEMETRY_MAX_BUFFER_SIZE) {
fe8ab488 145 telemetry_buffer.size = TELEMETRY_MAX_BUFFER_SIZE;
0a7de745 146 }
39236c6e 147
3e170ce0 148 ret = kmem_alloc(kernel_map, &telemetry_buffer.buffer, telemetry_buffer.size, VM_KERN_MEMORY_DIAG);
39236c6e
A
149 if (ret != KERN_SUCCESS) {
150 kprintf("Telemetry: Allocation failed: %d\n", ret);
151 return;
152 }
fe8ab488 153 bzero((void *) telemetry_buffer.buffer, telemetry_buffer.size);
39236c6e
A
154
155 if (!PE_parse_boot_argn("telemetry_notification_leeway", &telemetry_notification_leeway, sizeof(telemetry_notification_leeway))) {
156 /*
157 * By default, notify the user to collect the buffer when there is this much space left in the buffer.
158 */
159 telemetry_notification_leeway = TELEMETRY_DEFAULT_NOTIFY_LEEWAY;
160 }
fe8ab488 161 if (telemetry_notification_leeway >= telemetry_buffer.size) {
39236c6e 162 printf("telemetry: nonsensical telemetry_notification_leeway boot-arg %d changed to %d\n",
0a7de745 163 telemetry_notification_leeway, TELEMETRY_DEFAULT_NOTIFY_LEEWAY);
39236c6e
A
164 telemetry_notification_leeway = TELEMETRY_DEFAULT_NOTIFY_LEEWAY;
165 }
fe8ab488 166 telemetry_buffer_notify_at = telemetry_buffer.size - telemetry_notification_leeway;
39236c6e
A
167
168 if (!PE_parse_boot_argn("telemetry_sample_rate", &telemetry_sample_rate, sizeof(telemetry_sample_rate))) {
169 telemetry_sample_rate = TELEMETRY_DEFAULT_SAMPLE_RATE;
170 }
171
172 /*
173 * To enable telemetry for all tasks, include "telemetry_sample_all_tasks=1" in boot-args.
174 */
175 if (!PE_parse_boot_argn("telemetry_sample_all_tasks", &telemetry_sample_all_tasks, sizeof(telemetry_sample_all_tasks))) {
5ba3f43e
A
176#if CONFIG_EMBEDDED && !(DEVELOPMENT || DEBUG)
177 telemetry_sample_all_tasks = FALSE;
178#else
39236c6e 179 telemetry_sample_all_tasks = TRUE;
5ba3f43e 180#endif /* CONFIG_EMBEDDED && !(DEVELOPMENT || DEBUG) */
39236c6e
A
181 }
182
183 kprintf("Telemetry: Sampling %stasks once per %u second%s\n",
0a7de745
A
184 (telemetry_sample_all_tasks) ? "all " : "",
185 telemetry_sample_rate, telemetry_sample_rate == 1 ? "" : "s");
39236c6e
A
186}
187
188/*
189 * Enable or disable global microstackshots (ie telemetry_sample_all_tasks).
190 *
191 * enable_disable == 1: turn it on
192 * enable_disable == 0: turn it off
193 */
194void
d9a64523 195telemetry_global_ctl(int enable_disable)
39236c6e
A
196{
197 if (enable_disable == 1) {
198 telemetry_sample_all_tasks = TRUE;
199 } else {
200 telemetry_sample_all_tasks = FALSE;
201 }
202}
203
204/*
205 * Opt the given task into or out of the telemetry stream.
206 *
207 * Supported reasons (callers may use any or all of):
208 * TF_CPUMON_WARNING
209 * TF_WAKEMON_WARNING
210 *
211 * enable_disable == 1: turn it on
212 * enable_disable == 0: turn it off
213 */
214void
215telemetry_task_ctl(task_t task, uint32_t reasons, int enable_disable)
216{
217 task_lock(task);
218 telemetry_task_ctl_locked(task, reasons, enable_disable);
219 task_unlock(task);
220}
221
222void
223telemetry_task_ctl_locked(task_t task, uint32_t reasons, int enable_disable)
224{
225 uint32_t origflags;
226
227 assert((reasons != 0) && ((reasons | TF_TELEMETRY) == TF_TELEMETRY));
228
229 task_lock_assert_owned(task);
230
231 origflags = task->t_flags;
232
233 if (enable_disable == 1) {
234 task->t_flags |= reasons;
235 if ((origflags & TF_TELEMETRY) == 0) {
236 OSIncrementAtomic(&telemetry_active_tasks);
d9a64523 237#if TELEMETRY_DEBUG
39236c6e 238 printf("%s: telemetry OFF -> ON (%d active)\n", proc_name_address(task->bsd_info), telemetry_active_tasks);
d9a64523 239#endif
39236c6e
A
240 }
241 } else {
242 task->t_flags &= ~reasons;
243 if (((origflags & TF_TELEMETRY) != 0) && ((task->t_flags & TF_TELEMETRY) == 0)) {
244 /*
245 * If this task went from having at least one telemetry bit to having none,
246 * the net change was to disable telemetry for the task.
247 */
248 OSDecrementAtomic(&telemetry_active_tasks);
249#if TELEMETRY_DEBUG
250 printf("%s: telemetry ON -> OFF (%d active)\n", proc_name_address(task->bsd_info), telemetry_active_tasks);
251#endif
252 }
253 }
254}
255
256/*
257 * Determine if the current thread is eligible for telemetry:
258 *
259 * telemetry_sample_all_tasks: All threads are eligible. This takes precedence.
260 * telemetry_active_tasks: Count of tasks opted in.
261 * task->t_flags & TF_TELEMETRY: This task is opted in.
262 */
263static boolean_t
264telemetry_is_active(thread_t thread)
265{
3e170ce0
A
266 task_t task = thread->task;
267
268 if (task == kernel_task) {
269 /* Kernel threads never return to an AST boundary, and are ineligible */
270 return FALSE;
271 }
272
d9a64523
A
273 if (telemetry_sample_all_tasks || telemetry_sample_pmis) {
274 return TRUE;
39236c6e
A
275 }
276
277 if ((telemetry_active_tasks > 0) && ((thread->task->t_flags & TF_TELEMETRY) != 0)) {
d9a64523 278 return TRUE;
39236c6e 279 }
d9a64523
A
280
281 return FALSE;
39236c6e
A
282}
283
284/*
285 * Userland is arming a timer. If we are eligible for such a record,
286 * sample now. No need to do this one at the AST because we're already at
287 * a safe place in this system call.
288 */
0a7de745
A
289int
290telemetry_timer_event(__unused uint64_t deadline, __unused uint64_t interval, __unused uint64_t leeway)
39236c6e
A
291{
292 if (telemetry_needs_timer_arming_record == TRUE) {
293 telemetry_needs_timer_arming_record = FALSE;
fe8ab488 294 telemetry_take_sample(current_thread(), kTimerArmingRecord | kUserMode, &telemetry_buffer);
39236c6e
A
295 }
296
0a7de745 297 return 0;
39236c6e
A
298}
299
d9a64523
A
300#if defined(MT_CORE_INSTRS) && defined(MT_CORE_CYCLES)
301static void
302telemetry_pmi_handler(bool user_mode, __unused void *ctx)
303{
304 telemetry_mark_curthread(user_mode, TRUE);
305}
306#endif /* defined(MT_CORE_INSTRS) && defined(MT_CORE_CYCLES) */
307
0a7de745
A
308int
309telemetry_pmi_setup(enum telemetry_pmi pmi_ctr, uint64_t period)
d9a64523
A
310{
311#if defined(MT_CORE_INSTRS) && defined(MT_CORE_CYCLES)
312 static boolean_t sample_all_tasks_aside = FALSE;
313 static uint32_t active_tasks_aside = FALSE;
314 int error = 0;
315 const char *name = "?";
316
317 unsigned int ctr = 0;
318
319 TELEMETRY_PMI_LOCK();
320
321 switch (pmi_ctr) {
322 case TELEMETRY_PMI_NONE:
323 if (!telemetry_sample_pmis) {
324 error = 1;
325 goto out;
326 }
327
328 telemetry_sample_pmis = FALSE;
329 telemetry_sample_all_tasks = sample_all_tasks_aside;
330 telemetry_active_tasks = active_tasks_aside;
331 error = mt_microstackshot_stop();
332 if (!error) {
333 printf("telemetry: disabling ustackshot on PMI\n");
334 }
335 goto out;
336
337 case TELEMETRY_PMI_INSTRS:
338 ctr = MT_CORE_INSTRS;
339 name = "instructions";
340 break;
341
342 case TELEMETRY_PMI_CYCLES:
343 ctr = MT_CORE_CYCLES;
344 name = "cycles";
345 break;
346
347 default:
348 error = 1;
349 goto out;
350 }
351
352 telemetry_sample_pmis = TRUE;
353 sample_all_tasks_aside = telemetry_sample_all_tasks;
354 active_tasks_aside = telemetry_active_tasks;
355 telemetry_sample_all_tasks = FALSE;
356 telemetry_active_tasks = 0;
357
358 error = mt_microstackshot_start(ctr, period, telemetry_pmi_handler, NULL);
359 if (!error) {
360 printf("telemetry: ustackshot every %llu %s\n", period, name);
361 }
362
363out:
364 TELEMETRY_PMI_UNLOCK();
365 return error;
366#else /* defined(MT_CORE_INSTRS) && defined(MT_CORE_CYCLES) */
367#pragma unused(pmi_ctr, period)
368 return 1;
369#endif /* !defined(MT_CORE_INSTRS) || !defined(MT_CORE_CYCLES) */
370}
371
39236c6e
A
372/*
373 * Mark the current thread for an interrupt-based
374 * telemetry record, to be sampled at the next AST boundary.
375 */
0a7de745
A
376void
377telemetry_mark_curthread(boolean_t interrupted_userspace, boolean_t pmi)
39236c6e 378{
fe8ab488 379 uint32_t ast_bits = 0;
39236c6e
A
380 thread_t thread = current_thread();
381
382 /*
383 * If telemetry isn't active for this thread, return and try
384 * again next time.
385 */
386 if (telemetry_is_active(thread) == FALSE) {
387 return;
388 }
389
fe8ab488 390 ast_bits |= (interrupted_userspace ? AST_TELEMETRY_USER : AST_TELEMETRY_KERNEL);
d9a64523
A
391 if (pmi) {
392 ast_bits |= AST_TELEMETRY_PMI;
393 }
fe8ab488 394
39236c6e 395 telemetry_needs_record = FALSE;
fe8ab488 396 thread_ast_set(thread, ast_bits);
5ba3f43e 397 ast_propagate(thread);
39236c6e
A
398}
399
0a7de745
A
400void
401compute_telemetry(void *arg __unused)
39236c6e
A
402{
403 if (telemetry_sample_all_tasks || (telemetry_active_tasks > 0)) {
404 if ((++telemetry_timestamp) % telemetry_sample_rate == 0) {
fe8ab488
A
405 telemetry_needs_record = TRUE;
406 telemetry_needs_timer_arming_record = TRUE;
407 }
408 }
409}
410
39236c6e
A
411/*
412 * If userland has registered a port for telemetry notifications, send one now.
413 */
414static void
415telemetry_notify_user(void)
416{
d9a64523 417 mach_port_t user_port = MACH_PORT_NULL;
39236c6e 418
d9a64523
A
419 kern_return_t kr = host_get_telemetry_port(host_priv_self(), &user_port);
420 if ((kr != KERN_SUCCESS) || !IPC_PORT_VALID(user_port)) {
39236c6e
A
421 return;
422 }
423
d9a64523 424 telemetry_notification(user_port, 0);
39037602 425 ipc_port_release_send(user_port);
39236c6e
A
426}
427
0a7de745
A
428void
429telemetry_ast(thread_t thread, ast_t reasons)
39236c6e 430{
d9a64523 431 assert((reasons & AST_TELEMETRY_ALL) != 0);
5ba3f43e 432
d9a64523
A
433 uint8_t record_type = 0;
434 if (reasons & AST_TELEMETRY_IO) {
435 record_type |= kIORecord;
436 }
437 if (reasons & (AST_TELEMETRY_USER | AST_TELEMETRY_KERNEL)) {
438 record_type |= (reasons & AST_TELEMETRY_PMI) ? kPMIRecord :
0a7de745 439 kInterruptRecord;
d9a64523 440 }
5ba3f43e 441
d9a64523 442 uint8_t user_telemetry = (reasons & AST_TELEMETRY_USER) ? kUserMode : 0;
39236c6e 443
d9a64523 444 uint8_t microsnapshot_flags = record_type | user_telemetry;
39236c6e 445
39037602 446 telemetry_take_sample(thread, microsnapshot_flags, &telemetry_buffer);
39236c6e
A
447}
448
0a7de745
A
449void
450telemetry_take_sample(thread_t thread, uint8_t microsnapshot_flags, struct micro_snapshot_buffer * current_buffer)
39236c6e
A
451{
452 task_t task;
453 void *p;
cc8bc92a 454 uint32_t btcount = 0, bti;
39236c6e
A
455 struct micro_snapshot *msnap;
456 struct task_snapshot *tsnap;
457 struct thread_snapshot *thsnap;
458 clock_sec_t secs;
459 clock_usec_t usecs;
460 vm_size_t framesize;
461 uint32_t current_record_start;
462 uint32_t tmp = 0;
463 boolean_t notify = FALSE;
464
0a7de745 465 if (thread == THREAD_NULL) {
39236c6e 466 return;
0a7de745 467 }
39236c6e
A
468
469 task = thread->task;
0a7de745 470 if ((task == TASK_NULL) || (task == kernel_task) || task_did_exec(task) || task_is_exec_copy(task)) {
39236c6e 471 return;
0a7de745 472 }
39236c6e
A
473
474 /* telemetry_XXX accessed outside of lock for instrumentation only */
d9a64523 475 KDBG(MACHDBG_CODE(DBG_MACH_STACKSHOT, MICROSTACKSHOT_RECORD) | DBG_FUNC_START,
0a7de745
A
476 microsnapshot_flags, telemetry_bytes_since_last_mark, 0,
477 (&telemetry_buffer != current_buffer));
39236c6e
A
478
479 p = get_bsdtask_info(task);
480
39236c6e
A
481 /*
482 * Gather up the data we'll need for this sample. The sample is written into the kernel
483 * buffer with the global telemetry lock held -- so we must do our (possibly faulting)
484 * copies from userland here, before taking the lock.
485 */
cb323159
A
486
487 uintptr_t frames[128];
488 bool user64_regs = false;
ea3f0419
A
489 int bterror = 0;
490 btcount = backtrace_user(frames,
491 sizeof(frames) / sizeof(frames[0]), &bterror, &user64_regs, NULL);
492 if (bterror != 0) {
39236c6e 493 return;
cc8bc92a 494 }
cb323159 495 bool user64_va = task_has_64Bit_addr(task);
39236c6e
A
496
497 /*
498 * Find the actual [slid] address of the shared cache's UUID, and copy it in from userland.
499 */
cb323159
A
500 int shared_cache_uuid_valid = 0;
501 uint64_t shared_cache_base_address = 0;
502 struct _dyld_cache_header shared_cache_header = {};
503 uint64_t shared_cache_slide = 0;
39236c6e
A
504
505 /*
506 * Don't copy in the entire shared cache header; we only need the UUID. Calculate the
507 * offset of that one field.
508 */
509 int sc_header_uuid_offset = (char *)&shared_cache_header.uuid - (char *)&shared_cache_header;
510 vm_shared_region_t sr = vm_shared_region_get(task);
511 if (sr != NULL) {
512 if ((vm_shared_region_start_address(sr, &shared_cache_base_address) == KERN_SUCCESS) &&
0a7de745
A
513 (copyin(shared_cache_base_address + sc_header_uuid_offset, (char *)&shared_cache_header.uuid,
514 sizeof(shared_cache_header.uuid)) == 0)) {
39236c6e
A
515 shared_cache_uuid_valid = 1;
516 shared_cache_slide = vm_shared_region_get_slide(sr);
517 }
518 // vm_shared_region_get() gave us a reference on the shared region.
519 vm_shared_region_deallocate(sr);
520 }
521
522 /*
523 * Retrieve the array of UUID's for binaries used by this task.
524 * We reach down into DYLD's data structures to find the array.
525 *
526 * XXX - make this common with kdp?
527 */
cb323159
A
528 uint32_t uuid_info_count = 0;
529 mach_vm_address_t uuid_info_addr = 0;
530 uint32_t uuid_info_size = 0;
531 if (user64_va) {
532 uuid_info_size = sizeof(struct user64_dyld_uuid_info);
39236c6e
A
533 struct user64_dyld_all_image_infos task_image_infos;
534 if (copyin(task->all_image_info_addr, (char *)&task_image_infos, sizeof(task_image_infos)) == 0) {
535 uuid_info_count = (uint32_t)task_image_infos.uuidArrayCount;
536 uuid_info_addr = task_image_infos.uuidArray;
537 }
538 } else {
cb323159 539 uuid_info_size = sizeof(struct user32_dyld_uuid_info);
39236c6e
A
540 struct user32_dyld_all_image_infos task_image_infos;
541 if (copyin(task->all_image_info_addr, (char *)&task_image_infos, sizeof(task_image_infos)) == 0) {
542 uuid_info_count = task_image_infos.uuidArrayCount;
543 uuid_info_addr = task_image_infos.uuidArray;
544 }
545 }
546
547 /*
548 * If we get a NULL uuid_info_addr (which can happen when we catch dyld in the middle of updating
549 * this data structure), we zero the uuid_info_count so that we won't even try to save load info
550 * for this task.
551 */
552 if (!uuid_info_addr) {
553 uuid_info_count = 0;
554 }
555
143464d5
A
556 /*
557 * Don't copy in an unbounded amount of memory. The main binary and interesting
558 * non-shared-cache libraries should be in the first few images.
559 */
560 if (uuid_info_count > TELEMETRY_MAX_UUID_COUNT) {
561 uuid_info_count = TELEMETRY_MAX_UUID_COUNT;
562 }
563
39236c6e 564 uint32_t uuid_info_array_size = uuid_info_count * uuid_info_size;
0a7de745 565 char *uuid_info_array = NULL;
39236c6e
A
566
567 if (uuid_info_count > 0) {
568 if ((uuid_info_array = (char *)kalloc(uuid_info_array_size)) == NULL) {
569 return;
570 }
571
572 /*
573 * Copy in the UUID info array.
574 * It may be nonresident, in which case just fix up nloadinfos to 0 in the task snapshot.
575 */
576 if (copyin(uuid_info_addr, uuid_info_array, uuid_info_array_size) != 0) {
577 kfree(uuid_info_array, uuid_info_array_size);
578 uuid_info_array = NULL;
579 uuid_info_array_size = 0;
580 }
581 }
582
583 /*
584 * Look for a dispatch queue serial number, and copy it in from userland if present.
585 */
586 uint64_t dqserialnum = 0;
0a7de745 587 int dqserialnum_valid = 0;
39236c6e
A
588
589 uint64_t dqkeyaddr = thread_dispatchqaddr(thread);
590 if (dqkeyaddr != 0) {
591 uint64_t dqaddr = 0;
39037602 592 uint64_t dq_serialno_offset = get_task_dispatchqueue_serialno_offset(task);
cb323159 593 if ((copyin(dqkeyaddr, (char *)&dqaddr, (user64_va ? 8 : 4)) == 0) &&
39236c6e
A
594 (dqaddr != 0) && (dq_serialno_offset != 0)) {
595 uint64_t dqserialnumaddr = dqaddr + dq_serialno_offset;
cb323159 596 if (copyin(dqserialnumaddr, (char *)&dqserialnum, (user64_va ? 8 : 4)) == 0) {
39236c6e
A
597 dqserialnum_valid = 1;
598 }
599 }
600 }
601
602 clock_get_calendar_microtime(&secs, &usecs);
603
604 TELEMETRY_LOCK();
605
fe8ab488 606 /*
39037602 607 * If our buffer is not backed by anything,
fe8ab488
A
608 * then we cannot take the sample. Meant to allow us to deallocate the window
609 * buffer if it is disabled.
610 */
0a7de745 611 if (!current_buffer->buffer) {
fe8ab488 612 goto cancel_sample;
0a7de745 613 }
fe8ab488 614
39236c6e
A
615 /*
616 * We do the bulk of the operation under the telemetry lock, on assumption that
617 * any page faults during execution will not cause another AST_TELEMETRY_ALL
618 * to deadlock; they will just block until we finish. This makes it easier
619 * to copy into the buffer directly. As soon as we unlock, userspace can copy
620 * out of our buffer.
621 */
622
623copytobuffer:
624
fe8ab488 625 current_record_start = current_buffer->current_position;
39236c6e 626
fe8ab488 627 if ((current_buffer->size - current_buffer->current_position) < sizeof(struct micro_snapshot)) {
39236c6e
A
628 /*
629 * We can't fit a record in the space available, so wrap around to the beginning.
630 * Save the current position as the known end point of valid data.
631 */
fe8ab488
A
632 current_buffer->end_point = current_record_start;
633 current_buffer->current_position = 0;
143464d5
A
634 if (current_record_start == 0) {
635 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
636 goto cancel_sample;
637 }
39236c6e
A
638 goto copytobuffer;
639 }
640
fe8ab488 641 msnap = (struct micro_snapshot *)(uintptr_t)(current_buffer->buffer + current_buffer->current_position);
39236c6e
A
642 msnap->snapshot_magic = STACKSHOT_MICRO_SNAPSHOT_MAGIC;
643 msnap->ms_flags = microsnapshot_flags;
644 msnap->ms_opaque_flags = 0; /* namespace managed by userspace */
d9a64523 645 msnap->ms_cpu = cpu_number();
39236c6e
A
646 msnap->ms_time = secs;
647 msnap->ms_time_microsecs = usecs;
648
fe8ab488 649 current_buffer->current_position += sizeof(struct micro_snapshot);
39236c6e 650
fe8ab488
A
651 if ((current_buffer->size - current_buffer->current_position) < sizeof(struct task_snapshot)) {
652 current_buffer->end_point = current_record_start;
653 current_buffer->current_position = 0;
143464d5
A
654 if (current_record_start == 0) {
655 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
656 goto cancel_sample;
657 }
39236c6e
A
658 goto copytobuffer;
659 }
660
fe8ab488 661 tsnap = (struct task_snapshot *)(uintptr_t)(current_buffer->buffer + current_buffer->current_position);
39236c6e
A
662 bzero(tsnap, sizeof(*tsnap));
663 tsnap->snapshot_magic = STACKSHOT_TASK_SNAPSHOT_MAGIC;
664 tsnap->pid = proc_pid(p);
665 tsnap->uniqueid = proc_uniqueid(p);
666 tsnap->user_time_in_terminated_threads = task->total_user_time;
667 tsnap->system_time_in_terminated_threads = task->total_system_time;
668 tsnap->suspend_count = task->suspend_count;
0a7de745 669 tsnap->task_size = (typeof(tsnap->task_size))(get_task_phys_footprint(task) / PAGE_SIZE);
39236c6e
A
670 tsnap->faults = task->faults;
671 tsnap->pageins = task->pageins;
672 tsnap->cow_faults = task->cow_faults;
673 /*
674 * The throttling counters are maintained as 64-bit counters in the proc
675 * structure. However, we reserve 32-bits (each) for them in the task_snapshot
676 * struct to save space and since we do not expect them to overflow 32-bits. If we
d9a64523 677 * find these values overflowing in the future, the fix would be to simply
39236c6e
A
678 * upgrade these counters to 64-bit in the task_snapshot struct
679 */
680 tsnap->was_throttled = (uint32_t) proc_was_throttled(p);
681 tsnap->did_throttle = (uint32_t) proc_did_throttle(p);
d9a64523 682
39236c6e
A
683 if (task->t_flags & TF_TELEMETRY) {
684 tsnap->ss_flags |= kTaskRsrcFlagged;
685 }
686
39037602 687 if (proc_get_effective_task_policy(task, TASK_POLICY_DARWIN_BG)) {
39236c6e
A
688 tsnap->ss_flags |= kTaskDarwinBG;
689 }
15129b1c
A
690
691 proc_get_darwinbgstate(task, &tmp);
39236c6e 692
39037602 693 if (proc_get_effective_task_policy(task, TASK_POLICY_ROLE) == TASK_FOREGROUND_APPLICATION) {
39236c6e
A
694 tsnap->ss_flags |= kTaskIsForeground;
695 }
696
697 if (tmp & PROC_FLAG_ADAPTIVE_IMPORTANT) {
698 tsnap->ss_flags |= kTaskIsBoosted;
699 }
700
701 if (tmp & PROC_FLAG_SUPPRESSED) {
702 tsnap->ss_flags |= kTaskIsSuppressed;
703 }
704
705 tsnap->latency_qos = task_grab_latency_qos(task);
706
707 strlcpy(tsnap->p_comm, proc_name_address(p), sizeof(tsnap->p_comm));
cb323159 708 if (user64_va) {
39236c6e
A
709 tsnap->ss_flags |= kUser64_p;
710 }
711
712 if (shared_cache_uuid_valid) {
713 tsnap->shared_cache_slide = shared_cache_slide;
0a7de745 714 bcopy(shared_cache_header.uuid, tsnap->shared_cache_identifier, sizeof(shared_cache_header.uuid));
39236c6e
A
715 }
716
fe8ab488 717 current_buffer->current_position += sizeof(struct task_snapshot);
39236c6e
A
718
719 /*
720 * Directly after the task snapshot, place the array of UUID's corresponding to the binaries
721 * used by this task.
722 */
fe8ab488
A
723 if ((current_buffer->size - current_buffer->current_position) < uuid_info_array_size) {
724 current_buffer->end_point = current_record_start;
725 current_buffer->current_position = 0;
143464d5
A
726 if (current_record_start == 0) {
727 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
728 goto cancel_sample;
729 }
39236c6e
A
730 goto copytobuffer;
731 }
732
733 /*
734 * Copy the UUID info array into our sample.
735 */
736 if (uuid_info_array_size > 0) {
fe8ab488 737 bcopy(uuid_info_array, (char *)(current_buffer->buffer + current_buffer->current_position), uuid_info_array_size);
39236c6e
A
738 tsnap->nloadinfos = uuid_info_count;
739 }
740
fe8ab488 741 current_buffer->current_position += uuid_info_array_size;
39236c6e
A
742
743 /*
744 * After the task snapshot & list of binary UUIDs, we place a thread snapshot.
745 */
746
fe8ab488 747 if ((current_buffer->size - current_buffer->current_position) < sizeof(struct thread_snapshot)) {
39236c6e 748 /* wrap and overwrite */
d9a64523 749 current_buffer->end_point = current_record_start;
fe8ab488 750 current_buffer->current_position = 0;
143464d5
A
751 if (current_record_start == 0) {
752 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
753 goto cancel_sample;
754 }
39236c6e
A
755 goto copytobuffer;
756 }
757
fe8ab488 758 thsnap = (struct thread_snapshot *)(uintptr_t)(current_buffer->buffer + current_buffer->current_position);
39236c6e
A
759 bzero(thsnap, sizeof(*thsnap));
760
761 thsnap->snapshot_magic = STACKSHOT_THREAD_SNAPSHOT_MAGIC;
762 thsnap->thread_id = thread_tid(thread);
763 thsnap->state = thread->state;
3e170ce0 764 thsnap->priority = thread->base_pri;
39236c6e
A
765 thsnap->sched_pri = thread->sched_pri;
766 thsnap->sched_flags = thread->sched_flags;
767 thsnap->ss_flags |= kStacksPCOnly;
fe8ab488 768 thsnap->ts_qos = thread->effective_policy.thep_qos;
3e170ce0 769 thsnap->ts_rqos = thread->requested_policy.thrp_qos;
d9a64523 770 thsnap->ts_rqos_override = MAX(thread->requested_policy.thrp_qos_override,
0a7de745 771 thread->requested_policy.thrp_qos_workq_override);
39236c6e 772
39037602 773 if (proc_get_effective_thread_policy(thread, TASK_POLICY_DARWIN_BG)) {
39236c6e
A
774 thsnap->ss_flags |= kThreadDarwinBG;
775 }
776
777 thsnap->user_time = timer_grab(&thread->user_timer);
778
779 uint64_t tval = timer_grab(&thread->system_timer);
780
781 if (thread->precise_user_kernel_time) {
782 thsnap->system_time = tval;
783 } else {
784 thsnap->user_time += tval;
785 thsnap->system_time = 0;
786 }
787
fe8ab488 788 current_buffer->current_position += sizeof(struct thread_snapshot);
39236c6e
A
789
790 /*
791 * If this thread has a dispatch queue serial number, include it here.
792 */
793 if (dqserialnum_valid) {
fe8ab488 794 if ((current_buffer->size - current_buffer->current_position) < sizeof(dqserialnum)) {
39236c6e 795 /* wrap and overwrite */
d9a64523 796 current_buffer->end_point = current_record_start;
fe8ab488 797 current_buffer->current_position = 0;
143464d5
A
798 if (current_record_start == 0) {
799 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
800 goto cancel_sample;
801 }
39236c6e
A
802 goto copytobuffer;
803 }
804
805 thsnap->ss_flags |= kHasDispatchSerial;
0a7de745
A
806 bcopy(&dqserialnum, (char *)current_buffer->buffer + current_buffer->current_position, sizeof(dqserialnum));
807 current_buffer->current_position += sizeof(dqserialnum);
39236c6e
A
808 }
809
cb323159 810 if (user64_regs) {
39236c6e
A
811 framesize = 8;
812 thsnap->ss_flags |= kUser64_p;
813 } else {
814 framesize = 4;
815 }
816
39236c6e
A
817 /*
818 * If we can't fit this entire stacktrace then cancel this record, wrap to the beginning,
819 * and start again there so that we always store a full record.
820 */
0a7de745 821 if ((current_buffer->size - current_buffer->current_position) / framesize < btcount) {
fe8ab488
A
822 current_buffer->end_point = current_record_start;
823 current_buffer->current_position = 0;
143464d5
A
824 if (current_record_start == 0) {
825 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
826 goto cancel_sample;
827 }
39236c6e
A
828 goto copytobuffer;
829 }
830
0a7de745 831 for (bti = 0; bti < btcount; bti++, current_buffer->current_position += framesize) {
39236c6e 832 if (framesize == 8) {
cc8bc92a 833 *(uint64_t *)(uintptr_t)(current_buffer->buffer + current_buffer->current_position) = frames[bti];
39236c6e 834 } else {
cc8bc92a 835 *(uint32_t *)(uintptr_t)(current_buffer->buffer + current_buffer->current_position) = (uint32_t)frames[bti];
39236c6e
A
836 }
837 }
838
fe8ab488 839 if (current_buffer->end_point < current_buffer->current_position) {
39236c6e
A
840 /*
841 * Each time the cursor wraps around to the beginning, we leave a
842 * differing amount of unused space at the end of the buffer. Make
843 * sure the cursor pushes the end point in case we're making use of
844 * more of the buffer than we did the last time we wrapped.
845 */
fe8ab488 846 current_buffer->end_point = current_buffer->current_position;
39236c6e
A
847 }
848
849 thsnap->nuser_frames = btcount;
850
fe8ab488
A
851 /*
852 * Now THIS is a hack.
853 */
854 if (current_buffer == &telemetry_buffer) {
855 telemetry_bytes_since_last_mark += (current_buffer->current_position - current_record_start);
856 if (telemetry_bytes_since_last_mark > telemetry_buffer_notify_at) {
857 notify = TRUE;
858 }
39236c6e
A
859 }
860
143464d5 861cancel_sample:
39236c6e
A
862 TELEMETRY_UNLOCK();
863
d9a64523 864 KDBG(MACHDBG_CODE(DBG_MACH_STACKSHOT, MICROSTACKSHOT_RECORD) | DBG_FUNC_END,
0a7de745
A
865 notify, telemetry_bytes_since_last_mark,
866 current_buffer->current_position, current_buffer->end_point);
39236c6e
A
867
868 if (notify) {
869 telemetry_notify_user();
870 }
871
872 if (uuid_info_array != NULL) {
873 kfree(uuid_info_array, uuid_info_array_size);
874 }
875}
876
877#if TELEMETRY_DEBUG
878static void
879log_telemetry_output(vm_offset_t buf, uint32_t pos, uint32_t sz)
880{
881 struct micro_snapshot *p;
882 uint32_t offset;
d9a64523 883
39236c6e
A
884 printf("Copying out %d bytes of telemetry at offset %d\n", sz, pos);
885
886 buf += pos;
887
888 /*
889 * Find and log each timestamp in this chunk of buffer.
890 */
891 for (offset = 0; offset < sz; offset++) {
892 p = (struct micro_snapshot *)(buf + offset);
893 if (p->snapshot_magic == STACKSHOT_MICRO_SNAPSHOT_MAGIC) {
894 printf("telemetry timestamp: %lld\n", p->ms_time);
895 }
896 }
897}
898#endif
899
0a7de745
A
900int
901telemetry_gather(user_addr_t buffer, uint32_t *length, boolean_t mark)
fe8ab488
A
902{
903 return telemetry_buffer_gather(buffer, length, mark, &telemetry_buffer);
904}
905
0a7de745
A
906int
907telemetry_buffer_gather(user_addr_t buffer, uint32_t *length, boolean_t mark, struct micro_snapshot_buffer * current_buffer)
39236c6e
A
908{
909 int result = 0;
910 uint32_t oldest_record_offset;
911
d9a64523 912 KDBG(MACHDBG_CODE(DBG_MACH_STACKSHOT, MICROSTACKSHOT_GATHER) | DBG_FUNC_START,
0a7de745
A
913 mark, telemetry_bytes_since_last_mark, 0,
914 (&telemetry_buffer != current_buffer));
39236c6e
A
915
916 TELEMETRY_LOCK();
917
fe8ab488 918 if (current_buffer->buffer == 0) {
d9a64523 919 *length = 0;
39236c6e
A
920 goto out;
921 }
922
fe8ab488 923 if (*length < current_buffer->size) {
39236c6e
A
924 result = KERN_NO_SPACE;
925 goto out;
926 }
927
928 /*
929 * Copy the ring buffer out to userland in order sorted by time: least recent to most recent.
930 * First, we need to search forward from the cursor to find the oldest record in our buffer.
931 */
fe8ab488 932 oldest_record_offset = current_buffer->current_position;
39236c6e 933 do {
fe8ab488
A
934 if (((oldest_record_offset + sizeof(uint32_t)) > current_buffer->size) ||
935 ((oldest_record_offset + sizeof(uint32_t)) > current_buffer->end_point)) {
fe8ab488 936 if (*(uint32_t *)(uintptr_t)(current_buffer->buffer) == 0) {
39236c6e
A
937 /*
938 * There is no magic number at the start of the buffer, which means
939 * it's empty; nothing to see here yet.
940 */
941 *length = 0;
942 goto out;
943 }
944 /*
945 * We've looked through the end of the active buffer without finding a valid
946 * record; that means all valid records are in a single chunk, beginning at
947 * the very start of the buffer.
948 */
949
950 oldest_record_offset = 0;
fe8ab488 951 assert(*(uint32_t *)(uintptr_t)(current_buffer->buffer) == STACKSHOT_MICRO_SNAPSHOT_MAGIC);
39236c6e
A
952 break;
953 }
954
0a7de745 955 if (*(uint32_t *)(uintptr_t)(current_buffer->buffer + oldest_record_offset) == STACKSHOT_MICRO_SNAPSHOT_MAGIC) {
39236c6e 956 break;
0a7de745 957 }
39236c6e
A
958
959 /*
960 * There are no alignment guarantees for micro-stackshot records, so we must search at each
961 * byte offset.
962 */
963 oldest_record_offset++;
fe8ab488 964 } while (oldest_record_offset != current_buffer->current_position);
39236c6e
A
965
966 /*
967 * If needed, copyout in two chunks: from the oldest record to the end of the buffer, and then
968 * from the beginning of the buffer up to the current position.
969 */
970 if (oldest_record_offset != 0) {
971#if TELEMETRY_DEBUG
fe8ab488 972 log_telemetry_output(current_buffer->buffer, oldest_record_offset,
0a7de745 973 current_buffer->end_point - oldest_record_offset);
39236c6e 974#endif
fe8ab488
A
975 if ((result = copyout((void *)(current_buffer->buffer + oldest_record_offset), buffer,
976 current_buffer->end_point - oldest_record_offset)) != 0) {
39236c6e
A
977 *length = 0;
978 goto out;
979 }
fe8ab488 980 *length = current_buffer->end_point - oldest_record_offset;
39236c6e
A
981 } else {
982 *length = 0;
983 }
984
985#if TELEMETRY_DEBUG
fe8ab488 986 log_telemetry_output(current_buffer->buffer, 0, current_buffer->current_position);
39236c6e 987#endif
fe8ab488
A
988 if ((result = copyout((void *)current_buffer->buffer, buffer + *length,
989 current_buffer->current_position)) != 0) {
39236c6e
A
990 *length = 0;
991 goto out;
992 }
fe8ab488 993 *length += (uint32_t)current_buffer->current_position;
39236c6e
A
994
995out:
996
997 if (mark && (*length > 0)) {
998 telemetry_bytes_since_last_mark = 0;
999 }
1000
1001 TELEMETRY_UNLOCK();
1002
d9a64523 1003 KDBG(MACHDBG_CODE(DBG_MACH_STACKSHOT, MICROSTACKSHOT_GATHER) | DBG_FUNC_END,
0a7de745
A
1004 current_buffer->current_position, *length,
1005 current_buffer->end_point, (&telemetry_buffer != current_buffer));
39236c6e 1006
0a7de745 1007 return result;
39236c6e
A
1008}
1009
1010/************************/
1011/* BOOT PROFILE SUPPORT */
1012/************************/
1013/*
1014 * Boot Profiling
1015 *
1016 * The boot-profiling support is a mechanism to sample activity happening on the
1017 * system during boot. This mechanism sets up a periodic timer and on every timer fire,
1018 * captures a full backtrace into the boot profiling buffer. This buffer can be pulled
1019 * out and analyzed from user-space. It is turned on using the following boot-args:
1020 * "bootprofile_buffer_size" specifies the size of the boot profile buffer
1021 * "bootprofile_interval_ms" specifies the interval for the profiling timer
1022 *
1023 * Process Specific Boot Profiling
1024 *
1025 * The boot-arg "bootprofile_proc_name" can be used to specify a certain
1026 * process that needs to profiled during boot. Setting this boot-arg changes
1027 * the way stackshots are captured. At every timer fire, the code looks at the
1028 * currently running process and takes a stackshot only if the requested process
1029 * is on-core (which makes it unsuitable for MP systems).
1030 *
fe8ab488
A
1031 * Trigger Events
1032 *
1033 * The boot-arg "bootprofile_type=boot" starts the timer during early boot. Using
1034 * "wake" starts the timer at AP wake from suspend-to-RAM.
39236c6e
A
1035 */
1036
1037#define BOOTPROFILE_MAX_BUFFER_SIZE (64*1024*1024) /* see also COPYSIZELIMIT_PANIC */
1038
0a7de745
A
1039vm_offset_t bootprofile_buffer = 0;
1040uint32_t bootprofile_buffer_size = 0;
1041uint32_t bootprofile_buffer_current_position = 0;
1042uint32_t bootprofile_interval_ms = 0;
1043uint32_t bootprofile_stackshot_flags = 0;
1044uint64_t bootprofile_interval_abs = 0;
1045uint64_t bootprofile_next_deadline = 0;
1046uint32_t bootprofile_all_procs = 0;
1047char bootprofile_proc_name[17];
39037602 1048uint64_t bootprofile_delta_since_timestamp = 0;
0a7de745
A
1049lck_grp_t bootprofile_lck_grp;
1050lck_mtx_t bootprofile_mtx;
39236c6e 1051
39037602 1052
fe8ab488
A
1053enum {
1054 kBootProfileDisabled = 0,
1055 kBootProfileStartTimerAtBoot,
1056 kBootProfileStartTimerAtWake
1057} bootprofile_type = kBootProfileDisabled;
1058
1059
0a7de745 1060static timer_call_data_t bootprofile_timer_call_entry;
39236c6e
A
1061
1062#define BOOTPROFILE_LOCK() do { lck_mtx_lock(&bootprofile_mtx); } while(0)
1063#define BOOTPROFILE_TRY_SPIN_LOCK() lck_mtx_try_lock_spin(&bootprofile_mtx)
1064#define BOOTPROFILE_UNLOCK() do { lck_mtx_unlock(&bootprofile_mtx); } while(0)
1065
1066static void bootprofile_timer_call(
1067 timer_call_param_t param0,
1068 timer_call_param_t param1);
1069
0a7de745
A
1070void
1071bootprofile_init(void)
39236c6e
A
1072{
1073 kern_return_t ret;
fe8ab488 1074 char type[32];
39236c6e
A
1075
1076 lck_grp_init(&bootprofile_lck_grp, "bootprofile group", LCK_GRP_ATTR_NULL);
1077 lck_mtx_init(&bootprofile_mtx, &bootprofile_lck_grp, LCK_ATTR_NULL);
1078
1079 if (!PE_parse_boot_argn("bootprofile_buffer_size", &bootprofile_buffer_size, sizeof(bootprofile_buffer_size))) {
1080 bootprofile_buffer_size = 0;
1081 }
1082
0a7de745 1083 if (bootprofile_buffer_size > BOOTPROFILE_MAX_BUFFER_SIZE) {
39236c6e 1084 bootprofile_buffer_size = BOOTPROFILE_MAX_BUFFER_SIZE;
0a7de745 1085 }
39236c6e
A
1086
1087 if (!PE_parse_boot_argn("bootprofile_interval_ms", &bootprofile_interval_ms, sizeof(bootprofile_interval_ms))) {
1088 bootprofile_interval_ms = 0;
1089 }
1090
39037602
A
1091 if (!PE_parse_boot_argn("bootprofile_stackshot_flags", &bootprofile_stackshot_flags, sizeof(bootprofile_stackshot_flags))) {
1092 bootprofile_stackshot_flags = 0;
1093 }
1094
39236c6e
A
1095 if (!PE_parse_boot_argn("bootprofile_proc_name", &bootprofile_proc_name, sizeof(bootprofile_proc_name))) {
1096 bootprofile_all_procs = 1;
1097 bootprofile_proc_name[0] = '\0';
1098 }
1099
fe8ab488
A
1100 if (PE_parse_boot_argn("bootprofile_type", type, sizeof(type))) {
1101 if (0 == strcmp(type, "boot")) {
1102 bootprofile_type = kBootProfileStartTimerAtBoot;
1103 } else if (0 == strcmp(type, "wake")) {
d9a64523 1104 bootprofile_type = kBootProfileStartTimerAtWake;
fe8ab488
A
1105 } else {
1106 bootprofile_type = kBootProfileDisabled;
1107 }
1108 } else {
1109 bootprofile_type = kBootProfileDisabled;
1110 }
1111
39236c6e
A
1112 clock_interval_to_absolutetime_interval(bootprofile_interval_ms, NSEC_PER_MSEC, &bootprofile_interval_abs);
1113
1114 /* Both boot args must be set to enable */
fe8ab488 1115 if ((bootprofile_type == kBootProfileDisabled) || (bootprofile_buffer_size == 0) || (bootprofile_interval_abs == 0)) {
39236c6e
A
1116 return;
1117 }
1118
3e170ce0 1119 ret = kmem_alloc(kernel_map, &bootprofile_buffer, bootprofile_buffer_size, VM_KERN_MEMORY_DIAG);
39236c6e
A
1120 if (ret != KERN_SUCCESS) {
1121 kprintf("Boot profile: Allocation failed: %d\n", ret);
1122 return;
1123 }
fe8ab488 1124 bzero((void *) bootprofile_buffer, bootprofile_buffer_size);
39236c6e 1125
0a7de745
A
1126 kprintf("Boot profile: Sampling %s once per %u ms at %s\n", bootprofile_all_procs ? "all procs" : bootprofile_proc_name, bootprofile_interval_ms,
1127 bootprofile_type == kBootProfileStartTimerAtBoot ? "boot" : (bootprofile_type == kBootProfileStartTimerAtWake ? "wake" : "unknown"));
39236c6e
A
1128
1129 timer_call_setup(&bootprofile_timer_call_entry,
0a7de745
A
1130 bootprofile_timer_call,
1131 NULL);
39236c6e 1132
fe8ab488
A
1133 if (bootprofile_type == kBootProfileStartTimerAtBoot) {
1134 bootprofile_next_deadline = mach_absolute_time() + bootprofile_interval_abs;
1135 timer_call_enter_with_leeway(&bootprofile_timer_call_entry,
0a7de745
A
1136 NULL,
1137 bootprofile_next_deadline,
1138 0,
1139 TIMER_CALL_SYS_NORMAL,
1140 FALSE);
fe8ab488 1141 }
39236c6e
A
1142}
1143
fe8ab488
A
1144void
1145bootprofile_wake_from_sleep(void)
1146{
1147 if (bootprofile_type == kBootProfileStartTimerAtWake) {
1148 bootprofile_next_deadline = mach_absolute_time() + bootprofile_interval_abs;
1149 timer_call_enter_with_leeway(&bootprofile_timer_call_entry,
0a7de745
A
1150 NULL,
1151 bootprofile_next_deadline,
1152 0,
1153 TIMER_CALL_SYS_NORMAL,
1154 FALSE);
fe8ab488
A
1155 }
1156}
1157
1158
39037602
A
1159static void
1160bootprofile_timer_call(
39236c6e
A
1161 timer_call_param_t param0 __unused,
1162 timer_call_param_t param1 __unused)
1163{
1164 unsigned retbytes = 0;
1165 int pid_to_profile = -1;
1166
1167 if (!BOOTPROFILE_TRY_SPIN_LOCK()) {
1168 goto reprogram;
1169 }
1170
1171 /* Check if process-specific boot profiling is turned on */
1172 if (!bootprofile_all_procs) {
1173 /*
1174 * Since boot profiling initializes really early in boot, it is
1175 * possible that at this point, the task/proc is not initialized.
1176 * Nothing to do in that case.
1177 */
1178
1179 if ((current_task() != NULL) && (current_task()->bsd_info != NULL) &&
1180 (0 == strncmp(bootprofile_proc_name, proc_name_address(current_task()->bsd_info), 17))) {
1181 pid_to_profile = proc_selfpid();
0a7de745 1182 } else {
39236c6e
A
1183 /*
1184 * Process-specific boot profiling requested but the on-core process is
1185 * something else. Nothing to do here.
1186 */
1187 BOOTPROFILE_UNLOCK();
1188 goto reprogram;
1189 }
1190 }
1191
1192 /* initiate a stackshot with whatever portion of the buffer is left */
1193 if (bootprofile_buffer_current_position < bootprofile_buffer_size) {
39037602 1194 uint32_t flags = STACKSHOT_KCDATA_FORMAT | STACKSHOT_TRYLOCK | STACKSHOT_SAVE_LOADINFO
0a7de745 1195 | STACKSHOT_GET_GLOBAL_MEM_STATS;
cb323159 1196#if !CONFIG_EMBEDDED
39037602 1197 flags |= STACKSHOT_SAVE_KEXT_LOADINFO;
cb323159 1198#endif
39037602
A
1199
1200
1201 /* OR on flags specified in boot-args */
1202 flags |= bootprofile_stackshot_flags;
1203 if ((flags & STACKSHOT_COLLECT_DELTA_SNAPSHOT) && (bootprofile_delta_since_timestamp == 0)) {
1204 /* Can't take deltas until the first one */
0a7de745 1205 flags &= ~STACKSHOT_COLLECT_DELTA_SNAPSHOT;
39037602
A
1206 }
1207
1208 uint64_t timestamp = 0;
1209 if (bootprofile_stackshot_flags & STACKSHOT_COLLECT_DELTA_SNAPSHOT) {
1210 timestamp = mach_absolute_time();
1211 }
1212
1213 kern_return_t r = stack_snapshot_from_kernel(
0a7de745
A
1214 pid_to_profile, (void *)(bootprofile_buffer + bootprofile_buffer_current_position),
1215 bootprofile_buffer_size - bootprofile_buffer_current_position,
39037602
A
1216 flags, bootprofile_delta_since_timestamp, &retbytes);
1217
1218 /*
1219 * We call with STACKSHOT_TRYLOCK because the stackshot lock is coarser
1220 * than the bootprofile lock. If someone else has the lock we'll just
1221 * try again later.
1222 */
1223
1224 if (r == KERN_LOCK_OWNED) {
1225 BOOTPROFILE_UNLOCK();
1226 goto reprogram;
1227 }
1228
0a7de745
A
1229 if (bootprofile_stackshot_flags & STACKSHOT_COLLECT_DELTA_SNAPSHOT &&
1230 r == KERN_SUCCESS) {
39037602
A
1231 bootprofile_delta_since_timestamp = timestamp;
1232 }
39236c6e
A
1233
1234 bootprofile_buffer_current_position += retbytes;
1235 }
1236
1237 BOOTPROFILE_UNLOCK();
1238
1239 /* If we didn't get any data or have run out of buffer space, stop profiling */
1240 if ((retbytes == 0) || (bootprofile_buffer_current_position == bootprofile_buffer_size)) {
1241 return;
1242 }
1243
1244
1245reprogram:
1246 /* If the user gathered the buffer, no need to keep profiling */
1247 if (bootprofile_interval_abs == 0) {
1248 return;
1249 }
1250
1251 clock_deadline_for_periodic_event(bootprofile_interval_abs,
0a7de745
A
1252 mach_absolute_time(),
1253 &bootprofile_next_deadline);
39236c6e 1254 timer_call_enter_with_leeway(&bootprofile_timer_call_entry,
0a7de745
A
1255 NULL,
1256 bootprofile_next_deadline,
1257 0,
1258 TIMER_CALL_SYS_NORMAL,
1259 FALSE);
39236c6e
A
1260}
1261
0a7de745
A
1262void
1263bootprofile_get(void **buffer, uint32_t *length)
39037602
A
1264{
1265 BOOTPROFILE_LOCK();
1266 *buffer = (void*) bootprofile_buffer;
1267 *length = bootprofile_buffer_current_position;
1268 BOOTPROFILE_UNLOCK();
1269}
1270
0a7de745
A
1271int
1272bootprofile_gather(user_addr_t buffer, uint32_t *length)
39236c6e
A
1273{
1274 int result = 0;
1275
1276 BOOTPROFILE_LOCK();
1277
1278 if (bootprofile_buffer == 0) {
d9a64523 1279 *length = 0;
39236c6e
A
1280 goto out;
1281 }
1282
1283 if (*length < bootprofile_buffer_current_position) {
1284 result = KERN_NO_SPACE;
1285 goto out;
1286 }
1287
1288 if ((result = copyout((void *)bootprofile_buffer, buffer,
1289 bootprofile_buffer_current_position)) != 0) {
1290 *length = 0;
1291 goto out;
1292 }
1293 *length = bootprofile_buffer_current_position;
1294
1295 /* cancel future timers */
1296 bootprofile_interval_abs = 0;
1297
1298out:
1299
1300 BOOTPROFILE_UNLOCK();
1301
0a7de745 1302 return result;
39236c6e 1303}