]> git.saurik.com Git - apple/xnu.git/blob - osfmk/kern/telemetry.c
xnu-2422.1.72.tar.gz
[apple/xnu.git] / osfmk / kern / telemetry.c
1 /*
2 * Copyright (c) 2012-2013 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 #include <mach/host_priv.h>
29 #include <mach/host_special_ports.h>
30 #include <mach/mach_types.h>
31 #include <mach/telemetry_notification_server.h>
32
33 #include <kern/assert.h>
34 #include <kern/clock.h>
35 #include <kern/debug.h>
36 #include <kern/host.h>
37 #include <kern/kalloc.h>
38 #include <kern/kern_types.h>
39 #include <kern/locks.h>
40 #include <kern/misc_protos.h>
41 #include <kern/sched.h>
42 #include <kern/sched_prim.h>
43 #include <kern/telemetry.h>
44 #include <kern/timer_call.h>
45
46 #include <pexpert/pexpert.h>
47
48 #include <vm/vm_kern.h>
49 #include <vm/vm_shared_region.h>
50
51 #include <kperf/kperf.h>
52 #include <kperf/context.h>
53 #include <kperf/callstack.h>
54
55 #include <sys/kdebug.h>
56 #include <uuid/uuid.h>
57 #include <kdp/kdp_dyld.h>
58
59 #define TELEMETRY_DEBUG 0
60
61 extern int proc_pid(void *);
62 extern char *proc_name_address(void *p);
63 extern uint64_t proc_uniqueid(void *p);
64 extern uint64_t proc_was_throttled(void *p);
65 extern uint64_t proc_did_throttle(void *p);
66 extern uint64_t get_dispatchqueue_serialno_offset_from_proc(void *p);
67 extern int proc_selfpid(void);
68
69 void telemetry_take_sample(thread_t thread, uint8_t microsnapshot_flags);
70
71 #define TELEMETRY_DEFAULT_SAMPLE_RATE (1) /* 1 sample every 1 second */
72 #define TELEMETRY_DEFAULT_BUFFER_SIZE (16*1024)
73 #define TELEMETRY_MAX_BUFFER_SIZE (64*1024)
74
75 #define TELEMETRY_DEFAULT_NOTIFY_LEEWAY (4*1024) // Userland gets 4k of leeway to collect data after notification
76
77 uint32_t telemetry_sample_rate = 0;
78 volatile boolean_t telemetry_needs_record = FALSE;
79 volatile boolean_t telemetry_needs_timer_arming_record = FALSE;
80
81 /*
82 * If TRUE, record micro-stackshot samples for all tasks.
83 * If FALSE, only sample tasks which are marked for telemetry.
84 */
85 boolean_t telemetry_sample_all_tasks = FALSE;
86 uint32_t telemetry_active_tasks = 0; // Number of tasks opted into telemetry
87
88 uint32_t telemetry_timestamp = 0;
89
90 vm_offset_t telemetry_buffer = 0;
91 uint32_t telemetry_buffer_size = 0;
92 uint32_t telemetry_buffer_current_position = 0;
93 uint32_t telemetry_buffer_end_point = 0; // If we've wrapped, where does the last record end?
94 int telemetry_bytes_since_last_mark = -1; // How much data since buf was last marked?
95 int telemetry_buffer_notify_at = 0;
96
97 lck_grp_t telemetry_lck_grp;
98 lck_mtx_t telemetry_mtx;
99
100 #define TELEMETRY_LOCK() do { lck_mtx_lock(&telemetry_mtx); } while(0)
101 #define TELEMETRY_TRY_SPIN_LOCK() lck_mtx_try_lock_spin(&telemetry_mtx)
102 #define TELEMETRY_UNLOCK() do { lck_mtx_unlock(&telemetry_mtx); } while(0)
103
104 void telemetry_init(void)
105 {
106 kern_return_t ret;
107 uint32_t telemetry_notification_leeway;
108
109 lck_grp_init(&telemetry_lck_grp, "telemetry group", LCK_GRP_ATTR_NULL);
110 lck_mtx_init(&telemetry_mtx, &telemetry_lck_grp, LCK_ATTR_NULL);
111
112 if (!PE_parse_boot_argn("telemetry_buffer_size", &telemetry_buffer_size, sizeof(telemetry_buffer_size))) {
113 telemetry_buffer_size = TELEMETRY_DEFAULT_BUFFER_SIZE;
114 }
115
116 if (telemetry_buffer_size > TELEMETRY_MAX_BUFFER_SIZE)
117 telemetry_buffer_size = TELEMETRY_MAX_BUFFER_SIZE;
118
119 ret = kmem_alloc(kernel_map, &telemetry_buffer, telemetry_buffer_size);
120 if (ret != KERN_SUCCESS) {
121 kprintf("Telemetry: Allocation failed: %d\n", ret);
122 return;
123 }
124
125 if (!PE_parse_boot_argn("telemetry_notification_leeway", &telemetry_notification_leeway, sizeof(telemetry_notification_leeway))) {
126 /*
127 * By default, notify the user to collect the buffer when there is this much space left in the buffer.
128 */
129 telemetry_notification_leeway = TELEMETRY_DEFAULT_NOTIFY_LEEWAY;
130 }
131 if (telemetry_notification_leeway >= telemetry_buffer_size) {
132 printf("telemetry: nonsensical telemetry_notification_leeway boot-arg %d changed to %d\n",
133 telemetry_notification_leeway, TELEMETRY_DEFAULT_NOTIFY_LEEWAY);
134 telemetry_notification_leeway = TELEMETRY_DEFAULT_NOTIFY_LEEWAY;
135 }
136 telemetry_buffer_notify_at = telemetry_buffer_size - telemetry_notification_leeway;
137
138 if (!PE_parse_boot_argn("telemetry_sample_rate", &telemetry_sample_rate, sizeof(telemetry_sample_rate))) {
139 telemetry_sample_rate = TELEMETRY_DEFAULT_SAMPLE_RATE;
140 }
141
142 /*
143 * To enable telemetry for all tasks, include "telemetry_sample_all_tasks=1" in boot-args.
144 */
145 if (!PE_parse_boot_argn("telemetry_sample_all_tasks", &telemetry_sample_all_tasks, sizeof(telemetry_sample_all_tasks))) {
146
147 telemetry_sample_all_tasks = TRUE;
148
149 }
150
151 kprintf("Telemetry: Sampling %stasks once per %u second%s\n",
152 (telemetry_sample_all_tasks) ? "all " : "",
153 telemetry_sample_rate, telemetry_sample_rate == 1 ? "" : "s");
154 }
155
156 /*
157 * Enable or disable global microstackshots (ie telemetry_sample_all_tasks).
158 *
159 * enable_disable == 1: turn it on
160 * enable_disable == 0: turn it off
161 */
162 void
163 telemetry_global_ctl(int enable_disable)
164 {
165 if (enable_disable == 1) {
166 telemetry_sample_all_tasks = TRUE;
167 } else {
168 telemetry_sample_all_tasks = FALSE;
169 }
170 }
171
172 /*
173 * Opt the given task into or out of the telemetry stream.
174 *
175 * Supported reasons (callers may use any or all of):
176 * TF_CPUMON_WARNING
177 * TF_WAKEMON_WARNING
178 *
179 * enable_disable == 1: turn it on
180 * enable_disable == 0: turn it off
181 */
182 void
183 telemetry_task_ctl(task_t task, uint32_t reasons, int enable_disable)
184 {
185 task_lock(task);
186 telemetry_task_ctl_locked(task, reasons, enable_disable);
187 task_unlock(task);
188 }
189
190 void
191 telemetry_task_ctl_locked(task_t task, uint32_t reasons, int enable_disable)
192 {
193 uint32_t origflags;
194
195 assert((reasons != 0) && ((reasons | TF_TELEMETRY) == TF_TELEMETRY));
196
197 task_lock_assert_owned(task);
198
199 origflags = task->t_flags;
200
201 if (enable_disable == 1) {
202 task->t_flags |= reasons;
203 if ((origflags & TF_TELEMETRY) == 0) {
204 OSIncrementAtomic(&telemetry_active_tasks);
205 #if TELEMETRY_DEBUG
206 printf("%s: telemetry OFF -> ON (%d active)\n", proc_name_address(task->bsd_info), telemetry_active_tasks);
207 #endif
208 }
209 } else {
210 task->t_flags &= ~reasons;
211 if (((origflags & TF_TELEMETRY) != 0) && ((task->t_flags & TF_TELEMETRY) == 0)) {
212 /*
213 * If this task went from having at least one telemetry bit to having none,
214 * the net change was to disable telemetry for the task.
215 */
216 OSDecrementAtomic(&telemetry_active_tasks);
217 #if TELEMETRY_DEBUG
218 printf("%s: telemetry ON -> OFF (%d active)\n", proc_name_address(task->bsd_info), telemetry_active_tasks);
219 #endif
220 }
221 }
222 }
223
224 /*
225 * Determine if the current thread is eligible for telemetry:
226 *
227 * telemetry_sample_all_tasks: All threads are eligible. This takes precedence.
228 * telemetry_active_tasks: Count of tasks opted in.
229 * task->t_flags & TF_TELEMETRY: This task is opted in.
230 */
231 static boolean_t
232 telemetry_is_active(thread_t thread)
233 {
234 if (telemetry_sample_all_tasks == TRUE) {
235 return (TRUE);
236 }
237
238 if ((telemetry_active_tasks > 0) && ((thread->task->t_flags & TF_TELEMETRY) != 0)) {
239 return (TRUE);
240 }
241
242 return (FALSE);
243 }
244
245 /*
246 * Userland is arming a timer. If we are eligible for such a record,
247 * sample now. No need to do this one at the AST because we're already at
248 * a safe place in this system call.
249 */
250 int telemetry_timer_event(__unused uint64_t deadline, __unused uint64_t interval, __unused uint64_t leeway)
251 {
252 if (telemetry_needs_timer_arming_record == TRUE) {
253 telemetry_needs_timer_arming_record = FALSE;
254 telemetry_take_sample(current_thread(), kTimerArmingRecord | kUserMode);
255 }
256
257 return (0);
258 }
259
260 /*
261 * Mark the current thread for an interrupt-based
262 * telemetry record, to be sampled at the next AST boundary.
263 */
264 void telemetry_mark_curthread(boolean_t interrupted_userspace)
265 {
266 thread_t thread = current_thread();
267
268 /*
269 * If telemetry isn't active for this thread, return and try
270 * again next time.
271 */
272 if (telemetry_is_active(thread) == FALSE) {
273 return;
274 }
275
276 telemetry_needs_record = FALSE;
277 thread_ast_set(thread, interrupted_userspace ? AST_TELEMETRY_USER : AST_TELEMETRY_KERNEL);
278 ast_propagate(thread->ast);
279 }
280
281 void compute_telemetry(void *arg __unused)
282 {
283 if (telemetry_sample_all_tasks || (telemetry_active_tasks > 0)) {
284 if ((++telemetry_timestamp) % telemetry_sample_rate == 0) {
285 /*
286 * To avoid overloading the system with telemetry ASTs, make
287 * sure we don't add more requests while existing ones
288 * are in-flight.
289 */
290 if (TELEMETRY_TRY_SPIN_LOCK()) {
291 telemetry_needs_record = TRUE;
292 telemetry_needs_timer_arming_record = TRUE;
293 TELEMETRY_UNLOCK();
294 }
295 }
296 }
297 }
298
299 /*
300 * If userland has registered a port for telemetry notifications, send one now.
301 */
302 static void
303 telemetry_notify_user(void)
304 {
305 mach_port_t user_port;
306 uint32_t flags = 0;
307 int error;
308
309 error = host_get_telemetry_port(host_priv_self(), &user_port);
310 if ((error != KERN_SUCCESS) || !IPC_PORT_VALID(user_port)) {
311 return;
312 }
313
314 telemetry_notification(user_port, flags);
315 }
316
317 void telemetry_ast(thread_t thread, boolean_t interrupted_userspace)
318 {
319 uint8_t microsnapshot_flags = kInterruptRecord;
320
321 if (interrupted_userspace)
322 microsnapshot_flags |= kUserMode;
323
324 telemetry_take_sample(thread, microsnapshot_flags);
325 }
326
327 void telemetry_take_sample(thread_t thread, uint8_t microsnapshot_flags)
328 {
329 task_t task;
330 void *p;
331 struct kperf_context ctx;
332 struct callstack cs;
333 uint32_t btcount, bti;
334 struct micro_snapshot *msnap;
335 struct task_snapshot *tsnap;
336 struct thread_snapshot *thsnap;
337 clock_sec_t secs;
338 clock_usec_t usecs;
339 vm_size_t framesize;
340 uint32_t current_record_start;
341 uint32_t tmp = 0;
342 boolean_t notify = FALSE;
343
344 if (thread == THREAD_NULL)
345 return;
346
347 task = thread->task;
348 if ((task == TASK_NULL) || (task == kernel_task))
349 return;
350
351 /* telemetry_XXX accessed outside of lock for instrumentation only */
352 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_STACKSHOT, MICROSTACKSHOT_RECORD) | DBG_FUNC_START, microsnapshot_flags, telemetry_bytes_since_last_mark, 0, 0, 0);
353
354 p = get_bsdtask_info(task);
355
356 ctx.cur_thread = thread;
357 ctx.cur_pid = proc_pid(p);
358
359 /*
360 * Gather up the data we'll need for this sample. The sample is written into the kernel
361 * buffer with the global telemetry lock held -- so we must do our (possibly faulting)
362 * copies from userland here, before taking the lock.
363 */
364 kperf_ucallstack_sample(&cs, &ctx);
365 if (!(cs.flags & CALLSTACK_VALID))
366 return;
367
368 /*
369 * Find the actual [slid] address of the shared cache's UUID, and copy it in from userland.
370 */
371 int shared_cache_uuid_valid = 0;
372 uint64_t shared_cache_base_address;
373 struct _dyld_cache_header shared_cache_header;
374 uint64_t shared_cache_slide;
375
376 /*
377 * Don't copy in the entire shared cache header; we only need the UUID. Calculate the
378 * offset of that one field.
379 */
380 int sc_header_uuid_offset = (char *)&shared_cache_header.uuid - (char *)&shared_cache_header;
381 vm_shared_region_t sr = vm_shared_region_get(task);
382 if (sr != NULL) {
383 if ((vm_shared_region_start_address(sr, &shared_cache_base_address) == KERN_SUCCESS) &&
384 (copyin(shared_cache_base_address + sc_header_uuid_offset, (char *)&shared_cache_header.uuid,
385 sizeof (shared_cache_header.uuid)) == 0)) {
386 shared_cache_uuid_valid = 1;
387 shared_cache_slide = vm_shared_region_get_slide(sr);
388 }
389 // vm_shared_region_get() gave us a reference on the shared region.
390 vm_shared_region_deallocate(sr);
391 }
392
393 /*
394 * Retrieve the array of UUID's for binaries used by this task.
395 * We reach down into DYLD's data structures to find the array.
396 *
397 * XXX - make this common with kdp?
398 */
399 uint32_t uuid_info_count = 0;
400 mach_vm_address_t uuid_info_addr = 0;
401 if (task_has_64BitAddr(task)) {
402 struct user64_dyld_all_image_infos task_image_infos;
403 if (copyin(task->all_image_info_addr, (char *)&task_image_infos, sizeof(task_image_infos)) == 0) {
404 uuid_info_count = (uint32_t)task_image_infos.uuidArrayCount;
405 uuid_info_addr = task_image_infos.uuidArray;
406 }
407 } else {
408 struct user32_dyld_all_image_infos task_image_infos;
409 if (copyin(task->all_image_info_addr, (char *)&task_image_infos, sizeof(task_image_infos)) == 0) {
410 uuid_info_count = task_image_infos.uuidArrayCount;
411 uuid_info_addr = task_image_infos.uuidArray;
412 }
413 }
414
415 /*
416 * If we get a NULL uuid_info_addr (which can happen when we catch dyld in the middle of updating
417 * this data structure), we zero the uuid_info_count so that we won't even try to save load info
418 * for this task.
419 */
420 if (!uuid_info_addr) {
421 uuid_info_count = 0;
422 }
423
424 uint32_t uuid_info_size = (uint32_t)(task_has_64BitAddr(thread->task) ? sizeof(struct user64_dyld_uuid_info) : sizeof(struct user32_dyld_uuid_info));
425 uint32_t uuid_info_array_size = uuid_info_count * uuid_info_size;
426 char *uuid_info_array = NULL;
427
428 if (uuid_info_count > 0) {
429 if ((uuid_info_array = (char *)kalloc(uuid_info_array_size)) == NULL) {
430 return;
431 }
432
433 /*
434 * Copy in the UUID info array.
435 * It may be nonresident, in which case just fix up nloadinfos to 0 in the task snapshot.
436 */
437 if (copyin(uuid_info_addr, uuid_info_array, uuid_info_array_size) != 0) {
438 kfree(uuid_info_array, uuid_info_array_size);
439 uuid_info_array = NULL;
440 uuid_info_array_size = 0;
441 }
442 }
443
444 /*
445 * Look for a dispatch queue serial number, and copy it in from userland if present.
446 */
447 uint64_t dqserialnum = 0;
448 int dqserialnum_valid = 0;
449
450 uint64_t dqkeyaddr = thread_dispatchqaddr(thread);
451 if (dqkeyaddr != 0) {
452 uint64_t dqaddr = 0;
453 uint64_t dq_serialno_offset = get_dispatchqueue_serialno_offset_from_proc(task->bsd_info);
454 if ((copyin(dqkeyaddr, (char *)&dqaddr, (task_has_64BitAddr(task) ? 8 : 4)) == 0) &&
455 (dqaddr != 0) && (dq_serialno_offset != 0)) {
456 uint64_t dqserialnumaddr = dqaddr + dq_serialno_offset;
457 if (copyin(dqserialnumaddr, (char *)&dqserialnum, (task_has_64BitAddr(task) ? 8 : 4)) == 0) {
458 dqserialnum_valid = 1;
459 }
460 }
461 }
462
463 clock_get_calendar_microtime(&secs, &usecs);
464
465 TELEMETRY_LOCK();
466
467 /*
468 * We do the bulk of the operation under the telemetry lock, on assumption that
469 * any page faults during execution will not cause another AST_TELEMETRY_ALL
470 * to deadlock; they will just block until we finish. This makes it easier
471 * to copy into the buffer directly. As soon as we unlock, userspace can copy
472 * out of our buffer.
473 */
474
475 copytobuffer:
476
477 current_record_start = telemetry_buffer_current_position;
478
479 if ((telemetry_buffer_size - telemetry_buffer_current_position) < sizeof(struct micro_snapshot)) {
480 /*
481 * We can't fit a record in the space available, so wrap around to the beginning.
482 * Save the current position as the known end point of valid data.
483 */
484 telemetry_buffer_end_point = current_record_start;
485 telemetry_buffer_current_position = 0;
486 goto copytobuffer;
487 }
488
489 msnap = (struct micro_snapshot *)(uintptr_t)(telemetry_buffer + telemetry_buffer_current_position);
490 msnap->snapshot_magic = STACKSHOT_MICRO_SNAPSHOT_MAGIC;
491 msnap->ms_flags = microsnapshot_flags;
492 msnap->ms_opaque_flags = 0; /* namespace managed by userspace */
493 msnap->ms_cpu = 0; /* XXX - does this field make sense for a micro-stackshot? */
494 msnap->ms_time = secs;
495 msnap->ms_time_microsecs = usecs;
496
497 telemetry_buffer_current_position += sizeof(struct micro_snapshot);
498
499 if ((telemetry_buffer_size - telemetry_buffer_current_position) < sizeof(struct task_snapshot)) {
500 telemetry_buffer_end_point = current_record_start;
501 telemetry_buffer_current_position = 0;
502 goto copytobuffer;
503 }
504
505 tsnap = (struct task_snapshot *)(uintptr_t)(telemetry_buffer + telemetry_buffer_current_position);
506 bzero(tsnap, sizeof(*tsnap));
507 tsnap->snapshot_magic = STACKSHOT_TASK_SNAPSHOT_MAGIC;
508 tsnap->pid = proc_pid(p);
509 tsnap->uniqueid = proc_uniqueid(p);
510 tsnap->user_time_in_terminated_threads = task->total_user_time;
511 tsnap->system_time_in_terminated_threads = task->total_system_time;
512 tsnap->suspend_count = task->suspend_count;
513 tsnap->task_size = pmap_resident_count(task->map->pmap);
514 tsnap->faults = task->faults;
515 tsnap->pageins = task->pageins;
516 tsnap->cow_faults = task->cow_faults;
517 /*
518 * The throttling counters are maintained as 64-bit counters in the proc
519 * structure. However, we reserve 32-bits (each) for them in the task_snapshot
520 * struct to save space and since we do not expect them to overflow 32-bits. If we
521 * find these values overflowing in the future, the fix would be to simply
522 * upgrade these counters to 64-bit in the task_snapshot struct
523 */
524 tsnap->was_throttled = (uint32_t) proc_was_throttled(p);
525 tsnap->did_throttle = (uint32_t) proc_did_throttle(p);
526
527 if (task->t_flags & TF_TELEMETRY) {
528 tsnap->ss_flags |= kTaskRsrcFlagged;
529 }
530
531 proc_get_darwinbgstate(task, &tmp);
532
533 if (tmp & PROC_FLAG_DARWINBG) {
534 tsnap->ss_flags |= kTaskDarwinBG;
535 }
536 if (tmp & PROC_FLAG_EXT_DARWINBG) {
537 tsnap->ss_flags |= kTaskExtDarwinBG;
538 }
539
540 if (task->requested_policy.t_role == TASK_FOREGROUND_APPLICATION) {
541 tsnap->ss_flags |= kTaskIsForeground;
542 }
543
544 if (tmp & PROC_FLAG_ADAPTIVE_IMPORTANT) {
545 tsnap->ss_flags |= kTaskIsBoosted;
546 }
547
548 if (tmp & PROC_FLAG_SUPPRESSED) {
549 tsnap->ss_flags |= kTaskIsSuppressed;
550 }
551
552 tsnap->latency_qos = task_grab_latency_qos(task);
553
554 strlcpy(tsnap->p_comm, proc_name_address(p), sizeof(tsnap->p_comm));
555 if (task_has_64BitAddr(thread->task)) {
556 tsnap->ss_flags |= kUser64_p;
557 }
558
559 if (shared_cache_uuid_valid) {
560 tsnap->shared_cache_slide = shared_cache_slide;
561 bcopy(shared_cache_header.uuid, tsnap->shared_cache_identifier, sizeof (shared_cache_header.uuid));
562 }
563
564 telemetry_buffer_current_position += sizeof(struct task_snapshot);
565
566 /*
567 * Directly after the task snapshot, place the array of UUID's corresponding to the binaries
568 * used by this task.
569 */
570 if ((telemetry_buffer_size - telemetry_buffer_current_position) < uuid_info_array_size) {
571 telemetry_buffer_end_point = current_record_start;
572 telemetry_buffer_current_position = 0;
573 goto copytobuffer;
574 }
575
576 /*
577 * Copy the UUID info array into our sample.
578 */
579 if (uuid_info_array_size > 0) {
580 bcopy(uuid_info_array, (char *)(telemetry_buffer + telemetry_buffer_current_position), uuid_info_array_size);
581 tsnap->nloadinfos = uuid_info_count;
582 }
583
584 telemetry_buffer_current_position += uuid_info_array_size;
585
586 /*
587 * After the task snapshot & list of binary UUIDs, we place a thread snapshot.
588 */
589
590 if ((telemetry_buffer_size - telemetry_buffer_current_position) < sizeof(struct thread_snapshot)) {
591 /* wrap and overwrite */
592 telemetry_buffer_end_point = current_record_start;
593 telemetry_buffer_current_position = 0;
594 goto copytobuffer;
595 }
596
597 thsnap = (struct thread_snapshot *)(uintptr_t)(telemetry_buffer + telemetry_buffer_current_position);
598 bzero(thsnap, sizeof(*thsnap));
599
600 thsnap->snapshot_magic = STACKSHOT_THREAD_SNAPSHOT_MAGIC;
601 thsnap->thread_id = thread_tid(thread);
602 thsnap->state = thread->state;
603 thsnap->priority = thread->priority;
604 thsnap->sched_pri = thread->sched_pri;
605 thsnap->sched_flags = thread->sched_flags;
606 thsnap->ss_flags |= kStacksPCOnly;
607
608 if (thread->effective_policy.darwinbg) {
609 thsnap->ss_flags |= kThreadDarwinBG;
610 }
611
612 thsnap->user_time = timer_grab(&thread->user_timer);
613
614 uint64_t tval = timer_grab(&thread->system_timer);
615
616 if (thread->precise_user_kernel_time) {
617 thsnap->system_time = tval;
618 } else {
619 thsnap->user_time += tval;
620 thsnap->system_time = 0;
621 }
622
623 telemetry_buffer_current_position += sizeof(struct thread_snapshot);
624
625 /*
626 * If this thread has a dispatch queue serial number, include it here.
627 */
628 if (dqserialnum_valid) {
629 if ((telemetry_buffer_size - telemetry_buffer_current_position) < sizeof(dqserialnum)) {
630 /* wrap and overwrite */
631 telemetry_buffer_end_point = current_record_start;
632 telemetry_buffer_current_position = 0;
633 goto copytobuffer;
634 }
635
636 thsnap->ss_flags |= kHasDispatchSerial;
637 bcopy(&dqserialnum, (char *)telemetry_buffer + telemetry_buffer_current_position, sizeof (dqserialnum));
638 telemetry_buffer_current_position += sizeof (dqserialnum);
639 }
640
641 if (task_has_64BitAddr(task)) {
642 framesize = 8;
643 thsnap->ss_flags |= kUser64_p;
644 } else {
645 framesize = 4;
646 }
647
648 btcount = cs.nframes;
649
650 /*
651 * If we can't fit this entire stacktrace then cancel this record, wrap to the beginning,
652 * and start again there so that we always store a full record.
653 */
654 if ((telemetry_buffer_size - telemetry_buffer_current_position)/framesize < btcount) {
655 telemetry_buffer_end_point = current_record_start;
656 telemetry_buffer_current_position = 0;
657 goto copytobuffer;
658 }
659
660 for (bti=0; bti < btcount; bti++, telemetry_buffer_current_position += framesize) {
661 if (framesize == 8) {
662 *(uint64_t *)(uintptr_t)(telemetry_buffer + telemetry_buffer_current_position) = cs.frames[bti];
663 } else {
664 *(uint32_t *)(uintptr_t)(telemetry_buffer + telemetry_buffer_current_position) = (uint32_t)cs.frames[bti];
665 }
666 }
667
668 if (telemetry_buffer_end_point < telemetry_buffer_current_position) {
669 /*
670 * Each time the cursor wraps around to the beginning, we leave a
671 * differing amount of unused space at the end of the buffer. Make
672 * sure the cursor pushes the end point in case we're making use of
673 * more of the buffer than we did the last time we wrapped.
674 */
675 telemetry_buffer_end_point = telemetry_buffer_current_position;
676 }
677
678 thsnap->nuser_frames = btcount;
679
680 telemetry_bytes_since_last_mark += (telemetry_buffer_current_position - current_record_start);
681 if (telemetry_bytes_since_last_mark > telemetry_buffer_notify_at) {
682 notify = TRUE;
683 }
684
685 TELEMETRY_UNLOCK();
686
687 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_STACKSHOT, MICROSTACKSHOT_RECORD) | DBG_FUNC_END, notify, telemetry_bytes_since_last_mark, telemetry_buffer_current_position, telemetry_buffer_end_point, 0);
688
689 if (notify) {
690 telemetry_notify_user();
691 }
692
693 if (uuid_info_array != NULL) {
694 kfree(uuid_info_array, uuid_info_array_size);
695 }
696 }
697
698 #if TELEMETRY_DEBUG
699 static void
700 log_telemetry_output(vm_offset_t buf, uint32_t pos, uint32_t sz)
701 {
702 struct micro_snapshot *p;
703 uint32_t offset;
704
705 printf("Copying out %d bytes of telemetry at offset %d\n", sz, pos);
706
707 buf += pos;
708
709 /*
710 * Find and log each timestamp in this chunk of buffer.
711 */
712 for (offset = 0; offset < sz; offset++) {
713 p = (struct micro_snapshot *)(buf + offset);
714 if (p->snapshot_magic == STACKSHOT_MICRO_SNAPSHOT_MAGIC) {
715 printf("telemetry timestamp: %lld\n", p->ms_time);
716 }
717 }
718 }
719 #endif
720
721 int telemetry_gather(user_addr_t buffer, uint32_t *length, boolean_t mark)
722 {
723 int result = 0;
724 uint32_t oldest_record_offset;
725
726 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_STACKSHOT, MICROSTACKSHOT_GATHER) | DBG_FUNC_START, mark, telemetry_bytes_since_last_mark, 0, 0, 0);
727
728 TELEMETRY_LOCK();
729
730 if (telemetry_buffer == 0) {
731 *length = 0;
732 goto out;
733 }
734
735 if (*length < telemetry_buffer_size) {
736 result = KERN_NO_SPACE;
737 goto out;
738 }
739
740 /*
741 * Copy the ring buffer out to userland in order sorted by time: least recent to most recent.
742 * First, we need to search forward from the cursor to find the oldest record in our buffer.
743 */
744 oldest_record_offset = telemetry_buffer_current_position;
745 do {
746 if ((oldest_record_offset == telemetry_buffer_size) ||
747 (oldest_record_offset == telemetry_buffer_end_point)) {
748
749 if (*(uint32_t *)(uintptr_t)(telemetry_buffer) == 0) {
750 /*
751 * There is no magic number at the start of the buffer, which means
752 * it's empty; nothing to see here yet.
753 */
754 *length = 0;
755 goto out;
756 }
757 /*
758 * We've looked through the end of the active buffer without finding a valid
759 * record; that means all valid records are in a single chunk, beginning at
760 * the very start of the buffer.
761 */
762
763 oldest_record_offset = 0;
764 assert(*(uint32_t *)(uintptr_t)(telemetry_buffer) == STACKSHOT_MICRO_SNAPSHOT_MAGIC);
765 break;
766 }
767
768 if (*(uint32_t *)(uintptr_t)(telemetry_buffer + oldest_record_offset) == STACKSHOT_MICRO_SNAPSHOT_MAGIC)
769 break;
770
771 /*
772 * There are no alignment guarantees for micro-stackshot records, so we must search at each
773 * byte offset.
774 */
775 oldest_record_offset++;
776 } while (oldest_record_offset != telemetry_buffer_current_position);
777
778 /*
779 * If needed, copyout in two chunks: from the oldest record to the end of the buffer, and then
780 * from the beginning of the buffer up to the current position.
781 */
782 if (oldest_record_offset != 0) {
783 #if TELEMETRY_DEBUG
784 log_telemetry_output(telemetry_buffer, oldest_record_offset,
785 telemetry_buffer_end_point - oldest_record_offset);
786 #endif
787 if ((result = copyout((void *)(telemetry_buffer + oldest_record_offset), buffer,
788 telemetry_buffer_end_point - oldest_record_offset)) != 0) {
789 *length = 0;
790 goto out;
791 }
792 *length = telemetry_buffer_end_point - oldest_record_offset;
793 } else {
794 *length = 0;
795 }
796
797 #if TELEMETRY_DEBUG
798 log_telemetry_output(telemetry_buffer, 0, telemetry_buffer_current_position);
799 #endif
800 if ((result = copyout((void *)telemetry_buffer, buffer + *length,
801 telemetry_buffer_current_position)) != 0) {
802 *length = 0;
803 goto out;
804 }
805 *length += (uint32_t)telemetry_buffer_current_position;
806
807 out:
808
809 if (mark && (*length > 0)) {
810 telemetry_bytes_since_last_mark = 0;
811 }
812
813 TELEMETRY_UNLOCK();
814
815 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_STACKSHOT, MICROSTACKSHOT_GATHER) | DBG_FUNC_END, telemetry_buffer_current_position, *length, telemetry_buffer_end_point, 0, 0);
816
817 return (result);
818 }
819
820 /************************/
821 /* BOOT PROFILE SUPPORT */
822 /************************/
823 /*
824 * Boot Profiling
825 *
826 * The boot-profiling support is a mechanism to sample activity happening on the
827 * system during boot. This mechanism sets up a periodic timer and on every timer fire,
828 * captures a full backtrace into the boot profiling buffer. This buffer can be pulled
829 * out and analyzed from user-space. It is turned on using the following boot-args:
830 * "bootprofile_buffer_size" specifies the size of the boot profile buffer
831 * "bootprofile_interval_ms" specifies the interval for the profiling timer
832 *
833 * Process Specific Boot Profiling
834 *
835 * The boot-arg "bootprofile_proc_name" can be used to specify a certain
836 * process that needs to profiled during boot. Setting this boot-arg changes
837 * the way stackshots are captured. At every timer fire, the code looks at the
838 * currently running process and takes a stackshot only if the requested process
839 * is on-core (which makes it unsuitable for MP systems).
840 *
841 */
842
843 #define BOOTPROFILE_MAX_BUFFER_SIZE (64*1024*1024) /* see also COPYSIZELIMIT_PANIC */
844
845 vm_offset_t bootprofile_buffer = 0;
846 uint32_t bootprofile_buffer_size = 0;
847 uint32_t bootprofile_buffer_current_position = 0;
848 uint32_t bootprofile_interval_ms = 0;
849 uint64_t bootprofile_interval_abs = 0;
850 uint64_t bootprofile_next_deadline = 0;
851 uint32_t bootprofile_all_procs = 0;
852 char bootprofile_proc_name[17];
853
854 lck_grp_t bootprofile_lck_grp;
855 lck_mtx_t bootprofile_mtx;
856
857 static timer_call_data_t bootprofile_timer_call_entry;
858
859 #define BOOTPROFILE_LOCK() do { lck_mtx_lock(&bootprofile_mtx); } while(0)
860 #define BOOTPROFILE_TRY_SPIN_LOCK() lck_mtx_try_lock_spin(&bootprofile_mtx)
861 #define BOOTPROFILE_UNLOCK() do { lck_mtx_unlock(&bootprofile_mtx); } while(0)
862
863 static void bootprofile_timer_call(
864 timer_call_param_t param0,
865 timer_call_param_t param1);
866
867 extern int
868 stack_snapshot_from_kernel(int pid, void *buf, uint32_t size, uint32_t flags, unsigned *retbytes);
869
870 void bootprofile_init(void)
871 {
872 kern_return_t ret;
873
874 lck_grp_init(&bootprofile_lck_grp, "bootprofile group", LCK_GRP_ATTR_NULL);
875 lck_mtx_init(&bootprofile_mtx, &bootprofile_lck_grp, LCK_ATTR_NULL);
876
877 if (!PE_parse_boot_argn("bootprofile_buffer_size", &bootprofile_buffer_size, sizeof(bootprofile_buffer_size))) {
878 bootprofile_buffer_size = 0;
879 }
880
881 if (bootprofile_buffer_size > BOOTPROFILE_MAX_BUFFER_SIZE)
882 bootprofile_buffer_size = BOOTPROFILE_MAX_BUFFER_SIZE;
883
884 if (!PE_parse_boot_argn("bootprofile_interval_ms", &bootprofile_interval_ms, sizeof(bootprofile_interval_ms))) {
885 bootprofile_interval_ms = 0;
886 }
887
888 if (!PE_parse_boot_argn("bootprofile_proc_name", &bootprofile_proc_name, sizeof(bootprofile_proc_name))) {
889 bootprofile_all_procs = 1;
890 bootprofile_proc_name[0] = '\0';
891 }
892
893 clock_interval_to_absolutetime_interval(bootprofile_interval_ms, NSEC_PER_MSEC, &bootprofile_interval_abs);
894
895 /* Both boot args must be set to enable */
896 if ((bootprofile_buffer_size == 0) || (bootprofile_interval_abs == 0)) {
897 return;
898 }
899
900 ret = kmem_alloc(kernel_map, &bootprofile_buffer, bootprofile_buffer_size);
901 if (ret != KERN_SUCCESS) {
902 kprintf("Boot profile: Allocation failed: %d\n", ret);
903 return;
904 }
905
906 kprintf("Boot profile: Sampling %s once per %u ms\n", bootprofile_all_procs ? "all procs" : bootprofile_proc_name, bootprofile_interval_ms);
907
908 timer_call_setup(&bootprofile_timer_call_entry,
909 bootprofile_timer_call,
910 NULL);
911
912 bootprofile_next_deadline = mach_absolute_time() + bootprofile_interval_abs;
913 timer_call_enter_with_leeway(&bootprofile_timer_call_entry,
914 NULL,
915 bootprofile_next_deadline,
916 0,
917 TIMER_CALL_SYS_NORMAL,
918 FALSE);
919 }
920
921 static void bootprofile_timer_call(
922 timer_call_param_t param0 __unused,
923 timer_call_param_t param1 __unused)
924 {
925 unsigned retbytes = 0;
926 int pid_to_profile = -1;
927
928 if (!BOOTPROFILE_TRY_SPIN_LOCK()) {
929 goto reprogram;
930 }
931
932 /* Check if process-specific boot profiling is turned on */
933 if (!bootprofile_all_procs) {
934 /*
935 * Since boot profiling initializes really early in boot, it is
936 * possible that at this point, the task/proc is not initialized.
937 * Nothing to do in that case.
938 */
939
940 if ((current_task() != NULL) && (current_task()->bsd_info != NULL) &&
941 (0 == strncmp(bootprofile_proc_name, proc_name_address(current_task()->bsd_info), 17))) {
942 pid_to_profile = proc_selfpid();
943 }
944 else {
945 /*
946 * Process-specific boot profiling requested but the on-core process is
947 * something else. Nothing to do here.
948 */
949 BOOTPROFILE_UNLOCK();
950 goto reprogram;
951 }
952 }
953
954 /* initiate a stackshot with whatever portion of the buffer is left */
955 if (bootprofile_buffer_current_position < bootprofile_buffer_size) {
956 stack_snapshot_from_kernel(
957 pid_to_profile,
958 (void *)(bootprofile_buffer + bootprofile_buffer_current_position),
959 bootprofile_buffer_size - bootprofile_buffer_current_position,
960 STACKSHOT_SAVE_LOADINFO | STACKSHOT_SAVE_KEXT_LOADINFO | STACKSHOT_GET_GLOBAL_MEM_STATS,
961 &retbytes
962 );
963
964 bootprofile_buffer_current_position += retbytes;
965 }
966
967 BOOTPROFILE_UNLOCK();
968
969 /* If we didn't get any data or have run out of buffer space, stop profiling */
970 if ((retbytes == 0) || (bootprofile_buffer_current_position == bootprofile_buffer_size)) {
971 return;
972 }
973
974
975 reprogram:
976 /* If the user gathered the buffer, no need to keep profiling */
977 if (bootprofile_interval_abs == 0) {
978 return;
979 }
980
981 clock_deadline_for_periodic_event(bootprofile_interval_abs,
982 mach_absolute_time(),
983 &bootprofile_next_deadline);
984 timer_call_enter_with_leeway(&bootprofile_timer_call_entry,
985 NULL,
986 bootprofile_next_deadline,
987 0,
988 TIMER_CALL_SYS_NORMAL,
989 FALSE);
990 }
991
992 int bootprofile_gather(user_addr_t buffer, uint32_t *length)
993 {
994 int result = 0;
995
996 BOOTPROFILE_LOCK();
997
998 if (bootprofile_buffer == 0) {
999 *length = 0;
1000 goto out;
1001 }
1002
1003 if (*length < bootprofile_buffer_current_position) {
1004 result = KERN_NO_SPACE;
1005 goto out;
1006 }
1007
1008 if ((result = copyout((void *)bootprofile_buffer, buffer,
1009 bootprofile_buffer_current_position)) != 0) {
1010 *length = 0;
1011 goto out;
1012 }
1013 *length = bootprofile_buffer_current_position;
1014
1015 /* cancel future timers */
1016 bootprofile_interval_abs = 0;
1017
1018 out:
1019
1020 BOOTPROFILE_UNLOCK();
1021
1022 return (result);
1023 }