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