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 /*
946 * The field is overloaded to represent the resource coalition ID of this
947 * task.
948 */
949 coalition_t rsrc_coal = task->coalition[COALITION_TYPE_RESOURCE];
950 tsnap->p_start_sec = rsrc_coal ? coalition_id(rsrc_coal) : 0;
951
952 if (task->t_flags & TF_TELEMETRY) {
953 tsnap->ss_flags |= kTaskRsrcFlagged;
954 }
955
956 if (proc_get_effective_task_policy(task, TASK_POLICY_DARWIN_BG)) {
957 tsnap->ss_flags |= kTaskDarwinBG;
958 }
959
960 proc_get_darwinbgstate(task, &tmp);
961
962 if (proc_get_effective_task_policy(task, TASK_POLICY_ROLE) == TASK_FOREGROUND_APPLICATION) {
963 tsnap->ss_flags |= kTaskIsForeground;
964 }
965
966 if (tmp & PROC_FLAG_ADAPTIVE_IMPORTANT) {
967 tsnap->ss_flags |= kTaskIsBoosted;
968 }
969
970 if (tmp & PROC_FLAG_SUPPRESSED) {
971 tsnap->ss_flags |= kTaskIsSuppressed;
972 }
973
974
975 tsnap->latency_qos = task_grab_latency_qos(task);
976
977 strlcpy(tsnap->p_comm, proc_name_address(p), sizeof(tsnap->p_comm));
978 if (user64_va) {
979 tsnap->ss_flags |= kUser64_p;
980 }
981
982 if (task->task_shared_region_slide != -1) {
983 tsnap->shared_cache_slide = task->task_shared_region_slide;
984 bcopy(task->task_shared_region_uuid, tsnap->shared_cache_identifier,
985 sizeof(task->task_shared_region_uuid));
986 }
987
988 current_buffer->current_position += sizeof(struct task_snapshot);
989
990 /*
991 * Directly after the task snapshot, place the array of UUID's corresponding to the binaries
992 * used by this task.
993 */
994 if ((current_buffer->size - current_buffer->current_position) < uuid_info_array_size) {
995 current_buffer->end_point = current_record_start;
996 current_buffer->current_position = 0;
997 if (current_record_start == 0) {
998 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
999 rv = ERANGE;
1000 goto cancel_sample;
1001 }
1002 goto copytobuffer;
1003 }
1004
1005 /*
1006 * Copy the UUID info array into our sample.
1007 */
1008 if (uuid_info_array_size > 0) {
1009 bcopy(uuid_info_array, (char *)(current_buffer->buffer + current_buffer->current_position), uuid_info_array_size);
1010 tsnap->nloadinfos = uuid_info_count;
1011 }
1012
1013 current_buffer->current_position += uuid_info_array_size;
1014
1015 /*
1016 * After the task snapshot & list of binary UUIDs, we place a thread snapshot.
1017 */
1018
1019 if ((current_buffer->size - current_buffer->current_position) < sizeof(struct thread_snapshot)) {
1020 /* wrap and overwrite */
1021 current_buffer->end_point = current_record_start;
1022 current_buffer->current_position = 0;
1023 if (current_record_start == 0) {
1024 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
1025 rv = ERANGE;
1026 goto cancel_sample;
1027 }
1028 goto copytobuffer;
1029 }
1030
1031 thsnap = (struct thread_snapshot *)(uintptr_t)(current_buffer->buffer + current_buffer->current_position);
1032 bzero(thsnap, sizeof(*thsnap));
1033
1034 thsnap->snapshot_magic = STACKSHOT_THREAD_SNAPSHOT_MAGIC;
1035 thsnap->thread_id = thread_tid(thread);
1036 thsnap->state = thread->state;
1037 thsnap->priority = thread->base_pri;
1038 thsnap->sched_pri = thread->sched_pri;
1039 thsnap->sched_flags = thread->sched_flags;
1040 thsnap->ss_flags |= kStacksPCOnly;
1041 thsnap->ts_qos = thread->effective_policy.thep_qos;
1042 thsnap->ts_rqos = thread->requested_policy.thrp_qos;
1043 thsnap->ts_rqos_override = MAX(thread->requested_policy.thrp_qos_override,
1044 thread->requested_policy.thrp_qos_workq_override);
1045 memcpy(thsnap->_reserved + 1, &target->async_start_index,
1046 sizeof(target->async_start_index));
1047
1048 if (proc_get_effective_thread_policy(thread, TASK_POLICY_DARWIN_BG)) {
1049 thsnap->ss_flags |= kThreadDarwinBG;
1050 }
1051
1052 boolean_t interrupt_state = ml_set_interrupts_enabled(FALSE);
1053 times = recount_current_thread_times();
1054 ml_set_interrupts_enabled(interrupt_state);
1055 thsnap->user_time = times.rtm_user;
1056 thsnap->system_time = times.rtm_system;
1057
1058 current_buffer->current_position += sizeof(struct thread_snapshot);
1059
1060 /*
1061 * If this thread has a dispatch queue serial number, include it here.
1062 */
1063 if (dqserialnum_valid) {
1064 if ((current_buffer->size - current_buffer->current_position) < sizeof(dqserialnum)) {
1065 /* wrap and overwrite */
1066 current_buffer->end_point = current_record_start;
1067 current_buffer->current_position = 0;
1068 if (current_record_start == 0) {
1069 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
1070 rv = ERANGE;
1071 goto cancel_sample;
1072 }
1073 goto copytobuffer;
1074 }
1075
1076 thsnap->ss_flags |= kHasDispatchSerial;
1077 bcopy(&dqserialnum, (char *)current_buffer->buffer + current_buffer->current_position, sizeof(dqserialnum));
1078 current_buffer->current_position += sizeof(dqserialnum);
1079 }
1080
1081 if (user64_regs) {
1082 framesize = 8;
1083 thsnap->ss_flags |= kUser64_p;
1084 } else {
1085 framesize = 4;
1086 }
1087
1088 /*
1089 * If we can't fit this entire stacktrace then cancel this record, wrap to the beginning,
1090 * and start again there so that we always store a full record.
1091 */
1092 if ((current_buffer->size - current_buffer->current_position) / framesize < btcount) {
1093 current_buffer->end_point = current_record_start;
1094 current_buffer->current_position = 0;
1095 if (current_record_start == 0) {
1096 /* This sample is too large to fit in the buffer even when we started at 0, so skip it */
1097 rv = ERANGE;
1098 goto cancel_sample;
1099 }
1100 goto copytobuffer;
1101 }
1102
1103 for (bti = 0; bti < btcount; bti++, current_buffer->current_position += framesize) {
1104 if (framesize == 8) {
1105 *(uint64_t *)(uintptr_t)(current_buffer->buffer + current_buffer->current_position) = frames[bti];
1106 } else {
1107 *(uint32_t *)(uintptr_t)(current_buffer->buffer + current_buffer->current_position) = (uint32_t)frames[bti];
1108 }
1109 }
1110
1111 if (current_buffer->end_point < current_buffer->current_position) {
1112 /*
1113 * Each time the cursor wraps around to the beginning, we leave a
1114 * differing amount of unused space at the end of the buffer. Make
1115 * sure the cursor pushes the end point in case we're making use of
1116 * more of the buffer than we did the last time we wrapped.
1117 */
1118 current_buffer->end_point = current_buffer->current_position;
1119 }
1120
1121 thsnap->nuser_frames = btcount;
1122
1123 /*
1124 * Now THIS is a hack.
1125 */
1126 if (current_buffer == &telemetry_buffer) {
1127 telemetry_bytes_since_last_mark += (current_buffer->current_position - current_record_start);
1128 if (telemetry_bytes_since_last_mark > telemetry_buffer_notify_at) {
1129 notify = true;
1130 }
1131 }
1132
1133 if (out_current_record_start != NULL) {
1134 *out_current_record_start = current_record_start;
1135 }
1136
1137 cancel_sample:
1138 if (release_buffer_lock) {
1139 lck_mtx_unlock(buffer_mtx);
1140 }
1141
1142 if (notify) {
1143 telemetry_notify_user();
1144 }
1145
1146 if (uuid_info_array != NULL) {
1147 kfree_data(uuid_info_array, uuid_info_array_size);
1148 }
1149
1150 return rv;
1151 }
1152
1153 #if TELEMETRY_DEBUG
1154 static void
log_telemetry_output(vm_offset_t buf,uint32_t pos,uint32_t sz)1155 log_telemetry_output(vm_offset_t buf, uint32_t pos, uint32_t sz)
1156 {
1157 struct micro_snapshot *p;
1158 uint32_t offset;
1159
1160 printf("Copying out %d bytes of telemetry at offset %d\n", sz, pos);
1161
1162 buf += pos;
1163
1164 /*
1165 * Find and log each timestamp in this chunk of buffer.
1166 */
1167 for (offset = 0; offset < sz; offset++) {
1168 p = (struct micro_snapshot *)(buf + offset);
1169 if (p->snapshot_magic == STACKSHOT_MICRO_SNAPSHOT_MAGIC) {
1170 printf("telemetry timestamp: %lld\n", p->ms_time);
1171 }
1172 }
1173 }
1174 #endif
1175
1176 int
telemetry_gather(user_addr_t buffer,uint32_t * length,bool mark)1177 telemetry_gather(user_addr_t buffer, uint32_t *length, bool mark)
1178 {
1179 return telemetry_buffer_gather(buffer, length, mark, &telemetry_buffer);
1180 }
1181
1182 int
telemetry_buffer_gather(user_addr_t buffer,uint32_t * length,bool mark,struct micro_snapshot_buffer * current_buffer)1183 telemetry_buffer_gather(user_addr_t buffer, uint32_t *length, bool mark, struct micro_snapshot_buffer * current_buffer)
1184 {
1185 int result = 0;
1186 uint32_t oldest_record_offset;
1187
1188 KDBG(MACHDBG_CODE(DBG_MACH_STACKSHOT, MICROSTACKSHOT_GATHER) | DBG_FUNC_START,
1189 mark, telemetry_bytes_since_last_mark, 0,
1190 (&telemetry_buffer != current_buffer));
1191
1192 TELEMETRY_LOCK();
1193
1194 if (current_buffer->buffer == 0) {
1195 *length = 0;
1196 goto out;
1197 }
1198
1199 if (*length < current_buffer->size) {
1200 result = KERN_NO_SPACE;
1201 goto out;
1202 }
1203
1204 /*
1205 * Copy the ring buffer out to userland in order sorted by time: least recent to most recent.
1206 * First, we need to search forward from the cursor to find the oldest record in our buffer.
1207 */
1208 oldest_record_offset = current_buffer->current_position;
1209 do {
1210 if (((oldest_record_offset + sizeof(uint32_t)) > current_buffer->size) ||
1211 ((oldest_record_offset + sizeof(uint32_t)) > current_buffer->end_point)) {
1212 if (*(uint32_t *)(uintptr_t)(current_buffer->buffer) == 0) {
1213 /*
1214 * There is no magic number at the start of the buffer, which means
1215 * it's empty; nothing to see here yet.
1216 */
1217 *length = 0;
1218 goto out;
1219 }
1220 /*
1221 * We've looked through the end of the active buffer without finding a valid
1222 * record; that means all valid records are in a single chunk, beginning at
1223 * the very start of the buffer.
1224 */
1225
1226 oldest_record_offset = 0;
1227 assert(*(uint32_t *)(uintptr_t)(current_buffer->buffer) == STACKSHOT_MICRO_SNAPSHOT_MAGIC);
1228 break;
1229 }
1230
1231 if (*(uint32_t *)(uintptr_t)(current_buffer->buffer + oldest_record_offset) == STACKSHOT_MICRO_SNAPSHOT_MAGIC) {
1232 break;
1233 }
1234
1235 /*
1236 * There are no alignment guarantees for micro-stackshot records, so we must search at each
1237 * byte offset.
1238 */
1239 oldest_record_offset++;
1240 } while (oldest_record_offset != current_buffer->current_position);
1241
1242 /*
1243 * If needed, copyout in two chunks: from the oldest record to the end of the buffer, and then
1244 * from the beginning of the buffer up to the current position.
1245 */
1246 if (oldest_record_offset != 0) {
1247 #if TELEMETRY_DEBUG
1248 log_telemetry_output(current_buffer->buffer, oldest_record_offset,
1249 current_buffer->end_point - oldest_record_offset);
1250 #endif
1251 if ((result = copyout((void *)(current_buffer->buffer + oldest_record_offset), buffer,
1252 current_buffer->end_point - oldest_record_offset)) != 0) {
1253 *length = 0;
1254 goto out;
1255 }
1256 *length = current_buffer->end_point - oldest_record_offset;
1257 } else {
1258 *length = 0;
1259 }
1260
1261 #if TELEMETRY_DEBUG
1262 log_telemetry_output(current_buffer->buffer, 0, current_buffer->current_position);
1263 #endif
1264 if ((result = copyout((void *)current_buffer->buffer, buffer + *length,
1265 current_buffer->current_position)) != 0) {
1266 *length = 0;
1267 goto out;
1268 }
1269 *length += (uint32_t)current_buffer->current_position;
1270
1271 out:
1272
1273 if (mark && (*length > 0)) {
1274 telemetry_bytes_since_last_mark = 0;
1275 }
1276
1277 TELEMETRY_UNLOCK();
1278
1279 KDBG(MACHDBG_CODE(DBG_MACH_STACKSHOT, MICROSTACKSHOT_GATHER) | DBG_FUNC_END,
1280 current_buffer->current_position, *length,
1281 current_buffer->end_point, (&telemetry_buffer != current_buffer));
1282
1283 return result;
1284 }
1285
1286 #if CONFIG_MACF
1287 static int
telemetry_macf_init_locked(size_t buffer_size)1288 telemetry_macf_init_locked(size_t buffer_size)
1289 {
1290 kern_return_t kr;
1291
1292 if (buffer_size > TELEMETRY_MAX_BUFFER_SIZE) {
1293 buffer_size = TELEMETRY_MAX_BUFFER_SIZE;
1294 }
1295
1296 telemetry_macf_buffer.size = buffer_size;
1297
1298 kr = kmem_alloc(kernel_map, &telemetry_macf_buffer.buffer,
1299 telemetry_macf_buffer.size, KMA_DATA | KMA_ZERO | KMA_PERMANENT,
1300 VM_KERN_MEMORY_SECURITY);
1301
1302 if (kr != KERN_SUCCESS) {
1303 kprintf("Telemetry (MACF): Allocation failed: %d\n", kr);
1304 return ENOMEM;
1305 }
1306
1307 return 0;
1308 }
1309
1310 int
telemetry_macf_mark_curthread(void)1311 telemetry_macf_mark_curthread(void)
1312 {
1313 thread_t thread = current_thread();
1314 task_t task = get_threadtask(thread);
1315 int rv = 0;
1316
1317 if (task == kernel_task) {
1318 /* Kernel threads never return to an AST boundary, and are ineligible */
1319 return EINVAL;
1320 }
1321
1322 /* Initialize the MACF telemetry buffer if needed. */
1323 TELEMETRY_MACF_LOCK();
1324 if (__improbable(telemetry_macf_buffer.size == 0)) {
1325 rv = telemetry_macf_init_locked(TELEMETRY_MACF_DEFAULT_BUFFER_SIZE);
1326
1327 if (rv != 0) {
1328 return rv;
1329 }
1330 }
1331 TELEMETRY_MACF_UNLOCK();
1332
1333 act_set_macf_telemetry_ast(thread);
1334 return 0;
1335 }
1336 #endif /* CONFIG_MACF */
1337
1338 /************************/
1339 /* BOOT PROFILE SUPPORT */
1340 /************************/
1341 /*
1342 * Boot Profiling
1343 *
1344 * The boot-profiling support is a mechanism to sample activity happening on the
1345 * system during boot. This mechanism sets up a periodic timer and on every timer fire,
1346 * captures a full backtrace into the boot profiling buffer. This buffer can be pulled
1347 * out and analyzed from user-space. It is turned on using the following boot-args:
1348 * "bootprofile_buffer_size" specifies the size of the boot profile buffer
1349 * "bootprofile_interval_ms" specifies the interval for the profiling timer
1350 *
1351 * Process Specific Boot Profiling
1352 *
1353 * The boot-arg "bootprofile_proc_name" can be used to specify a certain
1354 * process that needs to profiled during boot. Setting this boot-arg changes
1355 * the way stackshots are captured. At every timer fire, the code looks at the
1356 * currently running process and takes a stackshot only if the requested process
1357 * is on-core (which makes it unsuitable for MP systems).
1358 *
1359 * Trigger Events
1360 *
1361 * The boot-arg "bootprofile_type=boot" starts the timer during early boot. Using
1362 * "wake" starts the timer at AP wake from suspend-to-RAM.
1363 */
1364
1365 #define BOOTPROFILE_MAX_BUFFER_SIZE (64*1024*1024) /* see also COPYSIZELIMIT_PANIC */
1366
1367 vm_offset_t bootprofile_buffer = 0;
1368 uint32_t bootprofile_buffer_size = 0;
1369 uint32_t bootprofile_buffer_current_position = 0;
1370 uint32_t bootprofile_interval_ms = 0;
1371 uint64_t bootprofile_stackshot_flags = 0;
1372 uint64_t bootprofile_interval_abs = 0;
1373 uint64_t bootprofile_next_deadline = 0;
1374 uint32_t bootprofile_all_procs = 0;
1375 char bootprofile_proc_name[17];
1376 uint64_t bootprofile_delta_since_timestamp = 0;
1377 LCK_GRP_DECLARE(bootprofile_lck_grp, "bootprofile_group");
1378 LCK_MTX_DECLARE(bootprofile_mtx, &bootprofile_lck_grp);
1379
1380
1381 enum {
1382 kBootProfileDisabled = 0,
1383 kBootProfileStartTimerAtBoot,
1384 kBootProfileStartTimerAtWake
1385 } bootprofile_type = kBootProfileDisabled;
1386
1387
1388 static timer_call_data_t bootprofile_timer_call_entry;
1389
1390 #define BOOTPROFILE_LOCK() do { lck_mtx_lock(&bootprofile_mtx); } while(0)
1391 #define BOOTPROFILE_TRY_SPIN_LOCK() lck_mtx_try_lock_spin(&bootprofile_mtx)
1392 #define BOOTPROFILE_UNLOCK() do { lck_mtx_unlock(&bootprofile_mtx); } while(0)
1393
1394 static void bootprofile_timer_call(
1395 timer_call_param_t param0,
1396 timer_call_param_t param1);
1397
1398 void
bootprofile_init(void)1399 bootprofile_init(void)
1400 {
1401 kern_return_t ret;
1402 char type[32];
1403
1404 if (!PE_parse_boot_argn("bootprofile_buffer_size",
1405 &bootprofile_buffer_size, sizeof(bootprofile_buffer_size))) {
1406 bootprofile_buffer_size = 0;
1407 }
1408
1409 if (bootprofile_buffer_size > BOOTPROFILE_MAX_BUFFER_SIZE) {
1410 bootprofile_buffer_size = BOOTPROFILE_MAX_BUFFER_SIZE;
1411 }
1412
1413 if (!PE_parse_boot_argn("bootprofile_interval_ms",
1414 &bootprofile_interval_ms, sizeof(bootprofile_interval_ms))) {
1415 bootprofile_interval_ms = 0;
1416 }
1417
1418 if (!PE_parse_boot_argn("bootprofile_stackshot_flags",
1419 &bootprofile_stackshot_flags, sizeof(bootprofile_stackshot_flags))) {
1420 bootprofile_stackshot_flags = 0;
1421 }
1422
1423 if (!PE_parse_boot_argn("bootprofile_proc_name",
1424 &bootprofile_proc_name, sizeof(bootprofile_proc_name))) {
1425 bootprofile_all_procs = 1;
1426 bootprofile_proc_name[0] = '\0';
1427 }
1428
1429 if (PE_parse_boot_argn("bootprofile_type", type, sizeof(type))) {
1430 if (0 == strcmp(type, "boot")) {
1431 bootprofile_type = kBootProfileStartTimerAtBoot;
1432 } else if (0 == strcmp(type, "wake")) {
1433 bootprofile_type = kBootProfileStartTimerAtWake;
1434 } else {
1435 bootprofile_type = kBootProfileDisabled;
1436 }
1437 } else {
1438 bootprofile_type = kBootProfileDisabled;
1439 }
1440
1441 clock_interval_to_absolutetime_interval(bootprofile_interval_ms, NSEC_PER_MSEC, &bootprofile_interval_abs);
1442
1443 /* Both boot args must be set to enable */
1444 if ((bootprofile_type == kBootProfileDisabled) || (bootprofile_buffer_size == 0) || (bootprofile_interval_abs == 0)) {
1445 return;
1446 }
1447
1448 ret = kmem_alloc(kernel_map, &bootprofile_buffer, bootprofile_buffer_size,
1449 KMA_DATA | KMA_ZERO | KMA_PERMANENT, VM_KERN_MEMORY_DIAG);
1450 if (ret != KERN_SUCCESS) {
1451 kprintf("Boot profile: Allocation failed: %d\n", ret);
1452 return;
1453 }
1454
1455 kprintf("Boot profile: Sampling %s once per %u ms at %s\n",
1456 bootprofile_all_procs ? "all procs" : bootprofile_proc_name, bootprofile_interval_ms,
1457 bootprofile_type == kBootProfileStartTimerAtBoot ? "boot" : (bootprofile_type == kBootProfileStartTimerAtWake ? "wake" : "unknown"));
1458
1459 timer_call_setup(&bootprofile_timer_call_entry,
1460 bootprofile_timer_call,
1461 NULL);
1462
1463 if (bootprofile_type == kBootProfileStartTimerAtBoot) {
1464 bootprofile_next_deadline = mach_absolute_time() + bootprofile_interval_abs;
1465 timer_call_enter_with_leeway(&bootprofile_timer_call_entry,
1466 NULL,
1467 bootprofile_next_deadline,
1468 0,
1469 TIMER_CALL_SYS_NORMAL,
1470 false);
1471 }
1472 }
1473
1474 void
bootprofile_wake_from_sleep(void)1475 bootprofile_wake_from_sleep(void)
1476 {
1477 if (bootprofile_type == kBootProfileStartTimerAtWake) {
1478 bootprofile_next_deadline = mach_absolute_time() + bootprofile_interval_abs;
1479 timer_call_enter_with_leeway(&bootprofile_timer_call_entry,
1480 NULL,
1481 bootprofile_next_deadline,
1482 0,
1483 TIMER_CALL_SYS_NORMAL,
1484 false);
1485 }
1486 }
1487
1488
1489 static void
bootprofile_timer_call(timer_call_param_t param0 __unused,timer_call_param_t param1 __unused)1490 bootprofile_timer_call(
1491 timer_call_param_t param0 __unused,
1492 timer_call_param_t param1 __unused)
1493 {
1494 unsigned retbytes = 0;
1495 int pid_to_profile = -1;
1496
1497 if (!BOOTPROFILE_TRY_SPIN_LOCK()) {
1498 goto reprogram;
1499 }
1500
1501 /* Check if process-specific boot profiling is turned on */
1502 if (!bootprofile_all_procs) {
1503 /*
1504 * Since boot profiling initializes really early in boot, it is
1505 * possible that at this point, the task/proc is not initialized.
1506 * Nothing to do in that case.
1507 */
1508
1509 if ((current_task() != NULL) && (get_bsdtask_info(current_task()) != NULL) &&
1510 (0 == strncmp(bootprofile_proc_name, proc_name_address(get_bsdtask_info(current_task())), 17))) {
1511 pid_to_profile = proc_selfpid();
1512 } else {
1513 /*
1514 * Process-specific boot profiling requested but the on-core process is
1515 * something else. Nothing to do here.
1516 */
1517 BOOTPROFILE_UNLOCK();
1518 goto reprogram;
1519 }
1520 }
1521
1522 /* initiate a stackshot with whatever portion of the buffer is left */
1523 if (bootprofile_buffer_current_position < bootprofile_buffer_size) {
1524 uint64_t flags = STACKSHOT_KCDATA_FORMAT | STACKSHOT_TRYLOCK | STACKSHOT_SAVE_LOADINFO
1525 | STACKSHOT_GET_GLOBAL_MEM_STATS;
1526 #if defined(XNU_TARGET_OS_OSX)
1527 flags |= STACKSHOT_SAVE_KEXT_LOADINFO;
1528 #endif
1529
1530
1531 /* OR on flags specified in boot-args */
1532 flags |= bootprofile_stackshot_flags;
1533 if ((flags & STACKSHOT_COLLECT_DELTA_SNAPSHOT) && (bootprofile_delta_since_timestamp == 0)) {
1534 /* Can't take deltas until the first one */
1535 flags &= ~STACKSHOT_COLLECT_DELTA_SNAPSHOT;
1536 }
1537
1538 uint64_t timestamp = 0;
1539 if (bootprofile_stackshot_flags & STACKSHOT_COLLECT_DELTA_SNAPSHOT) {
1540 timestamp = mach_absolute_time();
1541 }
1542
1543 kern_return_t r = stack_snapshot_from_kernel(
1544 pid_to_profile, (void *)(bootprofile_buffer + bootprofile_buffer_current_position),
1545 bootprofile_buffer_size - bootprofile_buffer_current_position,
1546 flags, bootprofile_delta_since_timestamp, 0, &retbytes);
1547
1548 /*
1549 * We call with STACKSHOT_TRYLOCK because the stackshot lock is coarser
1550 * than the bootprofile lock. If someone else has the lock we'll just
1551 * try again later.
1552 */
1553
1554 if (r == KERN_LOCK_OWNED) {
1555 BOOTPROFILE_UNLOCK();
1556 goto reprogram;
1557 }
1558
1559 if (bootprofile_stackshot_flags & STACKSHOT_COLLECT_DELTA_SNAPSHOT &&
1560 r == KERN_SUCCESS) {
1561 bootprofile_delta_since_timestamp = timestamp;
1562 }
1563
1564 bootprofile_buffer_current_position += retbytes;
1565 }
1566
1567 BOOTPROFILE_UNLOCK();
1568
1569 /* If we didn't get any data or have run out of buffer space, stop profiling */
1570 if ((retbytes == 0) || (bootprofile_buffer_current_position == bootprofile_buffer_size)) {
1571 return;
1572 }
1573
1574
1575 reprogram:
1576 /* If the user gathered the buffer, no need to keep profiling */
1577 if (bootprofile_interval_abs == 0) {
1578 return;
1579 }
1580
1581 clock_deadline_for_periodic_event(bootprofile_interval_abs,
1582 mach_absolute_time(),
1583 &bootprofile_next_deadline);
1584 timer_call_enter_with_leeway(&bootprofile_timer_call_entry,
1585 NULL,
1586 bootprofile_next_deadline,
1587 0,
1588 TIMER_CALL_SYS_NORMAL,
1589 false);
1590 }
1591
1592 void
bootprofile_get(void ** buffer,uint32_t * length)1593 bootprofile_get(void **buffer, uint32_t *length)
1594 {
1595 BOOTPROFILE_LOCK();
1596 *buffer = (void*) bootprofile_buffer;
1597 *length = bootprofile_buffer_current_position;
1598 BOOTPROFILE_UNLOCK();
1599 }
1600
1601 int
bootprofile_gather(user_addr_t buffer,uint32_t * length)1602 bootprofile_gather(user_addr_t buffer, uint32_t *length)
1603 {
1604 int result = 0;
1605
1606 BOOTPROFILE_LOCK();
1607
1608 if (bootprofile_buffer == 0) {
1609 *length = 0;
1610 goto out;
1611 }
1612
1613 if (*length < bootprofile_buffer_current_position) {
1614 result = KERN_NO_SPACE;
1615 goto out;
1616 }
1617
1618 if ((result = copyout((void *)bootprofile_buffer, buffer,
1619 bootprofile_buffer_current_position)) != 0) {
1620 *length = 0;
1621 goto out;
1622 }
1623 *length = bootprofile_buffer_current_position;
1624
1625 /* cancel future timers */
1626 bootprofile_interval_abs = 0;
1627
1628 out:
1629
1630 BOOTPROFILE_UNLOCK();
1631
1632 return result;
1633 }
1634