1 /*
2 * Copyright (c) 2012-2020 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/coalition.h>
36 #include <kern/debug.h>
37 #include <kern/host.h>
38 #include <kern/kalloc.h>
39 #include <kern/kern_types.h>
40 #include <kern/locks.h>
41 #include <kern/misc_protos.h>
42 #include <kern/sched.h>
43 #include <kern/sched_prim.h>
44 #include <kern/telemetry.h>
45 #include <kern/timer_call.h>
46 #include <kern/policy_internal.h>
47 #include <kern/kcdata.h>
48
49 #include <pexpert/pexpert.h>
50
51 #include <string.h>
52 #include <vm/vm_kern.h>
53 #include <vm/vm_shared_region.h>
54
55 #include <kperf/callstack.h>
56 #include <kern/backtrace.h>
57 #include <kern/monotonic.h>
58
59 #include <security/mac_mach_internal.h>
60
61 #include <sys/errno.h>
62 #include <sys/kdebug.h>
63 #include <uuid/uuid.h>
64 #include <kdp/kdp_dyld.h>
65
66 #define TELEMETRY_DEBUG 0
67
68 struct proc;
69 extern int proc_pid(struct proc *);
70 extern char *proc_name_address(void *p);
71 extern uint64_t proc_uniqueid(void *p);
72 extern uint64_t proc_was_throttled(void *p);
73 extern uint64_t proc_did_throttle(void *p);
74 extern int proc_selfpid(void);
75 extern boolean_t task_did_exec(task_t task);
76 extern boolean_t task_is_exec_copy(task_t task);
77
78 struct micro_snapshot_buffer {
79 vm_offset_t buffer;
80 uint32_t size;
81 uint32_t current_position;
82 uint32_t end_point;
83 };
84
85 static bool telemetry_task_ready_for_sample(task_t task);
86
87 static void telemetry_instrumentation_begin(
88 struct micro_snapshot_buffer *buffer, enum micro_snapshot_flags flags);
89
90 static void telemetry_instrumentation_end(struct micro_snapshot_buffer *buffer);
91
92 static void telemetry_take_sample(thread_t thread, enum micro_snapshot_flags flags);
93
94 #if CONFIG_MACF
95 static void telemetry_macf_take_sample(thread_t thread, enum micro_snapshot_flags flags);
96 #endif
97
98 struct telemetry_target {
99 thread_t thread;
100 uintptr_t *frames;
101 size_t frames_count;
102 bool user64_regs;
103 uint16_t async_start_index;
104 enum micro_snapshot_flags microsnapshot_flags;
105 struct micro_snapshot_buffer *buffer;
106 lck_mtx_t *buffer_mtx;
107 };
108
109 static int telemetry_process_sample(
110 const struct telemetry_target *target,
111 bool release_buffer_lock,
112 uint32_t *out_current_record_start);
113
114 static int telemetry_buffer_gather(
115 user_addr_t buffer,
116 uint32_t *length,
117 bool mark,
118 struct micro_snapshot_buffer *current_buffer);
119
120 #define TELEMETRY_DEFAULT_SAMPLE_RATE (1) /* 1 sample every 1 second */
121 #define TELEMETRY_DEFAULT_BUFFER_SIZE (16*1024)
122 #define TELEMETRY_MAX_BUFFER_SIZE (64*1024)
123
124 #define TELEMETRY_DEFAULT_NOTIFY_LEEWAY (4*1024) // Userland gets 4k of leeway to collect data after notification
125 #define TELEMETRY_MAX_UUID_COUNT (128) // Max of 128 non-shared-cache UUIDs to log for symbolication
126
127 uint32_t telemetry_sample_rate = 0;
128 volatile boolean_t telemetry_needs_record = FALSE;
129 volatile boolean_t telemetry_needs_timer_arming_record = FALSE;
130
131 /*
132 * If TRUE, record micro-stackshot samples for all tasks.
133 * If FALSE, only sample tasks which are marked for telemetry.
134 */
135 bool telemetry_sample_all_tasks = false;
136 bool telemetry_sample_pmis = false;
137 uint32_t telemetry_active_tasks = 0; // Number of tasks opted into telemetry
138
139 uint32_t telemetry_timestamp = 0;
140
141 /*
142 * The telemetry_buffer is responsible
143 * for timer samples and interrupt samples that are driven by
144 * compute_averages(). It will notify its client (if one
145 * exists) when it has enough data to be worth flushing.
146 */
147 struct micro_snapshot_buffer telemetry_buffer = {
148 .buffer = 0,
149 .size = 0,
150 .current_position = 0,
151 .end_point = 0
152 };
153
154 #if CONFIG_MACF
155 #define TELEMETRY_MACF_DEFAULT_BUFFER_SIZE (16*1024)
156 /*
157 * The MAC framework uses its own telemetry buffer for the purposes of auditing
158 * security-related work being done by userland threads.
159 */
160 struct micro_snapshot_buffer telemetry_macf_buffer = {
161 .buffer = 0,
162 .size = 0,
163 .current_position = 0,
164 .end_point = 0
165 };
166 #endif
167
168 int telemetry_bytes_since_last_mark = -1; // How much data since buf was last marked?
169 int telemetry_buffer_notify_at = 0;
170
171 LCK_GRP_DECLARE(telemetry_lck_grp, "telemetry group");
172 LCK_MTX_DECLARE(telemetry_mtx, &telemetry_lck_grp);
173 LCK_MTX_DECLARE(telemetry_pmi_mtx, &telemetry_lck_grp);
174 LCK_MTX_DECLARE(telemetry_macf_mtx, &telemetry_lck_grp);
175
176 #define TELEMETRY_LOCK() do { lck_mtx_lock(&telemetry_mtx); } while (0)
177 #define TELEMETRY_TRY_SPIN_LOCK() lck_mtx_try_lock_spin(&telemetry_mtx)
178 #define TELEMETRY_UNLOCK() do { lck_mtx_unlock(&telemetry_mtx); } while (0)
179
180 #define TELEMETRY_PMI_LOCK() do { lck_mtx_lock(&telemetry_pmi_mtx); } while (0)
181 #define TELEMETRY_PMI_UNLOCK() do { lck_mtx_unlock(&telemetry_pmi_mtx); } while (0)
182
183 #define TELEMETRY_MACF_LOCK() do { lck_mtx_lock(&telemetry_macf_mtx); } while (0)
184 #define TELEMETRY_MACF_UNLOCK() do { lck_mtx_unlock(&telemetry_macf_mtx); } while (0)
185
186 void
telemetry_init(void)187 telemetry_init(void)
188 {
189 kern_return_t ret;
190 uint32_t telemetry_notification_leeway;
191
192 if (!PE_parse_boot_argn("telemetry_buffer_size",
193 &telemetry_buffer.size, sizeof(telemetry_buffer.size))) {
194 telemetry_buffer.size = TELEMETRY_DEFAULT_BUFFER_SIZE;
195 }
196
197 if (telemetry_buffer.size > TELEMETRY_MAX_BUFFER_SIZE) {
198 telemetry_buffer.size = TELEMETRY_MAX_BUFFER_SIZE;
199 }
200
201 ret = kmem_alloc(kernel_map, &telemetry_buffer.buffer, telemetry_buffer.size,
202 KMA_DATA | KMA_ZERO | KMA_PERMANENT, VM_KERN_MEMORY_DIAG);
203 if (ret != KERN_SUCCESS) {
204 kprintf("Telemetry: Allocation failed: %d\n", ret);
205 return;
206 }
207
208 if (!PE_parse_boot_argn("telemetry_notification_leeway",
209 &telemetry_notification_leeway, sizeof(telemetry_notification_leeway))) {
210 /*
211 * By default, notify the user to collect the buffer when there is this much space left in the buffer.
212 */
213 telemetry_notification_leeway = TELEMETRY_DEFAULT_NOTIFY_LEEWAY;
214 }
215 if (telemetry_notification_leeway >= telemetry_buffer.size) {
216 printf("telemetry: nonsensical telemetry_notification_leeway boot-arg %d changed to %d\n",
217 telemetry_notification_leeway, TELEMETRY_DEFAULT_NOTIFY_LEEWAY);
218 telemetry_notification_leeway = TELEMETRY_DEFAULT_NOTIFY_LEEWAY;
219 }
220 telemetry_buffer_notify_at = telemetry_buffer.size - telemetry_notification_leeway;
221
222 if (!PE_parse_boot_argn("telemetry_sample_rate",
223 &telemetry_sample_rate, sizeof(telemetry_sample_rate))) {
224 telemetry_sample_rate = TELEMETRY_DEFAULT_SAMPLE_RATE;
225 }
226
227 /*
228 * To enable telemetry for all tasks, include "telemetry_sample_all_tasks=1" in boot-args.
229 */
230 if (!PE_parse_boot_argn("telemetry_sample_all_tasks",
231 &telemetry_sample_all_tasks, sizeof(telemetry_sample_all_tasks))) {
232 #if !defined(XNU_TARGET_OS_OSX) && !(DEVELOPMENT || DEBUG)
233 telemetry_sample_all_tasks = false;
234 #else
235 telemetry_sample_all_tasks = true;
236 #endif /* !defined(XNU_TARGET_OS_OSX) && !(DEVELOPMENT || DEBUG) */
237 }
238
239 kprintf("Telemetry: Sampling %stasks once per %u second%s\n",
240 (telemetry_sample_all_tasks) ? "all " : "",
241 telemetry_sample_rate, telemetry_sample_rate == 1 ? "" : "s");
242 }
243
244 /*
245 * Enable or disable global microstackshots (ie telemetry_sample_all_tasks).
246 *
247 * enable_disable == 1: turn it on
248 * enable_disable == 0: turn it off
249 */
250 void
telemetry_global_ctl(int enable_disable)251 telemetry_global_ctl(int enable_disable)
252 {
253 if (enable_disable == 1) {
254 telemetry_sample_all_tasks = true;
255 } else {
256 telemetry_sample_all_tasks = false;
257 }
258 }
259
260 /*
261 * Opt the given task into or out of the telemetry stream.
262 *
263 * Supported reasons (callers may use any or all of):
264 * TF_CPUMON_WARNING
265 * TF_WAKEMON_WARNING
266 *
267 * enable_disable == 1: turn it on
268 * enable_disable == 0: turn it off
269 */
270 void
telemetry_task_ctl(task_t task,uint32_t reasons,int enable_disable)271 telemetry_task_ctl(task_t task, uint32_t reasons, int enable_disable)
272 {
273 task_lock(task);
274 telemetry_task_ctl_locked(task, reasons, enable_disable);
275 task_unlock(task);
276 }
277
278 void
telemetry_task_ctl_locked(task_t task,uint32_t reasons,int enable_disable)279 telemetry_task_ctl_locked(task_t task, uint32_t reasons, int enable_disable)
280 {
281 uint32_t origflags;
282
283 assert((reasons != 0) && ((reasons | TF_TELEMETRY) == TF_TELEMETRY));
284
285 task_lock_assert_owned(task);
286
287 origflags = task->t_flags;
288
289 if (enable_disable == 1) {
290 task->t_flags |= reasons;
291 if ((origflags & TF_TELEMETRY) == 0) {
292 OSIncrementAtomic(&telemetry_active_tasks);
293 #if TELEMETRY_DEBUG
294 printf("%s: telemetry OFF -> ON (%d active)\n", proc_name_address(get_bsdtask_info(task)), telemetry_active_tasks);
295 #endif
296 }
297 } else {
298 task->t_flags &= ~reasons;
299 if (((origflags & TF_TELEMETRY) != 0) && ((task->t_flags & TF_TELEMETRY) == 0)) {
300 /*
301 * If this task went from having at least one telemetry bit to having none,
302 * the net change was to disable telemetry for the task.
303 */
304 OSDecrementAtomic(&telemetry_active_tasks);
305 #if TELEMETRY_DEBUG
306 printf("%s: telemetry ON -> OFF (%d active)\n", proc_name_address(get_bsdtask_info(task)), telemetry_active_tasks);
307 #endif
308 }
309 }
310 }
311
312 /*
313 * Determine if the current thread is eligible for telemetry:
314 *
315 * telemetry_sample_all_tasks: All threads are eligible. This takes precedence.
316 * telemetry_active_tasks: Count of tasks opted in.
317 * task->t_flags & TF_TELEMETRY: This task is opted in.
318 */
319 static bool
telemetry_is_active(thread_t thread)320 telemetry_is_active(thread_t thread)
321 {
322 task_t task = get_threadtask(thread);
323
324 if (task == kernel_task) {
325 /* Kernel threads never return to an AST boundary, and are ineligible */
326 return false;
327 }
328
329 if (telemetry_sample_all_tasks || telemetry_sample_pmis) {
330 return true;
331 }
332
333 if ((telemetry_active_tasks > 0) && ((task->t_flags & TF_TELEMETRY) != 0)) {
334 return true;
335 }
336
337 return false;
338 }
339
340 /*
341 * Userland is arming a timer. If we are eligible for such a record,
342 * sample now. No need to do this one at the AST because we're already at
343 * a safe place in this system call.
344 */
345 int
telemetry_timer_event(__unused uint64_t deadline,__unused uint64_t interval,__unused uint64_t leeway)346 telemetry_timer_event(__unused uint64_t deadline, __unused uint64_t interval, __unused uint64_t leeway)
347 {
348 if (telemetry_needs_timer_arming_record == TRUE) {
349 telemetry_needs_timer_arming_record = FALSE;
350 telemetry_take_sample(current_thread(), (enum micro_snapshot_flags)(kTimerArmingRecord | kUserMode));
351 }
352
353 return 0;
354 }
355
356 #if MONOTONIC
357 static void
telemetry_pmi_handler(bool user_mode,__unused void * ctx)358 telemetry_pmi_handler(bool user_mode, __unused void *ctx)
359 {
360 telemetry_mark_curthread(user_mode, TRUE);
361 }
362 #endif /* MONOTONIC */
363
364 int
telemetry_pmi_setup(enum telemetry_pmi pmi_ctr,uint64_t period)365 telemetry_pmi_setup(enum telemetry_pmi pmi_ctr, uint64_t period)
366 {
367 #if MONOTONIC
368 static bool sample_all_tasks_aside = false;
369 static uint32_t active_tasks_aside = false;
370 int error = 0;
371 const char *name = "?";
372
373 unsigned int ctr = 0;
374
375 TELEMETRY_PMI_LOCK();
376
377 switch (pmi_ctr) {
378 case TELEMETRY_PMI_NONE:
379 if (!telemetry_sample_pmis) {
380 error = 1;
381 goto out;
382 }
383
384 telemetry_sample_pmis = false;
385 telemetry_sample_all_tasks = sample_all_tasks_aside;
386 telemetry_active_tasks = active_tasks_aside;
387 error = mt_microstackshot_stop();
388 if (!error) {
389 printf("telemetry: disabling ustackshot on PMI\n");
390 }
391 goto out;
392
393 case TELEMETRY_PMI_INSTRS:
394 ctr = MT_CORE_INSTRS;
395 name = "instructions";
396 break;
397
398 case TELEMETRY_PMI_CYCLES:
399 ctr = MT_CORE_CYCLES;
400 name = "cycles";
401 break;
402
403 default:
404 error = 1;
405 goto out;
406 }
407
408 telemetry_sample_pmis = true;
409 sample_all_tasks_aside = telemetry_sample_all_tasks;
410 active_tasks_aside = telemetry_active_tasks;
411 telemetry_sample_all_tasks = false;
412 telemetry_active_tasks = 0;
413
414 error = mt_microstackshot_start(ctr, period, telemetry_pmi_handler, NULL);
415 if (!error) {
416 printf("telemetry: ustackshot every %llu %s\n", period, name);
417 }
418
419 out:
420 TELEMETRY_PMI_UNLOCK();
421 return error;
422 #else /* MONOTONIC */
423 #pragma unused(pmi_ctr, period)
424 return 1;
425 #endif /* !MONOTONIC */
426 }
427
428 /*
429 * Mark the current thread for an interrupt-based
430 * telemetry record, to be sampled at the next AST boundary.
431 */
432 void
telemetry_mark_curthread(boolean_t interrupted_userspace,boolean_t pmi)433 telemetry_mark_curthread(boolean_t interrupted_userspace, boolean_t pmi)
434 {
435 uint32_t ast_bits = 0;
436 thread_t thread = current_thread();
437
438 /*
439 * If telemetry isn't active for this thread, return and try
440 * again next time.
441 */
442 if (telemetry_is_active(thread) == false) {
443 return;
444 }
445
446 ast_bits |= (interrupted_userspace ? AST_TELEMETRY_USER : AST_TELEMETRY_KERNEL);
447 if (pmi) {
448 ast_bits |= AST_TELEMETRY_PMI;
449 }
450
451 telemetry_needs_record = FALSE;
452 thread_ast_set(thread, ast_bits);
453 ast_propagate(thread);
454 }
455
456 void
compute_telemetry(void * arg __unused)457 compute_telemetry(void *arg __unused)
458 {
459 if (telemetry_sample_all_tasks || (telemetry_active_tasks > 0)) {
460 if ((++telemetry_timestamp) % telemetry_sample_rate == 0) {
461 telemetry_needs_record = TRUE;
462 telemetry_needs_timer_arming_record = TRUE;
463 }
464 }
465 }
466
467 /*
468 * If userland has registered a port for telemetry notifications, send one now.
469 */
470 static void
telemetry_notify_user(void)471 telemetry_notify_user(void)
472 {
473 mach_port_t user_port = MACH_PORT_NULL;
474
475 kern_return_t kr = host_get_telemetry_port(host_priv_self(), &user_port);
476 if ((kr != KERN_SUCCESS) || !IPC_PORT_VALID(user_port)) {
477 return;
478 }
479
480 telemetry_notification(user_port, 0);
481 ipc_port_release_send(user_port);
482 }
483
484 void
telemetry_ast(thread_t thread,ast_t reasons)485 telemetry_ast(thread_t thread, ast_t reasons)
486 {
487 assert((reasons & AST_TELEMETRY_ALL) != 0);
488
489 uint8_t record_type = 0;
490 if (reasons & AST_TELEMETRY_IO) {
491 record_type |= kIORecord;
492 }
493 if (reasons & (AST_TELEMETRY_USER | AST_TELEMETRY_KERNEL)) {
494 record_type |= (reasons & AST_TELEMETRY_PMI) ? kPMIRecord :
495 kInterruptRecord;
496 }
497
498 if ((reasons & AST_TELEMETRY_MACF) != 0) {
499 record_type |= kMACFRecord;
500 }
501
502 enum micro_snapshot_flags user_telemetry = (reasons & AST_TELEMETRY_USER) ? kUserMode : 0;
503 enum micro_snapshot_flags microsnapshot_flags = record_type | user_telemetry;
504
505 if ((reasons & AST_TELEMETRY_MACF) != 0) {
506 telemetry_macf_take_sample(thread, microsnapshot_flags);
507 }
508
509 if ((reasons & (AST_TELEMETRY_IO | AST_TELEMETRY_KERNEL | AST_TELEMETRY_PMI
510 | AST_TELEMETRY_USER)) != 0) {
511 telemetry_take_sample(thread, microsnapshot_flags);
512 }
513 }
514
515 bool
telemetry_task_ready_for_sample(task_t task)516 telemetry_task_ready_for_sample(task_t task)
517 {
518 return task != TASK_NULL &&
519 task != kernel_task &&
520 !task_did_exec(task) &&
521 !task_is_exec_copy(task);
522 }
523
524 void
telemetry_instrumentation_begin(__unused struct micro_snapshot_buffer * buffer,__unused enum micro_snapshot_flags flags)525 telemetry_instrumentation_begin(
526 __unused struct micro_snapshot_buffer *buffer,
527 __unused enum micro_snapshot_flags flags)
528 {
529 /* telemetry_XXX accessed outside of lock for instrumentation only */
530 KDBG(MACHDBG_CODE(DBG_MACH_STACKSHOT, MICROSTACKSHOT_RECORD) | DBG_FUNC_START,
531 flags, telemetry_bytes_since_last_mark, 0,
532 (&telemetry_buffer != buffer));
533 }
534
535 void
telemetry_instrumentation_end(__unused struct micro_snapshot_buffer * buffer)536 telemetry_instrumentation_end(__unused struct micro_snapshot_buffer *buffer)
537 {
538 /* telemetry_XXX accessed outside of lock for instrumentation only */
539 KDBG(MACHDBG_CODE(DBG_MACH_STACKSHOT, MICROSTACKSHOT_RECORD) | DBG_FUNC_END,
540 (&telemetry_buffer == buffer), telemetry_bytes_since_last_mark,
541 buffer->current_position, buffer->end_point);
542 }
543
544 void
telemetry_take_sample(thread_t thread,enum micro_snapshot_flags flags)545 telemetry_take_sample(thread_t thread, enum micro_snapshot_flags flags)
546 {
547 task_t task;
548 uintptr_t frames[128];
549 size_t frames_len = sizeof(frames) / sizeof(frames[0]);
550 uint32_t btcount;
551 struct backtrace_user_info btinfo = BTUINFO_INIT;
552 uint16_t async_start_index = UINT16_MAX;
553
554 if (thread == THREAD_NULL) {
555 return;
556 }
557
558 /* Ensure task is ready for taking a sample. */
559 task = get_threadtask(thread);
560 if (!telemetry_task_ready_for_sample(task)) {
561 return;
562 }
563
564 telemetry_instrumentation_begin(&telemetry_buffer, flags);
565
566 /* Collect backtrace from user thread. */
567 btcount = backtrace_user(frames, frames_len, NULL, &btinfo);
568 if (btinfo.btui_error != 0) {
569 return;
570 }
571 if (btinfo.btui_async_frame_addr != 0 &&
572 btinfo.btui_async_start_index != 0) {
573 /*
574 * Put the async callstack inline after the frame pointer walk call
575 * stack.
576 */
577 async_start_index = (uint16_t)btinfo.btui_async_start_index;
578 uintptr_t frame_addr = btinfo.btui_async_frame_addr;
579 unsigned int frames_left = frames_len - async_start_index;
580 struct backtrace_control ctl = { .btc_frame_addr = frame_addr, };
581 btinfo = BTUINFO_INIT;
582 unsigned int async_filled = backtrace_user(frames + async_start_index,
583 frames_left, &ctl, &btinfo);
584 if (btinfo.btui_error == 0) {
585 btcount = MIN(async_start_index + async_filled, frames_len);
586 }
587 }
588
589 /* Process the backtrace. */
590 struct telemetry_target target = {
591 .thread = thread,
592 .frames = frames,
593 .frames_count = btcount,
594 .user64_regs = (btinfo.btui_info & BTI_64_BIT) != 0,
595 .microsnapshot_flags = flags,
596 .buffer = &telemetry_buffer,
597 .buffer_mtx = &telemetry_mtx,
598 .async_start_index = async_start_index,
599 };
600 telemetry_process_sample(&target, true, NULL);
601
602 telemetry_instrumentation_end(&telemetry_buffer);
603 }
604
605 #if CONFIG_MACF
606 void
telemetry_macf_take_sample(thread_t thread,enum micro_snapshot_flags flags)607 telemetry_macf_take_sample(thread_t thread, enum micro_snapshot_flags flags)
608 {
609 task_t task;
610
611 vm_size_t btcapacity = 128;
612 uintptr_t frames_stack[btcapacity];
613 uint32_t btcount = 0;
614 typedef uintptr_t telemetry_user_frame_t __kernel_data_semantics;
615 telemetry_user_frame_t *frames = frames_stack;
616 bool alloced_frames = false;
617
618 struct backtrace_user_info btinfo = BTUINFO_INIT;
619 struct backtrace_control btctl = BTCTL_INIT;
620
621 uint32_t retry_count = 0;
622 const uint32_t max_retries = 10;
623
624 bool initialized = false;
625 struct micro_snapshot_buffer *telbuf = &telemetry_macf_buffer;
626 uint32_t record_start = 0;
627 bool did_process = false;
628 int rv = 0;
629
630 if (thread == THREAD_NULL) {
631 return;
632 }
633
634 telemetry_instrumentation_begin(telbuf, flags);
635
636 /* Ensure task is ready for taking a sample. */
637 task = get_threadtask(thread);
638 if (!telemetry_task_ready_for_sample(task)) {
639 rv = EBUSY;
640 goto out;
641 }
642
643 /* Ensure MACF telemetry buffer was initialized. */
644 TELEMETRY_MACF_LOCK();
645 initialized = (telbuf->size > 0);
646 TELEMETRY_MACF_UNLOCK();
647
648 if (!initialized) {
649 rv = ENOMEM;
650 goto out;
651 }
652
653 /* Collect backtrace from user thread. */
654 while (retry_count < max_retries) {
655 btcount += backtrace_user(frames + btcount, btcapacity - btcount, &btctl, &btinfo);
656
657 if ((btinfo.btui_info & BTI_TRUNCATED) != 0 && btinfo.btui_next_frame_addr != 0) {
658 /*
659 * Fast path uses stack memory to avoid an allocation. We must
660 * pivot to heap memory in the case where we cannot write the
661 * complete backtrace to this buffer.
662 */
663 if (frames == frames_stack) {
664 btcapacity += 128;
665 frames = kalloc_data(btcapacity * sizeof(*frames), Z_WAITOK);
666
667 if (frames == NULL) {
668 break;
669 }
670
671 alloced_frames = true;
672
673 assert(btcapacity > sizeof(frames_stack) / sizeof(frames_stack[0]));
674 memcpy(frames, frames_stack, sizeof(frames_stack));
675 } else {
676 assert(alloced_frames);
677 frames = krealloc_data(frames,
678 btcapacity * sizeof(*frames),
679 (btcapacity + 128) * sizeof(*frames),
680 Z_WAITOK);
681
682 if (frames == NULL) {
683 break;
684 }
685
686 btcapacity += 128;
687 }
688
689 btctl.btc_frame_addr = btinfo.btui_next_frame_addr;
690 ++retry_count;
691 } else {
692 break;
693 }
694 }
695
696 if (frames == NULL) {
697 rv = ENOMEM;
698 goto out;
699 } else if (btinfo.btui_error != 0) {
700 rv = btinfo.btui_error;
701 goto out;
702 }
703
704 /* Process the backtrace. */
705 struct telemetry_target target = {
706 .thread = thread,
707 .frames = frames,
708 .frames_count = btcount,
709 .user64_regs = (btinfo.btui_info & BTI_64_BIT) != 0,
710 .microsnapshot_flags = flags,
711 .buffer = telbuf,
712 .buffer_mtx = &telemetry_macf_mtx
713 };
714 rv = telemetry_process_sample(&target, false, &record_start);
715 did_process = true;
716
717 out:
718 /* Immediately deliver the collected sample to MAC clients. */
719 if (rv == 0) {
720 assert(telbuf->current_position >= record_start);
721 mac_thread_telemetry(thread,
722 0,
723 (void *)(telbuf->buffer + record_start),
724 telbuf->current_position - record_start);
725 } else {
726 mac_thread_telemetry(thread, rv, NULL, 0);
727 }
728
729 /*
730 * The lock was taken by telemetry_process_sample, and we asked it not to
731 * unlock upon completion, so we must release the lock here.
732 */
733 if (did_process) {
734 TELEMETRY_MACF_UNLOCK();
735 }
736
737 if (alloced_frames && frames != NULL) {
738 kfree_data(frames, btcapacity * sizeof(*frames));
739 }
740
741 telemetry_instrumentation_end(telbuf);
742 }
743 #endif /* CONFIG_MACF */
744
745 int
telemetry_process_sample(const struct telemetry_target * target,bool release_buffer_lock,uint32_t * out_current_record_start)746 telemetry_process_sample(const struct telemetry_target *target,
747 bool release_buffer_lock,
748 uint32_t *out_current_record_start)
749 {
750 thread_t thread = target->thread;
751 uintptr_t *frames = target->frames;
752 size_t btcount = target->frames_count;
753 bool user64_regs = target->user64_regs;
754 enum micro_snapshot_flags microsnapshot_flags = target->microsnapshot_flags;
755 struct micro_snapshot_buffer *current_buffer = target->buffer;
756 lck_mtx_t *buffer_mtx = target->buffer_mtx;
757
758 task_t task;
759 void *p;
760 uint32_t bti;
761 struct micro_snapshot *msnap;
762 struct task_snapshot *tsnap;
763 struct thread_snapshot *thsnap;
764 clock_sec_t secs;
765 clock_usec_t usecs;
766 vm_size_t framesize;
767 uint32_t current_record_start;
768 uint32_t tmp = 0;
769 bool notify = false;
770 int rv = 0;
771
772 if (thread == THREAD_NULL) {
773 return EINVAL;
774 }
775
776 task = get_threadtask(thread);
777 p = get_bsdtask_info(task);
778 bool user64_va = task_has_64Bit_addr(task);
779
780 /*
781 * Retrieve the array of UUID's for binaries used by this task.
782 * We reach down into DYLD's data structures to find the array.
783 *
784 * XXX - make this common with kdp?
785 */
786 uint32_t uuid_info_count = 0;
787 mach_vm_address_t uuid_info_addr = 0;
788 uint32_t uuid_info_size = 0;
789 if (user64_va) {
790 uuid_info_size = sizeof(struct user64_dyld_uuid_info);
791 struct user64_dyld_all_image_infos task_image_infos;
792 if (copyin(task->all_image_info_addr, (char *)&task_image_infos, sizeof(task_image_infos)) == 0) {
793 uuid_info_count = (uint32_t)task_image_infos.uuidArrayCount;
794 uuid_info_addr = task_image_infos.uuidArray;
795 }
796 } else {
797 uuid_info_size = sizeof(struct user32_dyld_uuid_info);
798 struct user32_dyld_all_image_infos task_image_infos;
799 if (copyin(task->all_image_info_addr, (char *)&task_image_infos, sizeof(task_image_infos)) == 0) {
800 uuid_info_count = task_image_infos.uuidArrayCount;
801 uuid_info_addr = task_image_infos.uuidArray;
802 }
803 }
804
805 /*
806 * If we get a NULL uuid_info_addr (which can happen when we catch dyld in the middle of updating
807 * this data structure), we zero the uuid_info_count so that we won't even try to save load info
808 * for this task.
809 */
810 if (!uuid_info_addr) {
811 uuid_info_count = 0;
812 }
813
814 /*
815 * Don't copy in an unbounded amount of memory. The main binary and interesting
816 * non-shared-cache libraries should be in the first few images.
817 */
818 if (uuid_info_count > TELEMETRY_MAX_UUID_COUNT) {
819 uuid_info_count = TELEMETRY_MAX_UUID_COUNT;
820 }
821
822 uint32_t uuid_info_array_size = uuid_info_count * uuid_info_size;
823 char *uuid_info_array = NULL;
824
825 if (uuid_info_count > 0) {
826 uuid_info_array = kalloc_data(uuid_info_array_size, Z_WAITOK);
827 if (uuid_info_array == NULL) {
828 return ENOMEM;
829 }
830
831 /*
832 * Copy in the UUID info array.
833 * It may be nonresident, in which case just fix up nloadinfos to 0 in the task snapshot.
834 */
835 if (copyin(uuid_info_addr, uuid_info_array, uuid_info_array_size) != 0) {
836 kfree_data(uuid_info_array, uuid_info_array_size);
837 uuid_info_array = NULL;
838 uuid_info_array_size = 0;
839 }
840 }
841
842 /*
843 * Look for a dispatch queue serial number, and copy it in from userland if present.
844 */
845 uint64_t dqserialnum = 0;
846 int dqserialnum_valid = 0;
847
848 uint64_t dqkeyaddr = thread_dispatchqaddr(thread);
849 if (dqkeyaddr != 0) {
850 uint64_t dqaddr = 0;
851 uint64_t dq_serialno_offset = get_task_dispatchqueue_serialno_offset(task);
852 if ((copyin(dqkeyaddr, (char *)&dqaddr, (user64_va ? 8 : 4)) == 0) &&
853 (dqaddr != 0) && (dq_serialno_offset != 0)) {
854 uint64_t dqserialnumaddr = dqaddr + dq_serialno_offset;
855 if (copyin(dqserialnumaddr, (char *)&dqserialnum, (user64_va ? 8 : 4)) == 0) {
856 dqserialnum_valid = 1;
857 }
858 }
859 }
860
861 clock_get_calendar_microtime(&secs, &usecs);
862
863 lck_mtx_lock(buffer_mtx);
864
865 /*
866 * If our buffer is not backed by anything,
867 * then we cannot take the sample. Meant to allow us to deallocate the window
868 * buffer if it is disabled.
869 */
870 if (!current_buffer->buffer) {
871 rv = EINVAL;
872 goto cancel_sample;
873 }
874
875 /*
876 * We do the bulk of the operation under the telemetry lock, on assumption that
877 * any page faults during execution will not cause another AST_TELEMETRY_ALL
878 * to deadlock; they will just block until we finish. This makes it easier
879 * to copy into the buffer directly. As soon as we unlock, userspace can copy
880 * out of our buffer.
881 */
882
883 copytobuffer:
884
885 current_record_start = current_buffer->current_position;
886
887 if ((current_buffer->size - current_buffer->current_position) < sizeof(struct micro_snapshot)) {
888 /*
889 * We can't fit a record in the space available, so wrap around to the beginning.
890 * Save the current position as the known end point of valid data.
891 */
892 current_buffer->end_point = current_record_start;
893 current_buffer->current_position = 0;
894 if (current_record_start == 0) {
895 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
896 rv = ERANGE;
897 goto cancel_sample;
898 }
899 goto copytobuffer;
900 }
901
902 msnap = (struct micro_snapshot *)(uintptr_t)(current_buffer->buffer + current_buffer->current_position);
903 msnap->snapshot_magic = STACKSHOT_MICRO_SNAPSHOT_MAGIC;
904 msnap->ms_flags = (uint8_t)microsnapshot_flags;
905 msnap->ms_opaque_flags = 0; /* namespace managed by userspace */
906 msnap->ms_cpu = cpu_number();
907 msnap->ms_time = secs;
908 msnap->ms_time_microsecs = usecs;
909
910 current_buffer->current_position += sizeof(struct micro_snapshot);
911
912 if ((current_buffer->size - current_buffer->current_position) < sizeof(struct task_snapshot)) {
913 current_buffer->end_point = current_record_start;
914 current_buffer->current_position = 0;
915 if (current_record_start == 0) {
916 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
917 rv = ERANGE;
918 goto cancel_sample;
919 }
920 goto copytobuffer;
921 }
922
923 tsnap = (struct task_snapshot *)(uintptr_t)(current_buffer->buffer + current_buffer->current_position);
924 bzero(tsnap, sizeof(*tsnap));
925 tsnap->snapshot_magic = STACKSHOT_TASK_SNAPSHOT_MAGIC;
926 tsnap->pid = proc_pid(p);
927 tsnap->uniqueid = proc_uniqueid(p);
928 struct recount_times_mach times = recount_task_terminated_times(task);
929 tsnap->user_time_in_terminated_threads = times.rtm_user;
930 tsnap->system_time_in_terminated_threads = times.rtm_system;
931 tsnap->suspend_count = task->suspend_count;
932 tsnap->task_size = (typeof(tsnap->task_size))(get_task_phys_footprint(task) / PAGE_SIZE);
933 tsnap->faults = counter_load(&task->faults);
934 tsnap->pageins = counter_load(&task->pageins);
935 tsnap->cow_faults = counter_load(&task->cow_faults);
936 /*
937 * The throttling counters are maintained as 64-bit counters in the proc
938 * structure. However, we reserve 32-bits (each) for them in the task_snapshot
939 * struct to save space and since we do not expect them to overflow 32-bits. If we
940 * find these values overflowing in the future, the fix would be to simply
941 * upgrade these counters to 64-bit in the task_snapshot struct
942 */
943 tsnap->was_throttled = (uint32_t) proc_was_throttled(p);
944 tsnap->did_throttle = (uint32_t) proc_did_throttle(p);
945 #if CONFIG_COALITIONS
946 /*
947 * These fields are overloaded to represent the resource coalition ID of
948 * this task...
949 */
950 coalition_t rsrc_coal = task->coalition[COALITION_TYPE_RESOURCE];
951 tsnap->p_start_sec = rsrc_coal ? coalition_id(rsrc_coal) : 0;
952 /*
953 * ... and the process this thread is doing work on behalf of.
954 */
955 pid_t origin_pid = -1;
956 if (thread_get_voucher_origin_pid(thread, &origin_pid) != KERN_SUCCESS) {
957 origin_pid = -1;
958 }
959 tsnap->p_start_usec = origin_pid;
960 #endif /* CONFIG_COALITIONS */
961
962 if (task->t_flags & TF_TELEMETRY) {
963 tsnap->ss_flags |= kTaskRsrcFlagged;
964 }
965
966 if (proc_get_effective_task_policy(task, TASK_POLICY_DARWIN_BG)) {
967 tsnap->ss_flags |= kTaskDarwinBG;
968 }
969
970 proc_get_darwinbgstate(task, &tmp);
971
972 if (proc_get_effective_task_policy(task, TASK_POLICY_ROLE) == TASK_FOREGROUND_APPLICATION) {
973 tsnap->ss_flags |= kTaskIsForeground;
974 }
975
976 if (tmp & PROC_FLAG_ADAPTIVE_IMPORTANT) {
977 tsnap->ss_flags |= kTaskIsBoosted;
978 }
979
980 if (tmp & PROC_FLAG_SUPPRESSED) {
981 tsnap->ss_flags |= kTaskIsSuppressed;
982 }
983
984
985 tsnap->latency_qos = task_grab_latency_qos(task);
986
987 strlcpy(tsnap->p_comm, proc_name_address(p), sizeof(tsnap->p_comm));
988 if (user64_va) {
989 tsnap->ss_flags |= kUser64_p;
990 }
991
992 if (task->task_shared_region_slide != -1) {
993 tsnap->shared_cache_slide = task->task_shared_region_slide;
994 bcopy(task->task_shared_region_uuid, tsnap->shared_cache_identifier,
995 sizeof(task->task_shared_region_uuid));
996 }
997
998 current_buffer->current_position += sizeof(struct task_snapshot);
999
1000 /*
1001 * Directly after the task snapshot, place the array of UUID's corresponding to the binaries
1002 * used by this task.
1003 */
1004 if ((current_buffer->size - current_buffer->current_position) < uuid_info_array_size) {
1005 current_buffer->end_point = current_record_start;
1006 current_buffer->current_position = 0;
1007 if (current_record_start == 0) {
1008 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
1009 rv = ERANGE;
1010 goto cancel_sample;
1011 }
1012 goto copytobuffer;
1013 }
1014
1015 /*
1016 * Copy the UUID info array into our sample.
1017 */
1018 if (uuid_info_array_size > 0) {
1019 bcopy(uuid_info_array, (char *)(current_buffer->buffer + current_buffer->current_position), uuid_info_array_size);
1020 tsnap->nloadinfos = uuid_info_count;
1021 }
1022
1023 current_buffer->current_position += uuid_info_array_size;
1024
1025 /*
1026 * After the task snapshot & list of binary UUIDs, we place a thread snapshot.
1027 */
1028
1029 if ((current_buffer->size - current_buffer->current_position) < sizeof(struct thread_snapshot)) {
1030 /* wrap and overwrite */
1031 current_buffer->end_point = current_record_start;
1032 current_buffer->current_position = 0;
1033 if (current_record_start == 0) {
1034 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
1035 rv = ERANGE;
1036 goto cancel_sample;
1037 }
1038 goto copytobuffer;
1039 }
1040
1041 thsnap = (struct thread_snapshot *)(uintptr_t)(current_buffer->buffer + current_buffer->current_position);
1042 bzero(thsnap, sizeof(*thsnap));
1043
1044 thsnap->snapshot_magic = STACKSHOT_THREAD_SNAPSHOT_MAGIC;
1045 thsnap->thread_id = thread_tid(thread);
1046 thsnap->state = thread->state;
1047 thsnap->priority = thread->base_pri;
1048 thsnap->sched_pri = thread->sched_pri;
1049 thsnap->sched_flags = thread->sched_flags;
1050 thsnap->ss_flags |= kStacksPCOnly;
1051 thsnap->ts_qos = thread->effective_policy.thep_qos;
1052 thsnap->ts_rqos = thread->requested_policy.thrp_qos;
1053 thsnap->ts_rqos_override = MAX(thread->requested_policy.thrp_qos_override,
1054 thread->requested_policy.thrp_qos_workq_override);
1055 memcpy(thsnap->_reserved + 1, &target->async_start_index,
1056 sizeof(target->async_start_index));
1057
1058 if (proc_get_effective_thread_policy(thread, TASK_POLICY_DARWIN_BG)) {
1059 thsnap->ss_flags |= kThreadDarwinBG;
1060 }
1061
1062 boolean_t interrupt_state = ml_set_interrupts_enabled(FALSE);
1063 times = recount_current_thread_times();
1064 ml_set_interrupts_enabled(interrupt_state);
1065 thsnap->user_time = times.rtm_user;
1066 thsnap->system_time = times.rtm_system;
1067
1068 current_buffer->current_position += sizeof(struct thread_snapshot);
1069
1070 /*
1071 * If this thread has a dispatch queue serial number, include it here.
1072 */
1073 if (dqserialnum_valid) {
1074 if ((current_buffer->size - current_buffer->current_position) < sizeof(dqserialnum)) {
1075 /* wrap and overwrite */
1076 current_buffer->end_point = current_record_start;
1077 current_buffer->current_position = 0;
1078 if (current_record_start == 0) {
1079 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
1080 rv = ERANGE;
1081 goto cancel_sample;
1082 }
1083 goto copytobuffer;
1084 }
1085
1086 thsnap->ss_flags |= kHasDispatchSerial;
1087 bcopy(&dqserialnum, (char *)current_buffer->buffer + current_buffer->current_position, sizeof(dqserialnum));
1088 current_buffer->current_position += sizeof(dqserialnum);
1089 }
1090
1091 if (user64_regs) {
1092 framesize = 8;
1093 thsnap->ss_flags |= kUser64_p;
1094 } else {
1095 framesize = 4;
1096 }
1097
1098 /*
1099 * If we can't fit this entire stacktrace then cancel this record, wrap to the beginning,
1100 * and start again there so that we always store a full record.
1101 */
1102 if ((current_buffer->size - current_buffer->current_position) / framesize < btcount) {
1103 current_buffer->end_point = current_record_start;
1104 current_buffer->current_position = 0;
1105 if (current_record_start == 0) {
1106 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
1107 rv = ERANGE;
1108 goto cancel_sample;
1109 }
1110 goto copytobuffer;
1111 }
1112
1113 for (bti = 0; bti < btcount; bti++, current_buffer->current_position += framesize) {
1114 if (framesize == 8) {
1115 *(uint64_t *)(uintptr_t)(current_buffer->buffer + current_buffer->current_position) = frames[bti];
1116 } else {
1117 *(uint32_t *)(uintptr_t)(current_buffer->buffer + current_buffer->current_position) = (uint32_t)frames[bti];
1118 }
1119 }
1120
1121 if (current_buffer->end_point < current_buffer->current_position) {
1122 /*
1123 * Each time the cursor wraps around to the beginning, we leave a
1124 * differing amount of unused space at the end of the buffer. Make
1125 * sure the cursor pushes the end point in case we're making use of
1126 * more of the buffer than we did the last time we wrapped.
1127 */
1128 current_buffer->end_point = current_buffer->current_position;
1129 }
1130
1131 thsnap->nuser_frames = btcount;
1132
1133 /*
1134 * Now THIS is a hack.
1135 */
1136 if (current_buffer == &telemetry_buffer) {
1137 telemetry_bytes_since_last_mark += (current_buffer->current_position - current_record_start);
1138 if (telemetry_bytes_since_last_mark > telemetry_buffer_notify_at) {
1139 notify = true;
1140 }
1141 }
1142
1143 if (out_current_record_start != NULL) {
1144 *out_current_record_start = current_record_start;
1145 }
1146
1147 cancel_sample:
1148 if (release_buffer_lock) {
1149 lck_mtx_unlock(buffer_mtx);
1150 }
1151
1152 if (notify) {
1153 telemetry_notify_user();
1154 }
1155
1156 if (uuid_info_array != NULL) {
1157 kfree_data(uuid_info_array, uuid_info_array_size);
1158 }
1159
1160 return rv;
1161 }
1162
1163 #if TELEMETRY_DEBUG
1164 static void
log_telemetry_output(vm_offset_t buf,uint32_t pos,uint32_t sz)1165 log_telemetry_output(vm_offset_t buf, uint32_t pos, uint32_t sz)
1166 {
1167 struct micro_snapshot *p;
1168 uint32_t offset;
1169
1170 printf("Copying out %d bytes of telemetry at offset %d\n", sz, pos);
1171
1172 buf += pos;
1173
1174 /*
1175 * Find and log each timestamp in this chunk of buffer.
1176 */
1177 for (offset = 0; offset < sz; offset++) {
1178 p = (struct micro_snapshot *)(buf + offset);
1179 if (p->snapshot_magic == STACKSHOT_MICRO_SNAPSHOT_MAGIC) {
1180 printf("telemetry timestamp: %lld\n", p->ms_time);
1181 }
1182 }
1183 }
1184 #endif
1185
1186 int
telemetry_gather(user_addr_t buffer,uint32_t * length,bool mark)1187 telemetry_gather(user_addr_t buffer, uint32_t *length, bool mark)
1188 {
1189 return telemetry_buffer_gather(buffer, length, mark, &telemetry_buffer);
1190 }
1191
1192 int
telemetry_buffer_gather(user_addr_t buffer,uint32_t * length,bool mark,struct micro_snapshot_buffer * current_buffer)1193 telemetry_buffer_gather(user_addr_t buffer, uint32_t *length, bool mark, struct micro_snapshot_buffer * current_buffer)
1194 {
1195 int result = 0;
1196 uint32_t oldest_record_offset;
1197
1198 KDBG(MACHDBG_CODE(DBG_MACH_STACKSHOT, MICROSTACKSHOT_GATHER) | DBG_FUNC_START,
1199 mark, telemetry_bytes_since_last_mark, 0,
1200 (&telemetry_buffer != current_buffer));
1201
1202 TELEMETRY_LOCK();
1203
1204 if (current_buffer->buffer == 0) {
1205 *length = 0;
1206 goto out;
1207 }
1208
1209 if (*length < current_buffer->size) {
1210 result = KERN_NO_SPACE;
1211 goto out;
1212 }
1213
1214 /*
1215 * Copy the ring buffer out to userland in order sorted by time: least recent to most recent.
1216 * First, we need to search forward from the cursor to find the oldest record in our buffer.
1217 */
1218 oldest_record_offset = current_buffer->current_position;
1219 do {
1220 if (((oldest_record_offset + sizeof(uint32_t)) > current_buffer->size) ||
1221 ((oldest_record_offset + sizeof(uint32_t)) > current_buffer->end_point)) {
1222 if (*(uint32_t *)(uintptr_t)(current_buffer->buffer) == 0) {
1223 /*
1224 * There is no magic number at the start of the buffer, which means
1225 * it's empty; nothing to see here yet.
1226 */
1227 *length = 0;
1228 goto out;
1229 }
1230 /*
1231 * We've looked through the end of the active buffer without finding a valid
1232 * record; that means all valid records are in a single chunk, beginning at
1233 * the very start of the buffer.
1234 */
1235
1236 oldest_record_offset = 0;
1237 assert(*(uint32_t *)(uintptr_t)(current_buffer->buffer) == STACKSHOT_MICRO_SNAPSHOT_MAGIC);
1238 break;
1239 }
1240
1241 if (*(uint32_t *)(uintptr_t)(current_buffer->buffer + oldest_record_offset) == STACKSHOT_MICRO_SNAPSHOT_MAGIC) {
1242 break;
1243 }
1244
1245 /*
1246 * There are no alignment guarantees for micro-stackshot records, so we must search at each
1247 * byte offset.
1248 */
1249 oldest_record_offset++;
1250 } while (oldest_record_offset != current_buffer->current_position);
1251
1252 /*
1253 * If needed, copyout in two chunks: from the oldest record to the end of the buffer, and then
1254 * from the beginning of the buffer up to the current position.
1255 */
1256 if (oldest_record_offset != 0) {
1257 #if TELEMETRY_DEBUG
1258 log_telemetry_output(current_buffer->buffer, oldest_record_offset,
1259 current_buffer->end_point - oldest_record_offset);
1260 #endif
1261 if ((result = copyout((void *)(current_buffer->buffer + oldest_record_offset), buffer,
1262 current_buffer->end_point - oldest_record_offset)) != 0) {
1263 *length = 0;
1264 goto out;
1265 }
1266 *length = current_buffer->end_point - oldest_record_offset;
1267 } else {
1268 *length = 0;
1269 }
1270
1271 #if TELEMETRY_DEBUG
1272 log_telemetry_output(current_buffer->buffer, 0, current_buffer->current_position);
1273 #endif
1274 if ((result = copyout((void *)current_buffer->buffer, buffer + *length,
1275 current_buffer->current_position)) != 0) {
1276 *length = 0;
1277 goto out;
1278 }
1279 *length += (uint32_t)current_buffer->current_position;
1280
1281 out:
1282
1283 if (mark && (*length > 0)) {
1284 telemetry_bytes_since_last_mark = 0;
1285 }
1286
1287 TELEMETRY_UNLOCK();
1288
1289 KDBG(MACHDBG_CODE(DBG_MACH_STACKSHOT, MICROSTACKSHOT_GATHER) | DBG_FUNC_END,
1290 current_buffer->current_position, *length,
1291 current_buffer->end_point, (&telemetry_buffer != current_buffer));
1292
1293 return result;
1294 }
1295
1296 #if CONFIG_MACF
1297 static int
telemetry_macf_init_locked(size_t buffer_size)1298 telemetry_macf_init_locked(size_t buffer_size)
1299 {
1300 kern_return_t kr;
1301
1302 if (buffer_size > TELEMETRY_MAX_BUFFER_SIZE) {
1303 buffer_size = TELEMETRY_MAX_BUFFER_SIZE;
1304 }
1305
1306 telemetry_macf_buffer.size = buffer_size;
1307
1308 kr = kmem_alloc(kernel_map, &telemetry_macf_buffer.buffer,
1309 telemetry_macf_buffer.size, KMA_DATA | KMA_ZERO | KMA_PERMANENT,
1310 VM_KERN_MEMORY_SECURITY);
1311
1312 if (kr != KERN_SUCCESS) {
1313 kprintf("Telemetry (MACF): Allocation failed: %d\n", kr);
1314 return ENOMEM;
1315 }
1316
1317 return 0;
1318 }
1319
1320 int
telemetry_macf_mark_curthread(void)1321 telemetry_macf_mark_curthread(void)
1322 {
1323 thread_t thread = current_thread();
1324 task_t task = get_threadtask(thread);
1325 int rv = 0;
1326
1327 if (task == kernel_task) {
1328 /* Kernel threads never return to an AST boundary, and are ineligible */
1329 return EINVAL;
1330 }
1331
1332 /* Initialize the MACF telemetry buffer if needed. */
1333 TELEMETRY_MACF_LOCK();
1334 if (__improbable(telemetry_macf_buffer.size == 0)) {
1335 rv = telemetry_macf_init_locked(TELEMETRY_MACF_DEFAULT_BUFFER_SIZE);
1336
1337 if (rv != 0) {
1338 return rv;
1339 }
1340 }
1341 TELEMETRY_MACF_UNLOCK();
1342
1343 act_set_macf_telemetry_ast(thread);
1344 return 0;
1345 }
1346 #endif /* CONFIG_MACF */
1347
1348 /************************/
1349 /* BOOT PROFILE SUPPORT */
1350 /************************/
1351 /*
1352 * Boot Profiling
1353 *
1354 * The boot-profiling support is a mechanism to sample activity happening on the
1355 * system during boot. This mechanism sets up a periodic timer and on every timer fire,
1356 * captures a full backtrace into the boot profiling buffer. This buffer can be pulled
1357 * out and analyzed from user-space. It is turned on using the following boot-args:
1358 * "bootprofile_buffer_size" specifies the size of the boot profile buffer
1359 * "bootprofile_interval_ms" specifies the interval for the profiling timer
1360 *
1361 * Process Specific Boot Profiling
1362 *
1363 * The boot-arg "bootprofile_proc_name" can be used to specify a certain
1364 * process that needs to profiled during boot. Setting this boot-arg changes
1365 * the way stackshots are captured. At every timer fire, the code looks at the
1366 * currently running process and takes a stackshot only if the requested process
1367 * is on-core (which makes it unsuitable for MP systems).
1368 *
1369 * Trigger Events
1370 *
1371 * The boot-arg "bootprofile_type=boot" starts the timer during early boot. Using
1372 * "wake" starts the timer at AP wake from suspend-to-RAM.
1373 */
1374
1375 #define BOOTPROFILE_MAX_BUFFER_SIZE (64*1024*1024) /* see also COPYSIZELIMIT_PANIC */
1376
1377 vm_offset_t bootprofile_buffer = 0;
1378 uint32_t bootprofile_buffer_size = 0;
1379 uint32_t bootprofile_buffer_current_position = 0;
1380 uint32_t bootprofile_interval_ms = 0;
1381 uint64_t bootprofile_stackshot_flags = 0;
1382 uint64_t bootprofile_interval_abs = 0;
1383 uint64_t bootprofile_next_deadline = 0;
1384 uint32_t bootprofile_all_procs = 0;
1385 char bootprofile_proc_name[17];
1386 uint64_t bootprofile_delta_since_timestamp = 0;
1387 LCK_GRP_DECLARE(bootprofile_lck_grp, "bootprofile_group");
1388 LCK_MTX_DECLARE(bootprofile_mtx, &bootprofile_lck_grp);
1389
1390
1391 enum {
1392 kBootProfileDisabled = 0,
1393 kBootProfileStartTimerAtBoot,
1394 kBootProfileStartTimerAtWake
1395 } bootprofile_type = kBootProfileDisabled;
1396
1397
1398 static timer_call_data_t bootprofile_timer_call_entry;
1399
1400 #define BOOTPROFILE_LOCK() do { lck_mtx_lock(&bootprofile_mtx); } while(0)
1401 #define BOOTPROFILE_TRY_SPIN_LOCK() lck_mtx_try_lock_spin(&bootprofile_mtx)
1402 #define BOOTPROFILE_UNLOCK() do { lck_mtx_unlock(&bootprofile_mtx); } while(0)
1403
1404 static void bootprofile_timer_call(
1405 timer_call_param_t param0,
1406 timer_call_param_t param1);
1407
1408 void
bootprofile_init(void)1409 bootprofile_init(void)
1410 {
1411 kern_return_t ret;
1412 char type[32];
1413
1414 if (!PE_parse_boot_argn("bootprofile_buffer_size",
1415 &bootprofile_buffer_size, sizeof(bootprofile_buffer_size))) {
1416 bootprofile_buffer_size = 0;
1417 }
1418
1419 if (bootprofile_buffer_size > BOOTPROFILE_MAX_BUFFER_SIZE) {
1420 bootprofile_buffer_size = BOOTPROFILE_MAX_BUFFER_SIZE;
1421 }
1422
1423 if (!PE_parse_boot_argn("bootprofile_interval_ms",
1424 &bootprofile_interval_ms, sizeof(bootprofile_interval_ms))) {
1425 bootprofile_interval_ms = 0;
1426 }
1427
1428 if (!PE_parse_boot_argn("bootprofile_stackshot_flags",
1429 &bootprofile_stackshot_flags, sizeof(bootprofile_stackshot_flags))) {
1430 bootprofile_stackshot_flags = 0;
1431 }
1432
1433 if (!PE_parse_boot_argn("bootprofile_proc_name",
1434 &bootprofile_proc_name, sizeof(bootprofile_proc_name))) {
1435 bootprofile_all_procs = 1;
1436 bootprofile_proc_name[0] = '\0';
1437 }
1438
1439 if (PE_parse_boot_argn("bootprofile_type", type, sizeof(type))) {
1440 if (0 == strcmp(type, "boot")) {
1441 bootprofile_type = kBootProfileStartTimerAtBoot;
1442 } else if (0 == strcmp(type, "wake")) {
1443 bootprofile_type = kBootProfileStartTimerAtWake;
1444 } else {
1445 bootprofile_type = kBootProfileDisabled;
1446 }
1447 } else {
1448 bootprofile_type = kBootProfileDisabled;
1449 }
1450
1451 clock_interval_to_absolutetime_interval(bootprofile_interval_ms, NSEC_PER_MSEC, &bootprofile_interval_abs);
1452
1453 /* Both boot args must be set to enable */
1454 if ((bootprofile_type == kBootProfileDisabled) || (bootprofile_buffer_size == 0) || (bootprofile_interval_abs == 0)) {
1455 return;
1456 }
1457
1458 ret = kmem_alloc(kernel_map, &bootprofile_buffer, bootprofile_buffer_size,
1459 KMA_DATA | KMA_ZERO | KMA_PERMANENT, VM_KERN_MEMORY_DIAG);
1460 if (ret != KERN_SUCCESS) {
1461 kprintf("Boot profile: Allocation failed: %d\n", ret);
1462 return;
1463 }
1464
1465 kprintf("Boot profile: Sampling %s once per %u ms at %s\n",
1466 bootprofile_all_procs ? "all procs" : bootprofile_proc_name, bootprofile_interval_ms,
1467 bootprofile_type == kBootProfileStartTimerAtBoot ? "boot" : (bootprofile_type == kBootProfileStartTimerAtWake ? "wake" : "unknown"));
1468
1469 timer_call_setup(&bootprofile_timer_call_entry,
1470 bootprofile_timer_call,
1471 NULL);
1472
1473 if (bootprofile_type == kBootProfileStartTimerAtBoot) {
1474 bootprofile_next_deadline = mach_absolute_time() + bootprofile_interval_abs;
1475 timer_call_enter_with_leeway(&bootprofile_timer_call_entry,
1476 NULL,
1477 bootprofile_next_deadline,
1478 0,
1479 TIMER_CALL_SYS_NORMAL,
1480 false);
1481 }
1482 }
1483
1484 void
bootprofile_wake_from_sleep(void)1485 bootprofile_wake_from_sleep(void)
1486 {
1487 if (bootprofile_type == kBootProfileStartTimerAtWake) {
1488 bootprofile_next_deadline = mach_absolute_time() + bootprofile_interval_abs;
1489 timer_call_enter_with_leeway(&bootprofile_timer_call_entry,
1490 NULL,
1491 bootprofile_next_deadline,
1492 0,
1493 TIMER_CALL_SYS_NORMAL,
1494 false);
1495 }
1496 }
1497
1498
1499 static void
bootprofile_timer_call(timer_call_param_t param0 __unused,timer_call_param_t param1 __unused)1500 bootprofile_timer_call(
1501 timer_call_param_t param0 __unused,
1502 timer_call_param_t param1 __unused)
1503 {
1504 unsigned retbytes = 0;
1505 int pid_to_profile = -1;
1506
1507 if (!BOOTPROFILE_TRY_SPIN_LOCK()) {
1508 goto reprogram;
1509 }
1510
1511 /* Check if process-specific boot profiling is turned on */
1512 if (!bootprofile_all_procs) {
1513 /*
1514 * Since boot profiling initializes really early in boot, it is
1515 * possible that at this point, the task/proc is not initialized.
1516 * Nothing to do in that case.
1517 */
1518
1519 if ((current_task() != NULL) && (get_bsdtask_info(current_task()) != NULL) &&
1520 (0 == strncmp(bootprofile_proc_name, proc_name_address(get_bsdtask_info(current_task())), 17))) {
1521 pid_to_profile = proc_selfpid();
1522 } else {
1523 /*
1524 * Process-specific boot profiling requested but the on-core process is
1525 * something else. Nothing to do here.
1526 */
1527 BOOTPROFILE_UNLOCK();
1528 goto reprogram;
1529 }
1530 }
1531
1532 /* initiate a stackshot with whatever portion of the buffer is left */
1533 if (bootprofile_buffer_current_position < bootprofile_buffer_size) {
1534 uint64_t flags = STACKSHOT_KCDATA_FORMAT | STACKSHOT_TRYLOCK | STACKSHOT_SAVE_LOADINFO
1535 | STACKSHOT_GET_GLOBAL_MEM_STATS;
1536 #if defined(XNU_TARGET_OS_OSX)
1537 flags |= STACKSHOT_SAVE_KEXT_LOADINFO;
1538 #endif
1539
1540
1541 /* OR on flags specified in boot-args */
1542 flags |= bootprofile_stackshot_flags;
1543 if ((flags & STACKSHOT_COLLECT_DELTA_SNAPSHOT) && (bootprofile_delta_since_timestamp == 0)) {
1544 /* Can't take deltas until the first one */
1545 flags &= ~STACKSHOT_COLLECT_DELTA_SNAPSHOT;
1546 }
1547
1548 uint64_t timestamp = 0;
1549 if (bootprofile_stackshot_flags & STACKSHOT_COLLECT_DELTA_SNAPSHOT) {
1550 timestamp = mach_absolute_time();
1551 }
1552
1553 kern_return_t r = stack_snapshot_from_kernel(
1554 pid_to_profile, (void *)(bootprofile_buffer + bootprofile_buffer_current_position),
1555 bootprofile_buffer_size - bootprofile_buffer_current_position,
1556 flags, bootprofile_delta_since_timestamp, 0, &retbytes);
1557
1558 /*
1559 * We call with STACKSHOT_TRYLOCK because the stackshot lock is coarser
1560 * than the bootprofile lock. If someone else has the lock we'll just
1561 * try again later.
1562 */
1563
1564 if (r == KERN_LOCK_OWNED) {
1565 BOOTPROFILE_UNLOCK();
1566 goto reprogram;
1567 }
1568
1569 if (bootprofile_stackshot_flags & STACKSHOT_COLLECT_DELTA_SNAPSHOT &&
1570 r == KERN_SUCCESS) {
1571 bootprofile_delta_since_timestamp = timestamp;
1572 }
1573
1574 bootprofile_buffer_current_position += retbytes;
1575 }
1576
1577 BOOTPROFILE_UNLOCK();
1578
1579 /* If we didn't get any data or have run out of buffer space, stop profiling */
1580 if ((retbytes == 0) || (bootprofile_buffer_current_position == bootprofile_buffer_size)) {
1581 return;
1582 }
1583
1584
1585 reprogram:
1586 /* If the user gathered the buffer, no need to keep profiling */
1587 if (bootprofile_interval_abs == 0) {
1588 return;
1589 }
1590
1591 clock_deadline_for_periodic_event(bootprofile_interval_abs,
1592 mach_absolute_time(),
1593 &bootprofile_next_deadline);
1594 timer_call_enter_with_leeway(&bootprofile_timer_call_entry,
1595 NULL,
1596 bootprofile_next_deadline,
1597 0,
1598 TIMER_CALL_SYS_NORMAL,
1599 false);
1600 }
1601
1602 void
bootprofile_get(void ** buffer,uint32_t * length)1603 bootprofile_get(void **buffer, uint32_t *length)
1604 {
1605 BOOTPROFILE_LOCK();
1606 *buffer = (void*) bootprofile_buffer;
1607 *length = bootprofile_buffer_current_position;
1608 BOOTPROFILE_UNLOCK();
1609 }
1610
1611 int
bootprofile_gather(user_addr_t buffer,uint32_t * length)1612 bootprofile_gather(user_addr_t buffer, uint32_t *length)
1613 {
1614 int result = 0;
1615
1616 BOOTPROFILE_LOCK();
1617
1618 if (bootprofile_buffer == 0) {
1619 *length = 0;
1620 goto out;
1621 }
1622
1623 if (*length < bootprofile_buffer_current_position) {
1624 result = KERN_NO_SPACE;
1625 goto out;
1626 }
1627
1628 if ((result = copyout((void *)bootprofile_buffer, buffer,
1629 bootprofile_buffer_current_position)) != 0) {
1630 *length = 0;
1631 goto out;
1632 }
1633 *length = bootprofile_buffer_current_position;
1634
1635 /* cancel future timers */
1636 bootprofile_interval_abs = 0;
1637
1638 out:
1639
1640 BOOTPROFILE_UNLOCK();
1641
1642 return result;
1643 }
1644