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