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