xnu-2422.100.13.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 if (task->effective_policy.darwinbg == 1) {
532 tsnap->ss_flags |= kTaskDarwinBG;
533 }
534
535 proc_get_darwinbgstate(task, &tmp);
536
537 if (task->requested_policy.t_role == TASK_FOREGROUND_APPLICATION) {
538 tsnap->ss_flags |= kTaskIsForeground;
539 }
540
541 if (tmp & PROC_FLAG_ADAPTIVE_IMPORTANT) {
542 tsnap->ss_flags |= kTaskIsBoosted;
543 }
544
545 if (tmp & PROC_FLAG_SUPPRESSED) {
546 tsnap->ss_flags |= kTaskIsSuppressed;
547 }
548
549 tsnap->latency_qos = task_grab_latency_qos(task);
550
551 strlcpy(tsnap->p_comm, proc_name_address(p), sizeof(tsnap->p_comm));
552 if (task_has_64BitAddr(thread->task)) {
553 tsnap->ss_flags |= kUser64_p;
554 }
555
556 if (shared_cache_uuid_valid) {
557 tsnap->shared_cache_slide = shared_cache_slide;
558 bcopy(shared_cache_header.uuid, tsnap->shared_cache_identifier, sizeof (shared_cache_header.uuid));
559 }
560
561 telemetry_buffer_current_position += sizeof(struct task_snapshot);
562
563 /*
564 * Directly after the task snapshot, place the array of UUID's corresponding to the binaries
565 * used by this task.
566 */
567 if ((telemetry_buffer_size - telemetry_buffer_current_position) < uuid_info_array_size) {
568 telemetry_buffer_end_point = current_record_start;
569 telemetry_buffer_current_position = 0;
570 goto copytobuffer;
571 }
572
573 /*
574 * Copy the UUID info array into our sample.
575 */
576 if (uuid_info_array_size > 0) {
577 bcopy(uuid_info_array, (char *)(telemetry_buffer + telemetry_buffer_current_position), uuid_info_array_size);
578 tsnap->nloadinfos = uuid_info_count;
579 }
580
581 telemetry_buffer_current_position += uuid_info_array_size;
582
583 /*
584 * After the task snapshot & list of binary UUIDs, we place a thread snapshot.
585 */
586
587 if ((telemetry_buffer_size - telemetry_buffer_current_position) < sizeof(struct thread_snapshot)) {
588 /* wrap and overwrite */
589 telemetry_buffer_end_point = current_record_start;
590 telemetry_buffer_current_position = 0;
591 goto copytobuffer;
592 }
593
594 thsnap = (struct thread_snapshot *)(uintptr_t)(telemetry_buffer + telemetry_buffer_current_position);
595 bzero(thsnap, sizeof(*thsnap));
596
597 thsnap->snapshot_magic = STACKSHOT_THREAD_SNAPSHOT_MAGIC;
598 thsnap->thread_id = thread_tid(thread);
599 thsnap->state = thread->state;
600 thsnap->priority = thread->priority;
601 thsnap->sched_pri = thread->sched_pri;
602 thsnap->sched_flags = thread->sched_flags;
603 thsnap->ss_flags |= kStacksPCOnly;
604
605 if (thread->effective_policy.darwinbg) {
606 thsnap->ss_flags |= kThreadDarwinBG;
607 }
608
609 thsnap->user_time = timer_grab(&thread->user_timer);
610
611 uint64_t tval = timer_grab(&thread->system_timer);
612
613 if (thread->precise_user_kernel_time) {
614 thsnap->system_time = tval;
615 } else {
616 thsnap->user_time += tval;
617 thsnap->system_time = 0;
618 }
619
620 telemetry_buffer_current_position += sizeof(struct thread_snapshot);
621
622 /*
623 * If this thread has a dispatch queue serial number, include it here.
624 */
625 if (dqserialnum_valid) {
626 if ((telemetry_buffer_size - telemetry_buffer_current_position) < sizeof(dqserialnum)) {
627 /* wrap and overwrite */
628 telemetry_buffer_end_point = current_record_start;
629 telemetry_buffer_current_position = 0;
630 goto copytobuffer;
631 }
632
633 thsnap->ss_flags |= kHasDispatchSerial;
634 bcopy(&dqserialnum, (char *)telemetry_buffer + telemetry_buffer_current_position, sizeof (dqserialnum));
635 telemetry_buffer_current_position += sizeof (dqserialnum);
636 }
637
638 if (task_has_64BitAddr(task)) {
639 framesize = 8;
640 thsnap->ss_flags |= kUser64_p;
641 } else {
642 framesize = 4;
643 }
644
645 btcount = cs.nframes;
646
647 /*
648 * If we can't fit this entire stacktrace then cancel this record, wrap to the beginning,
649 * and start again there so that we always store a full record.
650 */
651 if ((telemetry_buffer_size - telemetry_buffer_current_position)/framesize < btcount) {
652 telemetry_buffer_end_point = current_record_start;
653 telemetry_buffer_current_position = 0;
654 goto copytobuffer;
655 }
656
657 for (bti=0; bti < btcount; bti++, telemetry_buffer_current_position += framesize) {
658 if (framesize == 8) {
659 *(uint64_t *)(uintptr_t)(telemetry_buffer + telemetry_buffer_current_position) = cs.frames[bti];
660 } else {
661 *(uint32_t *)(uintptr_t)(telemetry_buffer + telemetry_buffer_current_position) = (uint32_t)cs.frames[bti];
662 }
663 }
664
665 if (telemetry_buffer_end_point < telemetry_buffer_current_position) {
666 /*
667 * Each time the cursor wraps around to the beginning, we leave a
668 * differing amount of unused space at the end of the buffer. Make
669 * sure the cursor pushes the end point in case we're making use of
670 * more of the buffer than we did the last time we wrapped.
671 */
672 telemetry_buffer_end_point = telemetry_buffer_current_position;
673 }
674
675 thsnap->nuser_frames = btcount;
676
677 telemetry_bytes_since_last_mark += (telemetry_buffer_current_position - current_record_start);
678 if (telemetry_bytes_since_last_mark > telemetry_buffer_notify_at) {
679 notify = TRUE;
680 }
681
682 TELEMETRY_UNLOCK();
683
684 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);
685
686 if (notify) {
687 telemetry_notify_user();
688 }
689
690 if (uuid_info_array != NULL) {
691 kfree(uuid_info_array, uuid_info_array_size);
692 }
693 }
694
695 #if TELEMETRY_DEBUG
696 static void
697 log_telemetry_output(vm_offset_t buf, uint32_t pos, uint32_t sz)
698 {
699 struct micro_snapshot *p;
700 uint32_t offset;
701
702 printf("Copying out %d bytes of telemetry at offset %d\n", sz, pos);
703
704 buf += pos;
705
706 /*
707 * Find and log each timestamp in this chunk of buffer.
708 */
709 for (offset = 0; offset < sz; offset++) {
710 p = (struct micro_snapshot *)(buf + offset);
711 if (p->snapshot_magic == STACKSHOT_MICRO_SNAPSHOT_MAGIC) {
712 printf("telemetry timestamp: %lld\n", p->ms_time);
713 }
714 }
715 }
716 #endif
717
718 int telemetry_gather(user_addr_t buffer, uint32_t *length, boolean_t mark)
719 {
720 int result = 0;
721 uint32_t oldest_record_offset;
722
723 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_STACKSHOT, MICROSTACKSHOT_GATHER) | DBG_FUNC_START, mark, telemetry_bytes_since_last_mark, 0, 0, 0);
724
725 TELEMETRY_LOCK();
726
727 if (telemetry_buffer == 0) {
728 *length = 0;
729 goto out;
730 }
731
732 if (*length < telemetry_buffer_size) {
733 result = KERN_NO_SPACE;
734 goto out;
735 }
736
737 /*
738 * Copy the ring buffer out to userland in order sorted by time: least recent to most recent.
739 * First, we need to search forward from the cursor to find the oldest record in our buffer.
740 */
741 oldest_record_offset = telemetry_buffer_current_position;
742 do {
743 if ((oldest_record_offset == telemetry_buffer_size) ||
744 (oldest_record_offset == telemetry_buffer_end_point)) {
745
746 if (*(uint32_t *)(uintptr_t)(telemetry_buffer) == 0) {
747 /*
748 * There is no magic number at the start of the buffer, which means
749 * it's empty; nothing to see here yet.
750 */
751 *length = 0;
752 goto out;
753 }
754 /*
755 * We've looked through the end of the active buffer without finding a valid
756 * record; that means all valid records are in a single chunk, beginning at
757 * the very start of the buffer.
758 */
759
760 oldest_record_offset = 0;
761 assert(*(uint32_t *)(uintptr_t)(telemetry_buffer) == STACKSHOT_MICRO_SNAPSHOT_MAGIC);
762 break;
763 }
764
765 if (*(uint32_t *)(uintptr_t)(telemetry_buffer + oldest_record_offset) == STACKSHOT_MICRO_SNAPSHOT_MAGIC)
766 break;
767
768 /*
769 * There are no alignment guarantees for micro-stackshot records, so we must search at each
770 * byte offset.
771 */
772 oldest_record_offset++;
773 } while (oldest_record_offset != telemetry_buffer_current_position);
774
775 /*
776 * If needed, copyout in two chunks: from the oldest record to the end of the buffer, and then
777 * from the beginning of the buffer up to the current position.
778 */
779 if (oldest_record_offset != 0) {
780 #if TELEMETRY_DEBUG
781 log_telemetry_output(telemetry_buffer, oldest_record_offset,
782 telemetry_buffer_end_point - oldest_record_offset);
783 #endif
784 if ((result = copyout((void *)(telemetry_buffer + oldest_record_offset), buffer,
785 telemetry_buffer_end_point - oldest_record_offset)) != 0) {
786 *length = 0;
787 goto out;
788 }
789 *length = telemetry_buffer_end_point - oldest_record_offset;
790 } else {
791 *length = 0;
792 }
793
794 #if TELEMETRY_DEBUG
795 log_telemetry_output(telemetry_buffer, 0, telemetry_buffer_current_position);
796 #endif
797 if ((result = copyout((void *)telemetry_buffer, buffer + *length,
798 telemetry_buffer_current_position)) != 0) {
799 *length = 0;
800 goto out;
801 }
802 *length += (uint32_t)telemetry_buffer_current_position;
803
804 out:
805
806 if (mark && (*length > 0)) {
807 telemetry_bytes_since_last_mark = 0;
808 }
809
810 TELEMETRY_UNLOCK();
811
812 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_STACKSHOT, MICROSTACKSHOT_GATHER) | DBG_FUNC_END, telemetry_buffer_current_position, *length, telemetry_buffer_end_point, 0, 0);
813
814 return (result);
815 }
816
817 /************************/
818 /* BOOT PROFILE SUPPORT */
819 /************************/
820 /*
821 * Boot Profiling
822 *
823 * The boot-profiling support is a mechanism to sample activity happening on the
824 * system during boot. This mechanism sets up a periodic timer and on every timer fire,
825 * captures a full backtrace into the boot profiling buffer. This buffer can be pulled
826 * out and analyzed from user-space. It is turned on using the following boot-args:
827 * "bootprofile_buffer_size" specifies the size of the boot profile buffer
828 * "bootprofile_interval_ms" specifies the interval for the profiling timer
829 *
830 * Process Specific Boot Profiling
831 *
832 * The boot-arg "bootprofile_proc_name" can be used to specify a certain
833 * process that needs to profiled during boot. Setting this boot-arg changes
834 * the way stackshots are captured. At every timer fire, the code looks at the
835 * currently running process and takes a stackshot only if the requested process
836 * is on-core (which makes it unsuitable for MP systems).
837 *
838 */
839
840 #define BOOTPROFILE_MAX_BUFFER_SIZE (64*1024*1024) /* see also COPYSIZELIMIT_PANIC */
841
842 vm_offset_t bootprofile_buffer = 0;
843 uint32_t bootprofile_buffer_size = 0;
844 uint32_t bootprofile_buffer_current_position = 0;
845 uint32_t bootprofile_interval_ms = 0;
846 uint64_t bootprofile_interval_abs = 0;
847 uint64_t bootprofile_next_deadline = 0;
848 uint32_t bootprofile_all_procs = 0;
849 char bootprofile_proc_name[17];
850
851 lck_grp_t bootprofile_lck_grp;
852 lck_mtx_t bootprofile_mtx;
853
854 static timer_call_data_t bootprofile_timer_call_entry;
855
856 #define BOOTPROFILE_LOCK() do { lck_mtx_lock(&bootprofile_mtx); } while(0)
857 #define BOOTPROFILE_TRY_SPIN_LOCK() lck_mtx_try_lock_spin(&bootprofile_mtx)
858 #define BOOTPROFILE_UNLOCK() do { lck_mtx_unlock(&bootprofile_mtx); } while(0)
859
860 static void bootprofile_timer_call(
861 timer_call_param_t param0,
862 timer_call_param_t param1);
863
864 extern int
865 stack_snapshot_from_kernel(int pid, void *buf, uint32_t size, uint32_t flags, unsigned *retbytes);
866
867 void bootprofile_init(void)
868 {
869 kern_return_t ret;
870
871 lck_grp_init(&bootprofile_lck_grp, "bootprofile group", LCK_GRP_ATTR_NULL);
872 lck_mtx_init(&bootprofile_mtx, &bootprofile_lck_grp, LCK_ATTR_NULL);
873
874 if (!PE_parse_boot_argn("bootprofile_buffer_size", &bootprofile_buffer_size, sizeof(bootprofile_buffer_size))) {
875 bootprofile_buffer_size = 0;
876 }
877
878 if (bootprofile_buffer_size > BOOTPROFILE_MAX_BUFFER_SIZE)
879 bootprofile_buffer_size = BOOTPROFILE_MAX_BUFFER_SIZE;
880
881 if (!PE_parse_boot_argn("bootprofile_interval_ms", &bootprofile_interval_ms, sizeof(bootprofile_interval_ms))) {
882 bootprofile_interval_ms = 0;
883 }
884
885 if (!PE_parse_boot_argn("bootprofile_proc_name", &bootprofile_proc_name, sizeof(bootprofile_proc_name))) {
886 bootprofile_all_procs = 1;
887 bootprofile_proc_name[0] = '\0';
888 }
889
890 clock_interval_to_absolutetime_interval(bootprofile_interval_ms, NSEC_PER_MSEC, &bootprofile_interval_abs);
891
892 /* Both boot args must be set to enable */
893 if ((bootprofile_buffer_size == 0) || (bootprofile_interval_abs == 0)) {
894 return;
895 }
896
897 ret = kmem_alloc(kernel_map, &bootprofile_buffer, bootprofile_buffer_size);
898 if (ret != KERN_SUCCESS) {
899 kprintf("Boot profile: Allocation failed: %d\n", ret);
900 return;
901 }
902
903 kprintf("Boot profile: Sampling %s once per %u ms\n", bootprofile_all_procs ? "all procs" : bootprofile_proc_name, bootprofile_interval_ms);
904
905 timer_call_setup(&bootprofile_timer_call_entry,
906 bootprofile_timer_call,
907 NULL);
908
909 bootprofile_next_deadline = mach_absolute_time() + bootprofile_interval_abs;
910 timer_call_enter_with_leeway(&bootprofile_timer_call_entry,
911 NULL,
912 bootprofile_next_deadline,
913 0,
914 TIMER_CALL_SYS_NORMAL,
915 FALSE);
916 }
917
918 static void bootprofile_timer_call(
919 timer_call_param_t param0 __unused,
920 timer_call_param_t param1 __unused)
921 {
922 unsigned retbytes = 0;
923 int pid_to_profile = -1;
924
925 if (!BOOTPROFILE_TRY_SPIN_LOCK()) {
926 goto reprogram;
927 }
928
929 /* Check if process-specific boot profiling is turned on */
930 if (!bootprofile_all_procs) {
931 /*
932 * Since boot profiling initializes really early in boot, it is
933 * possible that at this point, the task/proc is not initialized.
934 * Nothing to do in that case.
935 */
936
937 if ((current_task() != NULL) && (current_task()->bsd_info != NULL) &&
938 (0 == strncmp(bootprofile_proc_name, proc_name_address(current_task()->bsd_info), 17))) {
939 pid_to_profile = proc_selfpid();
940 }
941 else {
942 /*
943 * Process-specific boot profiling requested but the on-core process is
944 * something else. Nothing to do here.
945 */
946 BOOTPROFILE_UNLOCK();
947 goto reprogram;
948 }
949 }
950
951 /* initiate a stackshot with whatever portion of the buffer is left */
952 if (bootprofile_buffer_current_position < bootprofile_buffer_size) {
953 stack_snapshot_from_kernel(
954 pid_to_profile,
955 (void *)(bootprofile_buffer + bootprofile_buffer_current_position),
956 bootprofile_buffer_size - bootprofile_buffer_current_position,
957 STACKSHOT_SAVE_LOADINFO | STACKSHOT_SAVE_KEXT_LOADINFO | STACKSHOT_GET_GLOBAL_MEM_STATS,
958 &retbytes
959 );
960
961 bootprofile_buffer_current_position += retbytes;
962 }
963
964 BOOTPROFILE_UNLOCK();
965
966 /* If we didn't get any data or have run out of buffer space, stop profiling */
967 if ((retbytes == 0) || (bootprofile_buffer_current_position == bootprofile_buffer_size)) {
968 return;
969 }
970
971
972 reprogram:
973 /* If the user gathered the buffer, no need to keep profiling */
974 if (bootprofile_interval_abs == 0) {
975 return;
976 }
977
978 clock_deadline_for_periodic_event(bootprofile_interval_abs,
979 mach_absolute_time(),
980 &bootprofile_next_deadline);
981 timer_call_enter_with_leeway(&bootprofile_timer_call_entry,
982 NULL,
983 bootprofile_next_deadline,
984 0,
985 TIMER_CALL_SYS_NORMAL,
986 FALSE);
987 }
988
989 int bootprofile_gather(user_addr_t buffer, uint32_t *length)
990 {
991 int result = 0;
992
993 BOOTPROFILE_LOCK();
994
995 if (bootprofile_buffer == 0) {
996 *length = 0;
997 goto out;
998 }
999
1000 if (*length < bootprofile_buffer_current_position) {
1001 result = KERN_NO_SPACE;
1002 goto out;
1003 }
1004
1005 if ((result = copyout((void *)bootprofile_buffer, buffer,
1006 bootprofile_buffer_current_position)) != 0) {
1007 *length = 0;
1008 goto out;
1009 }
1010 *length = bootprofile_buffer_current_position;
1011
1012 /* cancel future timers */
1013 bootprofile_interval_abs = 0;
1014
1015 out:
1016
1017 BOOTPROFILE_UNLOCK();
1018
1019 return (result);
1020 }