1 /*
2 * Copyright (c) 2000-2021 Apple Inc. All rights reserved.
3 *
4 * @Apple_LICENSE_HEADER_START@
5 *
6 * The contents of this file constitute Original Code as defined in and
7 * are subject to the Apple Public Source License Version 1.1 (the
8 * "License"). You may not use this file except in compliance with the
9 * License. Please obtain a copy of the License at
10 * http://www.apple.com/publicsource and read it before using this file.
11 *
12 * This Original Code and all software distributed under the License are
13 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
17 * License for the specific language governing rights and limitations
18 * under the License.
19 *
20 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
21 */
22
23 #include <sys/errno.h>
24 #include <sys/kdebug_private.h>
25 #include <sys/proc_internal.h>
26 #include <sys/vm.h>
27 #include <sys/sysctl.h>
28 #include <sys/kdebug_common.h>
29 #include <sys/kdebug.h>
30 #include <sys/kdebug_triage.h>
31 #include <sys/kauth.h>
32 #include <sys/ktrace.h>
33 #include <sys/sysproto.h>
34 #include <sys/bsdtask_info.h>
35 #include <sys/random.h>
36
37 #include <mach/mach_vm.h>
38 #include <machine/atomic.h>
39
40 #include <mach/machine.h>
41 #include <mach/vm_map.h>
42 #include <kern/clock.h>
43
44 #include <kern/task.h>
45 #include <kern/debug.h>
46 #include <kern/kalloc.h>
47 #include <kern/telemetry.h>
48 #include <kern/sched_prim.h>
49 #include <sys/lock.h>
50 #include <pexpert/device_tree.h>
51
52 #include <sys/malloc.h>
53
54 #include <sys/vnode.h>
55 #include <sys/vnode_internal.h>
56 #include <sys/fcntl.h>
57 #include <sys/file_internal.h>
58 #include <sys/ubc.h>
59 #include <sys/param.h> /* for isset() */
60
61 #include <vm/vm_kern_xnu.h>
62 #include <vm/vm_map_xnu.h>
63
64 #include <libkern/OSAtomic.h>
65
66 #include <machine/pal_routines.h>
67 #include <machine/atomic.h>
68
69
70 extern unsigned int wake_nkdbufs;
71 extern unsigned int trace_wrap;
72
73 // Coprocessors (or "IOP"s)
74 //
75 // Coprocessors are auxiliary cores that want to participate in kdebug event
76 // logging. They are registered dynamically, as devices match hardware, and are
77 // each assigned an ID at registration.
78 //
79 // Once registered, a coprocessor is permanent; it cannot be unregistered.
80 // The current implementation depends on this for thread safety.
81 //
82 // The `kd_coprocs` list may be safely walked at any time, without holding
83 // locks.
84 //
85 // When starting a trace session, the current `kd_coprocs` head is captured. Any
86 // operations that depend on the buffer state (such as flushing IOP traces on
87 // reads, etc.) should use the captured list head. This will allow registrations
88 // to take place while trace is in use, though their events will be rejected
89 // until the next time a trace session is started.
90
91 struct kd_coproc {
92 char full_name[32];
93 kdebug_coproc_flags_t flags;
94 kd_callback_t callback;
95 uint32_t cpu_id;
96 struct kd_coproc *next;
97 struct mpsc_queue_chain chain;
98 };
99
100 static struct kd_coproc *kd_coprocs = NULL;
101
102 // Use an MPSC queue to notify coprocessors of the current trace state during
103 // registration, if space is available for them in the current trace session.
104 static struct mpsc_daemon_queue _coproc_notify_queue;
105
106 // Typefilter(s)
107 //
108 // A typefilter is a 8KB bitmap that is used to selectively filter events
109 // being recorded. It is able to individually address every class & subclass.
110 //
111 // There is a shared typefilter in the kernel which is lazily allocated. Once
112 // allocated, the shared typefilter is never deallocated. The shared typefilter
113 // is also mapped on demand into userspace processes that invoke kdebug_trace
114 // API from Libsyscall. When mapped into a userspace process, the memory is
115 // read only, and does not have a fixed address.
116 //
117 // It is a requirement that the kernel's shared typefilter always pass DBG_TRACE
118 // events. This is enforced automatically, by having the needed bits set any
119 // time the shared typefilter is mutated.
120
121 typedef uint8_t *typefilter_t;
122
123 static typefilter_t kdbg_typefilter;
124 static mach_port_t kdbg_typefilter_memory_entry;
125
126 /*
127 * There are 3 combinations of page sizes:
128 *
129 * 4KB / 4KB
130 * 4KB / 16KB
131 * 16KB / 16KB
132 *
133 * The typefilter is exactly 8KB. In the first two scenarios, we would like
134 * to use 2 pages exactly; in the third scenario we must make certain that
135 * a full page is allocated so we do not inadvertantly share 8KB of random
136 * data to userspace. The round_page_32 macro rounds to kernel page size.
137 */
138 #define TYPEFILTER_ALLOC_SIZE MAX(round_page_32(KDBG_TYPEFILTER_BITMAP_SIZE), KDBG_TYPEFILTER_BITMAP_SIZE)
139
140 static typefilter_t
typefilter_create(void)141 typefilter_create(void)
142 {
143 typefilter_t tf;
144 if (KERN_SUCCESS == kmem_alloc(kernel_map, (vm_offset_t*)&tf,
145 TYPEFILTER_ALLOC_SIZE, KMA_DATA | KMA_ZERO, VM_KERN_MEMORY_DIAG)) {
146 return tf;
147 }
148 return NULL;
149 }
150
151 static void
typefilter_deallocate(typefilter_t tf)152 typefilter_deallocate(typefilter_t tf)
153 {
154 assert(tf != NULL);
155 assert(tf != kdbg_typefilter);
156 kmem_free(kernel_map, (vm_offset_t)tf, TYPEFILTER_ALLOC_SIZE);
157 }
158
159 static void
typefilter_copy(typefilter_t dst,typefilter_t src)160 typefilter_copy(typefilter_t dst, typefilter_t src)
161 {
162 assert(src != NULL);
163 assert(dst != NULL);
164 memcpy(dst, src, KDBG_TYPEFILTER_BITMAP_SIZE);
165 }
166
167 static void
typefilter_reject_all(typefilter_t tf)168 typefilter_reject_all(typefilter_t tf)
169 {
170 assert(tf != NULL);
171 memset(tf, 0, KDBG_TYPEFILTER_BITMAP_SIZE);
172 }
173
174 static void
typefilter_allow_all(typefilter_t tf)175 typefilter_allow_all(typefilter_t tf)
176 {
177 assert(tf != NULL);
178 memset(tf, ~0, KDBG_TYPEFILTER_BITMAP_SIZE);
179 }
180
181 static void
typefilter_allow_class(typefilter_t tf,uint8_t class)182 typefilter_allow_class(typefilter_t tf, uint8_t class)
183 {
184 assert(tf != NULL);
185 const uint32_t BYTES_PER_CLASS = 256 / 8; // 256 subclasses, 1 bit each
186 memset(&tf[class * BYTES_PER_CLASS], 0xFF, BYTES_PER_CLASS);
187 }
188
189 static void
typefilter_allow_csc(typefilter_t tf,uint16_t csc)190 typefilter_allow_csc(typefilter_t tf, uint16_t csc)
191 {
192 assert(tf != NULL);
193 setbit(tf, csc);
194 }
195
196 static bool
typefilter_is_debugid_allowed(typefilter_t tf,uint32_t id)197 typefilter_is_debugid_allowed(typefilter_t tf, uint32_t id)
198 {
199 assert(tf != NULL);
200 return isset(tf, KDBG_EXTRACT_CSC(id));
201 }
202
203 static mach_port_t
typefilter_create_memory_entry(typefilter_t tf)204 typefilter_create_memory_entry(typefilter_t tf)
205 {
206 assert(tf != NULL);
207
208 mach_port_t memory_entry = MACH_PORT_NULL;
209 memory_object_size_t size = TYPEFILTER_ALLOC_SIZE;
210
211 kern_return_t kr = mach_make_memory_entry_64(kernel_map,
212 &size,
213 (memory_object_offset_t)tf,
214 VM_PROT_READ,
215 &memory_entry,
216 MACH_PORT_NULL);
217 if (kr != KERN_SUCCESS) {
218 return MACH_PORT_NULL;
219 }
220
221 return memory_entry;
222 }
223
224 static int kdbg_copyin_typefilter(user_addr_t addr, size_t size);
225 static void kdbg_enable_typefilter(void);
226 static void kdbg_disable_typefilter(void);
227
228 // External prototypes
229
230 void commpage_update_kdebug_state(void);
231
232 static int kdbg_readcurthrmap(user_addr_t, size_t *);
233 static int kdbg_setpidex(kd_regtype *);
234 static int kdbg_setpid(kd_regtype *);
235 static int kdbg_reinit(unsigned int extra_cpus);
236 #if DEVELOPMENT || DEBUG
237 static int kdbg_test(size_t flavor);
238 #endif /* DEVELOPMENT || DEBUG */
239
240 static int _write_legacy_header(bool write_thread_map, vnode_t vp,
241 vfs_context_t ctx);
242 static int kdbg_write_thread_map(vnode_t vp, vfs_context_t ctx);
243 static int kdbg_copyout_thread_map(user_addr_t buffer, size_t *buffer_size);
244 static void _clear_thread_map(void);
245
246 static bool kdbg_wait(uint64_t timeout_ms);
247 static void kdbg_wakeup(void);
248
249 static int _copy_cpu_map(int version, void **dst, size_t *size);
250
251 static kd_threadmap *_thread_map_create_live(size_t max_count,
252 vm_size_t *map_size, vm_size_t *map_count);
253
254 static bool kdebug_current_proc_enabled(uint32_t debugid);
255 static errno_t kdebug_check_trace_string(uint32_t debugid, uint64_t str_id);
256
257 int kernel_debug_trace_write_to_file(user_addr_t *buffer, size_t *number,
258 size_t *count, size_t tempbuf_number, vnode_t vp, vfs_context_t ctx,
259 bool chunk);
260
261 extern void IOSleep(int);
262
263 unsigned int kdebug_enable = 0;
264
265 // A static buffer to record events prior to the start of regular logging.
266
267 #define KD_EARLY_BUFFER_SIZE (16 * 1024)
268 #define KD_EARLY_EVENT_COUNT (KD_EARLY_BUFFER_SIZE / sizeof(kd_buf))
269 #if defined(__x86_64__)
270 __attribute__((aligned(KD_EARLY_BUFFER_SIZE)))
271 static kd_buf kd_early_buffer[KD_EARLY_EVENT_COUNT];
272 #else /* defined(__x86_64__) */
273 // On ARM, the space for this is carved out by osfmk/arm/data.s -- clang
274 // has problems aligning to greater than 4K.
275 extern kd_buf kd_early_buffer[KD_EARLY_EVENT_COUNT];
276 #endif /* !defined(__x86_64__) */
277
278 static __security_const_late unsigned int kd_early_index = 0;
279 static __security_const_late bool kd_early_overflow = false;
280 static __security_const_late bool kd_early_done = false;
281
282 static bool kd_waiter = false;
283 static LCK_SPIN_DECLARE(kd_wait_lock, &kdebug_lck_grp);
284 // Synchronize access to coprocessor list for kdebug trace.
285 static LCK_SPIN_DECLARE(kd_coproc_spinlock, &kdebug_lck_grp);
286
287 #define TRACE_KDCOPYBUF_COUNT 8192
288 #define TRACE_KDCOPYBUF_SIZE (TRACE_KDCOPYBUF_COUNT * sizeof(kd_buf))
289
290 struct kd_control kd_control_trace = {
291 .kds_free_list = {.raw = KDS_PTR_NULL},
292 .enabled = 0,
293 .mode = KDEBUG_MODE_TRACE,
294 .kdebug_events_per_storage_unit = TRACE_EVENTS_PER_STORAGE_UNIT,
295 .kdebug_min_storage_units_per_cpu = TRACE_MIN_STORAGE_UNITS_PER_CPU,
296 .kdebug_kdcopybuf_count = TRACE_KDCOPYBUF_COUNT,
297 .kdebug_kdcopybuf_size = TRACE_KDCOPYBUF_SIZE,
298 .kdc_flags = 0,
299 .kdc_emit = KDEMIT_DISABLE,
300 .kdc_oldest_time = 0
301 };
302
303 struct kd_buffer kd_buffer_trace = {
304 .kdb_event_count = 0,
305 .kdb_storage_count = 0,
306 .kdb_storage_threshold = 0,
307 .kdb_region_count = 0,
308 .kdb_info = NULL,
309 .kd_bufs = NULL,
310 .kdcopybuf = NULL
311 };
312
313 unsigned int kdlog_beg = 0;
314 unsigned int kdlog_end = 0;
315 unsigned int kdlog_value1 = 0;
316 unsigned int kdlog_value2 = 0;
317 unsigned int kdlog_value3 = 0;
318 unsigned int kdlog_value4 = 0;
319
320 kd_threadmap *kd_mapptr = 0;
321 vm_size_t kd_mapsize = 0;
322 vm_size_t kd_mapcount = 0;
323
324 off_t RAW_file_offset = 0;
325 int RAW_file_written = 0;
326
327 /*
328 * A globally increasing counter for identifying strings in trace. Starts at
329 * 1 because 0 is a reserved return value.
330 */
331 __attribute__((aligned(MAX_CPU_CACHE_LINE_SIZE)))
332 static uint64_t g_curr_str_id = 1;
333
334 #define STR_ID_SIG_OFFSET (48)
335 #define STR_ID_MASK ((1ULL << STR_ID_SIG_OFFSET) - 1)
336 #define STR_ID_SIG_MASK (~STR_ID_MASK)
337
338 /*
339 * A bit pattern for identifying string IDs generated by
340 * kdebug_trace_string(2).
341 */
342 static uint64_t g_str_id_signature = (0x70acULL << STR_ID_SIG_OFFSET);
343
344 #define RAW_VERSION3 0x00001000
345
346 #define V3_RAW_EVENTS 0x00001e00
347
348 static void
_coproc_lock(void)349 _coproc_lock(void)
350 {
351 lck_spin_lock_grp(&kd_coproc_spinlock, &kdebug_lck_grp);
352 }
353
354 static void
_coproc_unlock(void)355 _coproc_unlock(void)
356 {
357 lck_spin_unlock(&kd_coproc_spinlock);
358 }
359
360 static void
_coproc_list_check(void)361 _coproc_list_check(void)
362 {
363 #if MACH_ASSERT
364 _coproc_lock();
365 struct kd_coproc *coproc = kd_control_trace.kdc_coprocs;
366 if (coproc) {
367 /* Is list sorted by cpu_id? */
368 struct kd_coproc* temp = coproc;
369 do {
370 assert(!temp->next || temp->next->cpu_id == temp->cpu_id - 1);
371 assert(temp->next || (temp->cpu_id == kdbg_cpu_count()));
372 } while ((temp = temp->next));
373
374 /* Does each entry have a function and a name? */
375 temp = coproc;
376 do {
377 assert(temp->callback.func);
378 assert(strlen(temp->callback.iop_name) < sizeof(temp->callback.iop_name));
379 } while ((temp = temp->next));
380 }
381 _coproc_unlock();
382 #endif // MACH_ASSERT
383 }
384
385 static void
_coproc_list_callback(kd_callback_type type,void * arg)386 _coproc_list_callback(kd_callback_type type, void *arg)
387 {
388 if (kd_control_trace.kdc_flags & KDBG_DISABLE_COPROCS) {
389 return;
390 }
391
392 _coproc_lock();
393 // Coprocessor list is only ever prepended to.
394 struct kd_coproc *head = kd_control_trace.kdc_coprocs;
395 _coproc_unlock();
396 while (head) {
397 head->callback.func(head->callback.context, type, arg);
398 head = head->next;
399 }
400 }
401
402 // Leave some extra space for coprocessors to register while tracing is active.
403 #define EXTRA_COPROC_COUNT (16)
404 // There are more coprocessors registering during boot tracing.
405 #define EXTRA_COPROC_COUNT_BOOT (32)
406
407 static kdebug_emit_filter_t
_trace_emit_filter(void)408 _trace_emit_filter(void)
409 {
410 if (!kdebug_enable) {
411 return KDEMIT_DISABLE;
412 } else if (kd_control_trace.kdc_flags & KDBG_TYPEFILTER_CHECK) {
413 return KDEMIT_TYPEFILTER;
414 } else if (kd_control_trace.kdc_flags & KDBG_RANGECHECK) {
415 return KDEMIT_RANGE;
416 } else if (kd_control_trace.kdc_flags & KDBG_VALCHECK) {
417 return KDEMIT_EXACT;
418 } else {
419 return KDEMIT_ALL;
420 }
421 }
422
423 static void
kdbg_set_tracing_enabled(bool enabled,uint32_t trace_type)424 kdbg_set_tracing_enabled(bool enabled, uint32_t trace_type)
425 {
426 // Drain any events from coprocessors before making the state change. On
427 // enabling, this removes any stale events from before tracing. On
428 // disabling, this saves any events up to the point tracing is disabled.
429 _coproc_list_callback(KD_CALLBACK_SYNC_FLUSH, NULL);
430
431 if (!enabled) {
432 // Give coprocessors a chance to log any events before tracing is
433 // disabled, outside the lock.
434 _coproc_list_callback(KD_CALLBACK_KDEBUG_DISABLED, NULL);
435 }
436
437 int intrs_en = kdebug_storage_lock(&kd_control_trace);
438 if (enabled) {
439 // The oldest valid time is now; reject past events from coprocessors.
440 kd_control_trace.kdc_oldest_time = kdebug_timestamp();
441 kdebug_enable |= trace_type;
442 kd_control_trace.kdc_emit = _trace_emit_filter();
443 kd_control_trace.enabled = 1;
444 commpage_update_kdebug_state();
445 } else {
446 kdebug_enable = 0;
447 kd_control_trace.kdc_emit = KDEMIT_DISABLE;
448 kd_control_trace.enabled = 0;
449 commpage_update_kdebug_state();
450 }
451 kdebug_storage_unlock(&kd_control_trace, intrs_en);
452
453 if (enabled) {
454 _coproc_list_callback(KD_CALLBACK_KDEBUG_ENABLED, NULL);
455 }
456 }
457
458 static int
create_buffers_trace(unsigned int extra_cpus)459 create_buffers_trace(unsigned int extra_cpus)
460 {
461 int events_per_storage_unit = kd_control_trace.kdebug_events_per_storage_unit;
462 int min_storage_units_per_cpu = kd_control_trace.kdebug_min_storage_units_per_cpu;
463
464 // For the duration of this allocation, trace code will only reference
465 // kdc_coprocs.
466 kd_control_trace.kdc_coprocs = kd_coprocs;
467 _coproc_list_check();
468
469 // If the list is valid, it is sorted from newest to oldest. Each entry is
470 // prepended, so the CPU IDs are sorted in descending order.
471 kd_control_trace.kdebug_cpus = kd_control_trace.kdc_coprocs ?
472 kd_control_trace.kdc_coprocs->cpu_id + 1 : kdbg_cpu_count();
473 kd_control_trace.alloc_cpus = kd_control_trace.kdebug_cpus + extra_cpus;
474
475 size_t min_event_count = kd_control_trace.alloc_cpus *
476 events_per_storage_unit * min_storage_units_per_cpu;
477 if (kd_buffer_trace.kdb_event_count < min_event_count) {
478 kd_buffer_trace.kdb_storage_count = kd_control_trace.alloc_cpus * min_storage_units_per_cpu;
479 } else {
480 kd_buffer_trace.kdb_storage_count = kd_buffer_trace.kdb_event_count / events_per_storage_unit;
481 }
482
483 kd_buffer_trace.kdb_event_count = kd_buffer_trace.kdb_storage_count * events_per_storage_unit;
484
485 kd_buffer_trace.kd_bufs = NULL;
486
487 int error = create_buffers(&kd_control_trace, &kd_buffer_trace,
488 VM_KERN_MEMORY_DIAG);
489 if (!error) {
490 struct kd_bufinfo *info = kd_buffer_trace.kdb_info;
491 struct kd_coproc *cur_iop = kd_control_trace.kdc_coprocs;
492 while (cur_iop != NULL) {
493 info[cur_iop->cpu_id].continuous_timestamps = ISSET(cur_iop->flags,
494 KDCP_CONTINUOUS_TIME);
495 cur_iop = cur_iop->next;
496 }
497 kd_buffer_trace.kdb_storage_threshold = kd_buffer_trace.kdb_storage_count / 2;
498 }
499
500 return error;
501 }
502
503 static void
delete_buffers_trace(void)504 delete_buffers_trace(void)
505 {
506 delete_buffers(&kd_control_trace, &kd_buffer_trace);
507 }
508
509 static int
_register_coproc_internal(const char * name,kdebug_coproc_flags_t flags,kd_callback_fn callback,void * context)510 _register_coproc_internal(const char *name, kdebug_coproc_flags_t flags,
511 kd_callback_fn callback, void *context)
512 {
513 struct kd_coproc *coproc = NULL;
514
515 coproc = zalloc_permanent_type(struct kd_coproc);
516 coproc->callback.func = callback;
517 coproc->callback.context = context;
518 coproc->flags = flags;
519 strlcpy(coproc->full_name, name, sizeof(coproc->full_name));
520
521 _coproc_lock();
522 coproc->next = kd_coprocs;
523 coproc->cpu_id = kd_coprocs == NULL ? kdbg_cpu_count() : kd_coprocs->cpu_id + 1;
524 kd_coprocs = coproc;
525 if (coproc->cpu_id < kd_control_trace.alloc_cpus) {
526 kd_control_trace.kdc_coprocs = kd_coprocs;
527 kd_control_trace.kdebug_cpus += 1;
528 if (kdebug_enable) {
529 mpsc_daemon_enqueue(&_coproc_notify_queue, &coproc->chain,
530 MPSC_QUEUE_NONE);
531 }
532 }
533 _coproc_unlock();
534
535 return coproc->cpu_id;
536 }
537
538 int
kernel_debug_register_callback(kd_callback_t callback)539 kernel_debug_register_callback(kd_callback_t callback)
540 {
541 // Be paranoid about using the provided name, but it's too late to reject
542 // it.
543 bool is_valid_name = false;
544 for (uint32_t length = 0; length < sizeof(callback.iop_name); ++length) {
545 if (callback.iop_name[length] > 0x20 && callback.iop_name[length] < 0x7F) {
546 continue;
547 }
548 if (callback.iop_name[length] == 0) {
549 if (length) {
550 is_valid_name = true;
551 }
552 break;
553 }
554 }
555 kd_callback_t sane_cb = callback;
556 if (!is_valid_name) {
557 strlcpy(sane_cb.iop_name, "IOP-???", sizeof(sane_cb.iop_name));
558 }
559
560 return _register_coproc_internal(sane_cb.iop_name, 0, sane_cb.func,
561 sane_cb.context);
562 }
563
564 int
kdebug_register_coproc(const char * name,kdebug_coproc_flags_t flags,kd_callback_fn callback,void * context)565 kdebug_register_coproc(const char *name, kdebug_coproc_flags_t flags,
566 kd_callback_fn callback, void *context)
567 {
568 size_t name_len = strlen(name);
569 if (!name || name_len == 0) {
570 panic("kdebug: invalid name for coprocessor: %p", name);
571 }
572 for (size_t i = 0; i < name_len; i++) {
573 if (name[i] <= 0x20 || name[i] >= 0x7F) {
574 panic("kdebug: invalid name for coprocessor: %s", name);
575 }
576 }
577 if (!callback) {
578 panic("kdebug: no callback for coprocessor `%s'", name);
579 }
580 return _register_coproc_internal(name, flags, callback, context);
581 }
582
583 static inline bool
_should_emit_debugid(kdebug_emit_filter_t emit,uint32_t debugid)584 _should_emit_debugid(kdebug_emit_filter_t emit, uint32_t debugid)
585 {
586 switch (emit) {
587 case KDEMIT_DISABLE:
588 return false;
589 case KDEMIT_TYPEFILTER:
590 return typefilter_is_debugid_allowed(kdbg_typefilter, debugid);
591 case KDEMIT_RANGE:
592 return debugid >= kdlog_beg && debugid <= kdlog_end;
593 case KDEMIT_EXACT:;
594 uint32_t eventid = debugid & KDBG_EVENTID_MASK;
595 return eventid == kdlog_value1 || eventid == kdlog_value2 ||
596 eventid == kdlog_value3 || eventid == kdlog_value4;
597 case KDEMIT_ALL:
598 return true;
599 }
600 }
601
602 static void
_try_wakeup_above_threshold(uint32_t debugid)603 _try_wakeup_above_threshold(uint32_t debugid)
604 {
605 bool over_threshold = kd_control_trace.kdc_storage_used >=
606 kd_buffer_trace.kdb_storage_threshold;
607 if (kd_waiter && over_threshold) {
608 // Wakeup any waiters if called from a safe context.
609
610 const uint32_t INTERRUPT_EVENT = 0x01050000;
611 const uint32_t VMFAULT_EVENT = 0x01300008;
612 const uint32_t BSD_SYSCALL_CSC = 0x040c0000;
613 const uint32_t MACH_SYSCALL_CSC = 0x010c0000;
614
615 uint32_t eventid = debugid & KDBG_EVENTID_MASK;
616 uint32_t csc = debugid & KDBG_CSC_MASK;
617
618 if (eventid == INTERRUPT_EVENT || eventid == VMFAULT_EVENT ||
619 csc == BSD_SYSCALL_CSC || csc == MACH_SYSCALL_CSC) {
620 kdbg_wakeup();
621 }
622 }
623 }
624
625 // Emit events from coprocessors.
626 void
kernel_debug_enter(uint32_t coreid,uint32_t debugid,uint64_t timestamp,uintptr_t arg1,uintptr_t arg2,uintptr_t arg3,uintptr_t arg4,uintptr_t threadid)627 kernel_debug_enter(
628 uint32_t coreid,
629 uint32_t debugid,
630 uint64_t timestamp,
631 uintptr_t arg1,
632 uintptr_t arg2,
633 uintptr_t arg3,
634 uintptr_t arg4,
635 uintptr_t threadid
636 )
637 {
638 if (kd_control_trace.kdc_flags & KDBG_DISABLE_COPROCS) {
639 return;
640 }
641 kdebug_emit_filter_t emit = kd_control_trace.kdc_emit;
642 if (!emit || !kdebug_enable) {
643 return;
644 }
645 if (!_should_emit_debugid(emit, debugid)) {
646 return;
647 }
648
649 struct kd_record kd_rec = {
650 .cpu = (int32_t)coreid,
651 .timestamp = (int64_t)timestamp,
652 .debugid = debugid,
653 .arg1 = arg1,
654 .arg2 = arg2,
655 .arg3 = arg3,
656 .arg4 = arg4,
657 .arg5 = threadid,
658 };
659 kernel_debug_write(&kd_control_trace, &kd_buffer_trace, kd_rec);
660 }
661
662 __pure2
663 static inline proc_t
kdebug_current_proc_unsafe(void)664 kdebug_current_proc_unsafe(void)
665 {
666 return get_thread_ro_unchecked(current_thread())->tro_proc;
667 }
668
669 // Return true iff the debug ID should be traced by the current process.
670 static inline bool
kdebug_debugid_procfilt_allowed(uint32_t debugid)671 kdebug_debugid_procfilt_allowed(uint32_t debugid)
672 {
673 uint32_t procfilt_flags = kd_control_trace.kdc_flags &
674 (KDBG_PIDCHECK | KDBG_PIDEXCLUDE);
675 if (!procfilt_flags) {
676 return true;
677 }
678
679 // DBG_TRACE and MACH_SCHED tracepoints ignore the process filter.
680 if ((debugid & KDBG_CSC_MASK) == MACHDBG_CODE(DBG_MACH_SCHED, 0) ||
681 (KDBG_EXTRACT_CLASS(debugid) == DBG_TRACE)) {
682 return true;
683 }
684
685 struct proc *curproc = kdebug_current_proc_unsafe();
686 // If the process is missing (early in boot), allow it.
687 if (!curproc) {
688 return true;
689 }
690
691 switch (procfilt_flags) {
692 case KDBG_PIDCHECK:
693 return curproc->p_kdebug;
694 case KDBG_PIDEXCLUDE:
695 return !curproc->p_kdebug;
696 default:
697 panic("kdebug: invalid procfilt flags %x", kd_control_trace.kdc_flags);
698 }
699 }
700
701 static void
kdebug_emit_internal(kdebug_emit_filter_t emit,uint32_t debugid,uintptr_t arg1,uintptr_t arg2,uintptr_t arg3,uintptr_t arg4,uintptr_t arg5,uint64_t flags)702 kdebug_emit_internal(kdebug_emit_filter_t emit,
703 uint32_t debugid,
704 uintptr_t arg1,
705 uintptr_t arg2,
706 uintptr_t arg3,
707 uintptr_t arg4,
708 uintptr_t arg5,
709 uint64_t flags)
710 {
711 bool only_filter = flags & KDBG_FLAG_FILTERED;
712 bool observe_procfilt = !(flags & KDBG_FLAG_NOPROCFILT);
713
714 if (!_should_emit_debugid(emit, debugid)) {
715 return;
716 }
717 if (emit == KDEMIT_ALL && only_filter) {
718 return;
719 }
720 if (!ml_at_interrupt_context() && observe_procfilt &&
721 !kdebug_debugid_procfilt_allowed(debugid)) {
722 return;
723 }
724
725 struct kd_record kd_rec = {
726 .cpu = -1,
727 .timestamp = -1,
728 .debugid = debugid,
729 .arg1 = arg1,
730 .arg2 = arg2,
731 .arg3 = arg3,
732 .arg4 = arg4,
733 .arg5 = arg5,
734 };
735 kernel_debug_write(&kd_control_trace, &kd_buffer_trace, kd_rec);
736
737 #if KPERF
738 kperf_kdebug_callback(kd_rec.debugid, __builtin_frame_address(0));
739 #endif // KPERF
740 }
741
742 static void
kernel_debug_internal(uint32_t debugid,uintptr_t arg1,uintptr_t arg2,uintptr_t arg3,uintptr_t arg4,uintptr_t arg5,uint64_t flags)743 kernel_debug_internal(
744 uint32_t debugid,
745 uintptr_t arg1,
746 uintptr_t arg2,
747 uintptr_t arg3,
748 uintptr_t arg4,
749 uintptr_t arg5,
750 uint64_t flags)
751 {
752 kdebug_emit_filter_t emit = kd_control_trace.kdc_emit;
753 if (!emit || !kdebug_enable) {
754 return;
755 }
756 kdebug_emit_internal(emit, debugid, arg1, arg2, arg3, arg4, arg5, flags);
757 _try_wakeup_above_threshold(debugid);
758 }
759
760 __attribute__((noinline))
761 void
kernel_debug(uint32_t debugid,uintptr_t arg1,uintptr_t arg2,uintptr_t arg3,uintptr_t arg4,__unused uintptr_t arg5)762 kernel_debug(uint32_t debugid, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3,
763 uintptr_t arg4, __unused uintptr_t arg5)
764 {
765 kernel_debug_internal(debugid, arg1, arg2, arg3, arg4,
766 (uintptr_t)thread_tid(current_thread()), 0);
767 }
768
769 __attribute__((noinline))
770 void
kernel_debug1(uint32_t debugid,uintptr_t arg1,uintptr_t arg2,uintptr_t arg3,uintptr_t arg4,uintptr_t arg5)771 kernel_debug1(uint32_t debugid, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3,
772 uintptr_t arg4, uintptr_t arg5)
773 {
774 kernel_debug_internal(debugid, arg1, arg2, arg3, arg4, arg5, 0);
775 }
776
777 __attribute__((noinline))
778 void
kernel_debug_flags(uint32_t debugid,uintptr_t arg1,uintptr_t arg2,uintptr_t arg3,uintptr_t arg4,uint64_t flags)779 kernel_debug_flags(
780 uint32_t debugid,
781 uintptr_t arg1,
782 uintptr_t arg2,
783 uintptr_t arg3,
784 uintptr_t arg4,
785 uint64_t flags)
786 {
787 kernel_debug_internal(debugid, arg1, arg2, arg3, arg4,
788 (uintptr_t)thread_tid(current_thread()), flags);
789 }
790
791 __attribute__((noinline))
792 void
kernel_debug_filtered(uint32_t debugid,uintptr_t arg1,uintptr_t arg2,uintptr_t arg3,uintptr_t arg4)793 kernel_debug_filtered(
794 uint32_t debugid,
795 uintptr_t arg1,
796 uintptr_t arg2,
797 uintptr_t arg3,
798 uintptr_t arg4)
799 {
800 kernel_debug_flags(debugid, arg1, arg2, arg3, arg4, KDBG_FLAG_FILTERED);
801 }
802
803 void
kernel_debug_string_early(const char * message)804 kernel_debug_string_early(const char *message)
805 {
806 uintptr_t a[4] = { 0 };
807 strncpy((char *)a, message, sizeof(a));
808 KERNEL_DEBUG_EARLY(TRACE_INFO_STRING, a[0], a[1], a[2], a[3]);
809 }
810
811 #define SIMPLE_STR_LEN (64)
812 static_assert(SIMPLE_STR_LEN % sizeof(uintptr_t) == 0);
813
814 void
kernel_debug_string_simple(uint32_t eventid,const char * str)815 kernel_debug_string_simple(uint32_t eventid, const char *str)
816 {
817 if (!kdebug_enable) {
818 return;
819 }
820
821 /* array of uintptr_ts simplifies emitting the string as arguments */
822 uintptr_t str_buf[(SIMPLE_STR_LEN / sizeof(uintptr_t)) + 1] = { 0 };
823 size_t len = strlcpy((char *)str_buf, str, SIMPLE_STR_LEN + 1);
824 len = MIN(len, SIMPLE_STR_LEN);
825
826 uintptr_t thread_id = (uintptr_t)thread_tid(current_thread());
827 uint32_t debugid = eventid | DBG_FUNC_START;
828
829 /* string can fit in a single tracepoint */
830 if (len <= (4 * sizeof(uintptr_t))) {
831 debugid |= DBG_FUNC_END;
832 }
833
834 kernel_debug_internal(debugid, str_buf[0], str_buf[1], str_buf[2],
835 str_buf[3], thread_id, 0);
836
837 debugid &= KDBG_EVENTID_MASK;
838 int i = 4;
839 size_t written = 4 * sizeof(uintptr_t);
840
841 for (; written < len; i += 4, written += 4 * sizeof(uintptr_t)) {
842 /* if this is the last tracepoint to be emitted */
843 if ((written + (4 * sizeof(uintptr_t))) >= len) {
844 debugid |= DBG_FUNC_END;
845 }
846 kernel_debug_internal(debugid, str_buf[i],
847 str_buf[i + 1],
848 str_buf[i + 2],
849 str_buf[i + 3], thread_id, 0);
850 }
851 }
852
853 extern int master_cpu; /* MACH_KERNEL_PRIVATE */
854 /*
855 * Used prior to start_kern_tracing() being called.
856 * Log temporarily into a static buffer.
857 */
858 void
kernel_debug_early(uint32_t debugid,uintptr_t arg1,uintptr_t arg2,uintptr_t arg3,uintptr_t arg4)859 kernel_debug_early(
860 uint32_t debugid,
861 uintptr_t arg1,
862 uintptr_t arg2,
863 uintptr_t arg3,
864 uintptr_t arg4)
865 {
866 #if defined(__x86_64__)
867 extern int early_boot;
868 /*
869 * Note that "early" isn't early enough in some cases where
870 * we're invoked before gsbase is set on x86, hence the
871 * check of "early_boot".
872 */
873 if (early_boot) {
874 return;
875 }
876 #endif
877
878 /* If early tracing is over, use the normal path. */
879 if (kd_early_done) {
880 KDBG_RELEASE(debugid, arg1, arg2, arg3, arg4);
881 return;
882 }
883
884 /* Do nothing if the buffer is full or we're not on the boot cpu. */
885 kd_early_overflow = kd_early_index >= KD_EARLY_EVENT_COUNT;
886 if (kd_early_overflow || cpu_number() != master_cpu) {
887 return;
888 }
889
890 kd_early_buffer[kd_early_index].debugid = debugid;
891 kd_early_buffer[kd_early_index].timestamp = mach_absolute_time();
892 kd_early_buffer[kd_early_index].arg1 = arg1;
893 kd_early_buffer[kd_early_index].arg2 = arg2;
894 kd_early_buffer[kd_early_index].arg3 = arg3;
895 kd_early_buffer[kd_early_index].arg4 = arg4;
896 kd_early_buffer[kd_early_index].arg5 = 0;
897 kd_early_index++;
898 }
899
900 /*
901 * Transfer the contents of the temporary buffer into the trace buffers.
902 * Precede that by logging the rebase time (offset) - the TSC-based time (in ns)
903 * when mach_absolute_time is set to 0.
904 */
905 static void
kernel_debug_early_end(void)906 kernel_debug_early_end(void)
907 {
908 if (cpu_number() != master_cpu) {
909 panic("kernel_debug_early_end() not call on boot processor");
910 }
911
912 /* reset the current oldest time to allow early events */
913 kd_control_trace.kdc_oldest_time = 0;
914
915 #if defined(__x86_64__)
916 /* Fake sentinel marking the start of kernel time relative to TSC */
917 kernel_debug_enter(0, TRACE_TIMESTAMPS, 0,
918 (uint32_t)(tsc_rebase_abs_time >> 32), (uint32_t)tsc_rebase_abs_time,
919 tsc_at_boot, 0, 0);
920 #endif /* defined(__x86_64__) */
921 for (unsigned int i = 0; i < kd_early_index; i++) {
922 kernel_debug_enter(0,
923 kd_early_buffer[i].debugid,
924 kd_early_buffer[i].timestamp,
925 kd_early_buffer[i].arg1,
926 kd_early_buffer[i].arg2,
927 kd_early_buffer[i].arg3,
928 kd_early_buffer[i].arg4,
929 0);
930 }
931
932 /* Cut events-lost event on overflow */
933 if (kd_early_overflow) {
934 KDBG_RELEASE(TRACE_LOST_EVENTS, 1);
935 }
936
937 kd_early_done = true;
938
939 /* This trace marks the start of kernel tracing */
940 kernel_debug_string_early("early trace done");
941 }
942
943 void
kernel_debug_disable(void)944 kernel_debug_disable(void)
945 {
946 if (kdebug_enable) {
947 kdbg_set_tracing_enabled(false, 0);
948 kdbg_wakeup();
949 }
950 }
951
952 // Returns true if debugid should only be traced from the kernel.
953 static int
_kernel_only_event(uint32_t debugid)954 _kernel_only_event(uint32_t debugid)
955 {
956 return KDBG_EXTRACT_CLASS(debugid) == DBG_TRACE;
957 }
958
959 /*
960 * Support syscall SYS_kdebug_typefilter.
961 */
962 int
kdebug_typefilter(__unused struct proc * p,struct kdebug_typefilter_args * uap,__unused int * retval)963 kdebug_typefilter(__unused struct proc* p, struct kdebug_typefilter_args* uap,
964 __unused int *retval)
965 {
966 if (uap->addr == USER_ADDR_NULL || uap->size == USER_ADDR_NULL) {
967 return EINVAL;
968 }
969
970 mach_vm_offset_t user_addr = 0;
971 vm_map_t user_map = current_map();
972 const bool copy = false;
973 kern_return_t kr = mach_vm_map_kernel(user_map, &user_addr,
974 TYPEFILTER_ALLOC_SIZE, 0, VM_MAP_KERNEL_FLAGS_ANYWHERE(),
975 kdbg_typefilter_memory_entry, 0, copy,
976 VM_PROT_READ, VM_PROT_READ, VM_INHERIT_SHARE);
977 if (kr != KERN_SUCCESS) {
978 return mach_to_bsd_errno(kr);
979 }
980
981 vm_size_t user_ptr_size = vm_map_is_64bit(user_map) ? 8 : 4;
982 int error = copyout((void *)&user_addr, uap->addr, user_ptr_size);
983 if (error != 0) {
984 mach_vm_deallocate(user_map, user_addr, TYPEFILTER_ALLOC_SIZE);
985 }
986 return error;
987 }
988
989 // Support SYS_kdebug_trace.
990 int
kdebug_trace(struct proc * p,struct kdebug_trace_args * uap,int32_t * retval)991 kdebug_trace(struct proc *p, struct kdebug_trace_args *uap, int32_t *retval)
992 {
993 struct kdebug_trace64_args uap64 = {
994 .code = uap->code,
995 .arg1 = uap->arg1,
996 .arg2 = uap->arg2,
997 .arg3 = uap->arg3,
998 .arg4 = uap->arg4,
999 };
1000 return kdebug_trace64(p, &uap64, retval);
1001 }
1002
1003 // Support kdebug_trace(2). 64-bit arguments on K32 will get truncated
1004 // to fit in the 32-bit record format.
1005 //
1006 // It is intentional that error conditions are not checked until kdebug is
1007 // enabled. This is to match the userspace wrapper behavior, which is optimizing
1008 // for non-error case performance.
1009 int
kdebug_trace64(__unused struct proc * p,struct kdebug_trace64_args * uap,__unused int32_t * retval)1010 kdebug_trace64(__unused struct proc *p, struct kdebug_trace64_args *uap,
1011 __unused int32_t *retval)
1012 {
1013 if (__probable(kdebug_enable == 0)) {
1014 return 0;
1015 }
1016 if (_kernel_only_event(uap->code)) {
1017 return EPERM;
1018 }
1019 kernel_debug_internal(uap->code, (uintptr_t)uap->arg1,
1020 (uintptr_t)uap->arg2, (uintptr_t)uap->arg3, (uintptr_t)uap->arg4,
1021 (uintptr_t)thread_tid(current_thread()), 0);
1022 return 0;
1023 }
1024
1025 /*
1026 * Adding enough padding to contain a full tracepoint for the last
1027 * portion of the string greatly simplifies the logic of splitting the
1028 * string between tracepoints. Full tracepoints can be generated using
1029 * the buffer itself, without having to manually add zeros to pad the
1030 * arguments.
1031 */
1032
1033 /* 2 string args in first tracepoint and 9 string data tracepoints */
1034 #define STR_BUF_ARGS (2 + (32 * 4))
1035 /* times the size of each arg on K64 */
1036 #define MAX_STR_LEN (STR_BUF_ARGS * sizeof(uint64_t))
1037 /* on K32, ending straddles a tracepoint, so reserve blanks */
1038 #define STR_BUF_SIZE (MAX_STR_LEN + (2 * sizeof(uint32_t)))
1039
1040 /*
1041 * This function does no error checking and assumes that it is called with
1042 * the correct arguments, including that the buffer pointed to by str is at
1043 * least STR_BUF_SIZE bytes. However, str must be aligned to word-size and
1044 * be NUL-terminated. In cases where a string can fit evenly into a final
1045 * tracepoint without its NUL-terminator, this function will not end those
1046 * strings with a NUL in trace. It's up to clients to look at the function
1047 * qualifier for DBG_FUNC_END in this case, to end the string.
1048 */
1049 static uint64_t
kernel_debug_string_internal(uint32_t debugid,uint64_t str_id,void * vstr,size_t str_len)1050 kernel_debug_string_internal(uint32_t debugid, uint64_t str_id, void *vstr,
1051 size_t str_len)
1052 {
1053 /* str must be word-aligned */
1054 uintptr_t *str = vstr;
1055 size_t written = 0;
1056 uintptr_t thread_id;
1057 int i;
1058 uint32_t trace_debugid = TRACEDBG_CODE(DBG_TRACE_STRING,
1059 TRACE_STRING_GLOBAL);
1060
1061 thread_id = (uintptr_t)thread_tid(current_thread());
1062
1063 /* if the ID is being invalidated, just emit that */
1064 if (str_id != 0 && str_len == 0) {
1065 kernel_debug_internal(trace_debugid | DBG_FUNC_START | DBG_FUNC_END,
1066 (uintptr_t)debugid, (uintptr_t)str_id, 0, 0, thread_id, 0);
1067 return str_id;
1068 }
1069
1070 /* generate an ID, if necessary */
1071 if (str_id == 0) {
1072 str_id = OSIncrementAtomic64((SInt64 *)&g_curr_str_id);
1073 str_id = (str_id & STR_ID_MASK) | g_str_id_signature;
1074 }
1075
1076 trace_debugid |= DBG_FUNC_START;
1077 /* string can fit in a single tracepoint */
1078 if (str_len <= (2 * sizeof(uintptr_t))) {
1079 trace_debugid |= DBG_FUNC_END;
1080 }
1081
1082 kernel_debug_internal(trace_debugid, (uintptr_t)debugid, (uintptr_t)str_id,
1083 str[0], str[1], thread_id, 0);
1084
1085 trace_debugid &= KDBG_EVENTID_MASK;
1086 i = 2;
1087 written += 2 * sizeof(uintptr_t);
1088
1089 for (; written < str_len; i += 4, written += 4 * sizeof(uintptr_t)) {
1090 if ((written + (4 * sizeof(uintptr_t))) >= str_len) {
1091 trace_debugid |= DBG_FUNC_END;
1092 }
1093 kernel_debug_internal(trace_debugid, str[i],
1094 str[i + 1],
1095 str[i + 2],
1096 str[i + 3], thread_id, 0);
1097 }
1098
1099 return str_id;
1100 }
1101
1102 /*
1103 * Returns true if the current process can emit events, and false otherwise.
1104 * Trace system and scheduling events circumvent this check, as do events
1105 * emitted in interrupt context.
1106 */
1107 static bool
kdebug_current_proc_enabled(uint32_t debugid)1108 kdebug_current_proc_enabled(uint32_t debugid)
1109 {
1110 /* can't determine current process in interrupt context */
1111 if (ml_at_interrupt_context()) {
1112 return true;
1113 }
1114
1115 /* always emit trace system and scheduling events */
1116 if ((KDBG_EXTRACT_CLASS(debugid) == DBG_TRACE ||
1117 (debugid & KDBG_CSC_MASK) == MACHDBG_CODE(DBG_MACH_SCHED, 0))) {
1118 return true;
1119 }
1120
1121 if (kd_control_trace.kdc_flags & KDBG_PIDCHECK) {
1122 proc_t cur_proc = kdebug_current_proc_unsafe();
1123
1124 /* only the process with the kdebug bit set is allowed */
1125 if (cur_proc && !(cur_proc->p_kdebug)) {
1126 return false;
1127 }
1128 } else if (kd_control_trace.kdc_flags & KDBG_PIDEXCLUDE) {
1129 proc_t cur_proc = kdebug_current_proc_unsafe();
1130
1131 /* every process except the one with the kdebug bit set is allowed */
1132 if (cur_proc && cur_proc->p_kdebug) {
1133 return false;
1134 }
1135 }
1136
1137 return true;
1138 }
1139
1140 bool
kdebug_debugid_enabled(uint32_t debugid)1141 kdebug_debugid_enabled(uint32_t debugid)
1142 {
1143 return _should_emit_debugid(kd_control_trace.kdc_emit, debugid);
1144 }
1145
1146 bool
kdebug_debugid_explicitly_enabled(uint32_t debugid)1147 kdebug_debugid_explicitly_enabled(uint32_t debugid)
1148 {
1149 if (kd_control_trace.kdc_flags & KDBG_TYPEFILTER_CHECK) {
1150 return typefilter_is_debugid_allowed(kdbg_typefilter, debugid);
1151 } else if (KDBG_EXTRACT_CLASS(debugid) == DBG_TRACE) {
1152 return true;
1153 } else if (kd_control_trace.kdc_flags & KDBG_RANGECHECK) {
1154 if (debugid < kdlog_beg || debugid > kdlog_end) {
1155 return false;
1156 }
1157 } else if (kd_control_trace.kdc_flags & KDBG_VALCHECK) {
1158 if ((debugid & KDBG_EVENTID_MASK) != kdlog_value1 &&
1159 (debugid & KDBG_EVENTID_MASK) != kdlog_value2 &&
1160 (debugid & KDBG_EVENTID_MASK) != kdlog_value3 &&
1161 (debugid & KDBG_EVENTID_MASK) != kdlog_value4) {
1162 return false;
1163 }
1164 }
1165
1166 return true;
1167 }
1168
1169 /*
1170 * Returns 0 if a string can be traced with these arguments. Returns errno
1171 * value if error occurred.
1172 */
1173 static errno_t
kdebug_check_trace_string(uint32_t debugid,uint64_t str_id)1174 kdebug_check_trace_string(uint32_t debugid, uint64_t str_id)
1175 {
1176 if (debugid & (DBG_FUNC_START | DBG_FUNC_END)) {
1177 return EINVAL;
1178 }
1179 if (_kernel_only_event(debugid)) {
1180 return EPERM;
1181 }
1182 if (str_id != 0 && (str_id & STR_ID_SIG_MASK) != g_str_id_signature) {
1183 return EINVAL;
1184 }
1185 return 0;
1186 }
1187
1188 /*
1189 * Implementation of KPI kernel_debug_string.
1190 */
1191 int
kernel_debug_string(uint32_t debugid,uint64_t * str_id,const char * str)1192 kernel_debug_string(uint32_t debugid, uint64_t *str_id, const char *str)
1193 {
1194 /* arguments to tracepoints must be word-aligned */
1195 __attribute__((aligned(sizeof(uintptr_t)))) char str_buf[STR_BUF_SIZE];
1196 static_assert(sizeof(str_buf) > MAX_STR_LEN);
1197 vm_size_t len_copied;
1198 int err;
1199
1200 assert(str_id);
1201
1202 if (__probable(kdebug_enable == 0)) {
1203 return 0;
1204 }
1205
1206 if (!kdebug_current_proc_enabled(debugid)) {
1207 return 0;
1208 }
1209
1210 if (!kdebug_debugid_enabled(debugid)) {
1211 return 0;
1212 }
1213
1214 if ((err = kdebug_check_trace_string(debugid, *str_id)) != 0) {
1215 return err;
1216 }
1217
1218 if (str == NULL) {
1219 if (str_id == 0) {
1220 return EINVAL;
1221 }
1222
1223 *str_id = kernel_debug_string_internal(debugid, *str_id, NULL, 0);
1224 return 0;
1225 }
1226
1227 memset(str_buf, 0, sizeof(str_buf));
1228 len_copied = strlcpy(str_buf, str, MAX_STR_LEN + 1);
1229 *str_id = kernel_debug_string_internal(debugid, *str_id, str_buf,
1230 len_copied);
1231 return 0;
1232 }
1233
1234 // Support kdebug_trace_string(2).
1235 int
kdebug_trace_string(__unused struct proc * p,struct kdebug_trace_string_args * uap,uint64_t * retval)1236 kdebug_trace_string(__unused struct proc *p,
1237 struct kdebug_trace_string_args *uap,
1238 uint64_t *retval)
1239 {
1240 __attribute__((aligned(sizeof(uintptr_t)))) char str_buf[STR_BUF_SIZE];
1241 static_assert(sizeof(str_buf) > MAX_STR_LEN);
1242 size_t len_copied;
1243 int err;
1244
1245 if (__probable(kdebug_enable == 0)) {
1246 return 0;
1247 }
1248
1249 if (!kdebug_current_proc_enabled(uap->debugid)) {
1250 return 0;
1251 }
1252
1253 if (!kdebug_debugid_enabled(uap->debugid)) {
1254 return 0;
1255 }
1256
1257 if ((err = kdebug_check_trace_string(uap->debugid, uap->str_id)) != 0) {
1258 return err;
1259 }
1260
1261 if (uap->str == USER_ADDR_NULL) {
1262 if (uap->str_id == 0) {
1263 return EINVAL;
1264 }
1265
1266 *retval = kernel_debug_string_internal(uap->debugid, uap->str_id,
1267 NULL, 0);
1268 return 0;
1269 }
1270
1271 memset(str_buf, 0, sizeof(str_buf));
1272 err = copyinstr(uap->str, str_buf, MAX_STR_LEN + 1, &len_copied);
1273
1274 /* it's alright to truncate the string, so allow ENAMETOOLONG */
1275 if (err == ENAMETOOLONG) {
1276 str_buf[MAX_STR_LEN] = '\0';
1277 } else if (err) {
1278 return err;
1279 }
1280
1281 if (len_copied <= 1) {
1282 return EINVAL;
1283 }
1284
1285 /* convert back to a length */
1286 len_copied--;
1287
1288 *retval = kernel_debug_string_internal(uap->debugid, uap->str_id, str_buf,
1289 len_copied);
1290 return 0;
1291 }
1292
1293 int
kdbg_reinit(unsigned int extra_cpus)1294 kdbg_reinit(unsigned int extra_cpus)
1295 {
1296 kernel_debug_disable();
1297 // Wait for any event writers to see the disable status.
1298 IOSleep(100);
1299 delete_buffers_trace();
1300
1301 _clear_thread_map();
1302 kd_control_trace.kdc_live_flags &= ~KDBG_WRAPPED;
1303
1304 RAW_file_offset = 0;
1305 RAW_file_written = 0;
1306
1307 return create_buffers_trace(extra_cpus);
1308 }
1309
1310 void
kdbg_trace_data(struct proc * proc,long * arg_pid,long * arg_uniqueid)1311 kdbg_trace_data(struct proc *proc, long *arg_pid, long *arg_uniqueid)
1312 {
1313 if (proc) {
1314 *arg_pid = proc_getpid(proc);
1315 *arg_uniqueid = (long)proc_uniqueid(proc);
1316 if ((uint64_t)*arg_uniqueid != proc_uniqueid(proc)) {
1317 *arg_uniqueid = 0;
1318 }
1319 } else {
1320 *arg_pid = 0;
1321 *arg_uniqueid = 0;
1322 }
1323 }
1324
1325 void kdebug_proc_name_args(struct proc *proc, long args[static 4]);
1326 void
kdebug_proc_name_args(struct proc * proc,long args[static4])1327 kdebug_proc_name_args(struct proc *proc, long args[static 4])
1328 {
1329 if (proc) {
1330 strncpy((char *)args, proc_best_name(proc), 4 * sizeof(args[0]));
1331 }
1332 }
1333
1334 static void
_copy_ap_name(unsigned int cpuid,void * dst,size_t size)1335 _copy_ap_name(unsigned int cpuid, void *dst, size_t size)
1336 {
1337 const char *name = "AP";
1338 #if defined(__arm64__)
1339 const ml_topology_info_t *topology = ml_get_topology_info();
1340 switch (topology->cpus[cpuid].cluster_type) {
1341 case CLUSTER_TYPE_E:
1342 name = "AP-E";
1343 break;
1344 case CLUSTER_TYPE_P:
1345 name = "AP-P";
1346 break;
1347 default:
1348 break;
1349 }
1350 #else /* defined(__arm64__) */
1351 #pragma unused(cpuid)
1352 #endif /* !defined(__arm64__) */
1353 strlcpy(dst, name, size);
1354 }
1355
1356 // Write the specified `map_version` of CPU map to the `dst` buffer, using at
1357 // most `size` bytes. Returns 0 on success and sets `size` to the number of
1358 // bytes written, and either ENOMEM or EINVAL on failure.
1359 //
1360 // If the value pointed to by `dst` is NULL, memory is allocated, and `size` is
1361 // adjusted to the allocated buffer's size.
1362 //
1363 // NB: `coprocs` is used to determine whether the stashed CPU map captured at
1364 // the start of tracing should be used.
1365 static errno_t
_copy_cpu_map(int map_version,void ** dst,size_t * size)1366 _copy_cpu_map(int map_version, void **dst, size_t *size)
1367 {
1368 _coproc_lock();
1369 struct kd_coproc *coprocs = kd_control_trace.kdc_coprocs;
1370 unsigned int cpu_count = kd_control_trace.kdebug_cpus;
1371 _coproc_unlock();
1372
1373 assert(cpu_count != 0);
1374 assert(coprocs == NULL || coprocs[0].cpu_id + 1 == cpu_count);
1375
1376 bool ext = map_version != RAW_VERSION1;
1377 size_t stride = ext ? sizeof(kd_cpumap_ext) : sizeof(kd_cpumap);
1378
1379 size_t size_needed = sizeof(kd_cpumap_header) + cpu_count * stride;
1380 size_t size_avail = *size;
1381 *size = size_needed;
1382
1383 if (*dst == NULL) {
1384 kern_return_t alloc_ret = kmem_alloc(kernel_map, (vm_offset_t *)dst,
1385 (vm_size_t)size_needed, KMA_DATA | KMA_ZERO, VM_KERN_MEMORY_DIAG);
1386 if (alloc_ret != KERN_SUCCESS) {
1387 return ENOMEM;
1388 }
1389 } else if (size_avail < size_needed) {
1390 return EINVAL;
1391 }
1392
1393 kd_cpumap_header *header = *dst;
1394 header->version_no = map_version;
1395 header->cpu_count = cpu_count;
1396
1397 void *cpus = &header[1];
1398 size_t name_size = ext ? sizeof(((kd_cpumap_ext *)NULL)->name) :
1399 sizeof(((kd_cpumap *)NULL)->name);
1400
1401 int i = cpu_count - 1;
1402 for (struct kd_coproc *cur_coproc = coprocs; cur_coproc != NULL;
1403 cur_coproc = cur_coproc->next, i--) {
1404 kd_cpumap_ext *cpu = (kd_cpumap_ext *)((uintptr_t)cpus + stride * i);
1405 cpu->cpu_id = cur_coproc->cpu_id;
1406 cpu->flags = KDBG_CPUMAP_IS_IOP;
1407 strlcpy((void *)&cpu->name, cur_coproc->full_name, name_size);
1408 }
1409 for (; i >= 0; i--) {
1410 kd_cpumap *cpu = (kd_cpumap *)((uintptr_t)cpus + stride * i);
1411 cpu->cpu_id = i;
1412 cpu->flags = 0;
1413 _copy_ap_name(i, &cpu->name, name_size);
1414 }
1415
1416 return 0;
1417 }
1418
1419 static void
_threadmap_init(void)1420 _threadmap_init(void)
1421 {
1422 ktrace_assert_lock_held();
1423
1424 if (kd_control_trace.kdc_flags & KDBG_MAPINIT) {
1425 return;
1426 }
1427
1428 kd_mapptr = _thread_map_create_live(0, &kd_mapsize, &kd_mapcount);
1429
1430 if (kd_mapptr) {
1431 kd_control_trace.kdc_flags |= KDBG_MAPINIT;
1432 }
1433 }
1434
1435 struct kd_resolver {
1436 kd_threadmap *krs_map;
1437 vm_size_t krs_count;
1438 vm_size_t krs_maxcount;
1439 };
1440
1441 static int
_resolve_iterator(proc_t proc,void * opaque)1442 _resolve_iterator(proc_t proc, void *opaque)
1443 {
1444 if (proc == kernproc) {
1445 /* Handled specially as it lacks uthreads. */
1446 return PROC_RETURNED;
1447 }
1448 struct kd_resolver *resolver = opaque;
1449 struct uthread *uth = NULL;
1450 const char *proc_name = proc_best_name(proc);
1451 pid_t pid = proc_getpid(proc);
1452
1453 proc_lock(proc);
1454 TAILQ_FOREACH(uth, &proc->p_uthlist, uu_list) {
1455 if (resolver->krs_count >= resolver->krs_maxcount) {
1456 break;
1457 }
1458 kd_threadmap *map = &resolver->krs_map[resolver->krs_count];
1459 map->thread = (uintptr_t)uthread_tid(uth);
1460 (void)strlcpy(map->command, proc_name, sizeof(map->command));
1461 map->valid = pid;
1462 resolver->krs_count++;
1463 }
1464 proc_unlock(proc);
1465
1466 bool done = resolver->krs_count >= resolver->krs_maxcount;
1467 return done ? PROC_RETURNED_DONE : PROC_RETURNED;
1468 }
1469
1470 static void
_resolve_kernel_task(thread_t thread,void * opaque)1471 _resolve_kernel_task(thread_t thread, void *opaque)
1472 {
1473 struct kd_resolver *resolver = opaque;
1474 if (resolver->krs_count >= resolver->krs_maxcount) {
1475 return;
1476 }
1477 kd_threadmap *map = &resolver->krs_map[resolver->krs_count];
1478 map->thread = (uintptr_t)thread_tid(thread);
1479 (void)strlcpy(map->command, "kernel_task", sizeof(map->command));
1480 map->valid = 1;
1481 resolver->krs_count++;
1482 }
1483
1484 static vm_size_t
_resolve_threads(kd_threadmap * map,vm_size_t nthreads)1485 _resolve_threads(kd_threadmap *map, vm_size_t nthreads)
1486 {
1487 struct kd_resolver resolver = {
1488 .krs_map = map, .krs_count = 0, .krs_maxcount = nthreads,
1489 };
1490
1491 // Handle kernel_task specially, as it lacks uthreads.
1492 extern void task_act_iterate_wth_args(task_t, void (*)(thread_t, void *),
1493 void *);
1494 task_act_iterate_wth_args(kernel_task, _resolve_kernel_task, &resolver);
1495 proc_iterate(PROC_ALLPROCLIST | PROC_NOWAITTRANS, _resolve_iterator,
1496 &resolver, NULL, NULL);
1497 return resolver.krs_count;
1498 }
1499
1500 static kd_threadmap *
_thread_map_create_live(size_t maxthreads,vm_size_t * mapsize,vm_size_t * mapcount)1501 _thread_map_create_live(size_t maxthreads, vm_size_t *mapsize,
1502 vm_size_t *mapcount)
1503 {
1504 kd_threadmap *thread_map = NULL;
1505
1506 assert(mapsize != NULL);
1507 assert(mapcount != NULL);
1508
1509 extern int threads_count;
1510 vm_size_t nthreads = threads_count;
1511
1512 // Allow 25% more threads to be started while iterating processes.
1513 if (os_add_overflow(nthreads, nthreads / 4, &nthreads)) {
1514 return NULL;
1515 }
1516
1517 *mapcount = nthreads;
1518 if (os_mul_overflow(nthreads, sizeof(kd_threadmap), mapsize)) {
1519 return NULL;
1520 }
1521
1522 // Wait until the out-parameters have been filled with the needed size to
1523 // do the bounds checking on the provided maximum.
1524 if (maxthreads != 0 && maxthreads < nthreads) {
1525 return NULL;
1526 }
1527
1528 // This allocation can be too large for `Z_NOFAIL`.
1529 thread_map = kalloc_data_tag(*mapsize, Z_WAITOK | Z_ZERO,
1530 VM_KERN_MEMORY_DIAG);
1531 if (thread_map != NULL) {
1532 *mapcount = _resolve_threads(thread_map, nthreads);
1533 }
1534 return thread_map;
1535 }
1536
1537 static void
kdbg_clear(void)1538 kdbg_clear(void)
1539 {
1540 kernel_debug_disable();
1541 kdbg_disable_typefilter();
1542
1543 // Wait for any event writers to see the disable status.
1544 IOSleep(100);
1545
1546 // Reset kdebug status for each process.
1547 if (kd_control_trace.kdc_flags & (KDBG_PIDCHECK | KDBG_PIDEXCLUDE)) {
1548 proc_list_lock();
1549 proc_t p;
1550 ALLPROC_FOREACH(p) {
1551 p->p_kdebug = 0;
1552 }
1553 proc_list_unlock();
1554 }
1555
1556 kd_control_trace.kdc_flags &= (unsigned int)~KDBG_CKTYPES;
1557 kd_control_trace.kdc_flags &= ~(KDBG_RANGECHECK | KDBG_VALCHECK);
1558 kd_control_trace.kdc_flags &= ~(KDBG_PIDCHECK | KDBG_PIDEXCLUDE);
1559 kd_control_trace.kdc_flags &= ~KDBG_CONTINUOUS_TIME;
1560 kd_control_trace.kdc_flags &= ~KDBG_DISABLE_COPROCS;
1561 kd_control_trace.kdc_flags &= ~KDBG_MATCH_DISABLE;
1562 kd_control_trace.kdc_live_flags &= ~(KDBG_NOWRAP | KDBG_WRAPPED);
1563
1564 kd_control_trace.kdc_oldest_time = 0;
1565
1566 delete_buffers_trace();
1567 kd_buffer_trace.kdb_event_count = 0;
1568
1569 _clear_thread_map();
1570
1571 RAW_file_offset = 0;
1572 RAW_file_written = 0;
1573 }
1574
1575 void
kdebug_reset(void)1576 kdebug_reset(void)
1577 {
1578 ktrace_assert_lock_held();
1579
1580 kdbg_clear();
1581 typefilter_reject_all(kdbg_typefilter);
1582 typefilter_allow_class(kdbg_typefilter, DBG_TRACE);
1583 }
1584
1585 void
kdebug_free_early_buf(void)1586 kdebug_free_early_buf(void)
1587 {
1588 #if defined(__x86_64__)
1589 ml_static_mfree((vm_offset_t)&kd_early_buffer, sizeof(kd_early_buffer));
1590 #endif /* defined(__x86_64__) */
1591 // ARM handles this as part of the BOOTDATA segment.
1592 }
1593
1594 int
kdbg_setpid(kd_regtype * kdr)1595 kdbg_setpid(kd_regtype *kdr)
1596 {
1597 pid_t pid;
1598 int flag, ret = 0;
1599 struct proc *p;
1600
1601 pid = (pid_t)kdr->value1;
1602 flag = (int)kdr->value2;
1603
1604 if (pid >= 0) {
1605 if ((p = proc_find(pid)) == NULL) {
1606 ret = ESRCH;
1607 } else {
1608 if (flag == 1) {
1609 /*
1610 * turn on pid check for this and all pids
1611 */
1612 kd_control_trace.kdc_flags |= KDBG_PIDCHECK;
1613 kd_control_trace.kdc_flags &= ~KDBG_PIDEXCLUDE;
1614
1615 p->p_kdebug = 1;
1616 } else {
1617 /*
1618 * turn off pid check for this pid value
1619 * Don't turn off all pid checking though
1620 *
1621 * kd_control_trace.kdc_flags &= ~KDBG_PIDCHECK;
1622 */
1623 p->p_kdebug = 0;
1624 }
1625 proc_rele(p);
1626 }
1627 } else {
1628 ret = EINVAL;
1629 }
1630
1631 return ret;
1632 }
1633
1634 /* This is for pid exclusion in the trace buffer */
1635 int
kdbg_setpidex(kd_regtype * kdr)1636 kdbg_setpidex(kd_regtype *kdr)
1637 {
1638 pid_t pid;
1639 int flag, ret = 0;
1640 struct proc *p;
1641
1642 pid = (pid_t)kdr->value1;
1643 flag = (int)kdr->value2;
1644
1645 if (pid >= 0) {
1646 if ((p = proc_find(pid)) == NULL) {
1647 ret = ESRCH;
1648 } else {
1649 if (flag == 1) {
1650 /*
1651 * turn on pid exclusion
1652 */
1653 kd_control_trace.kdc_flags |= KDBG_PIDEXCLUDE;
1654 kd_control_trace.kdc_flags &= ~KDBG_PIDCHECK;
1655
1656 p->p_kdebug = 1;
1657 } else {
1658 /*
1659 * turn off pid exclusion for this pid value
1660 * Don't turn off all pid exclusion though
1661 *
1662 * kd_control_trace.kdc_flags &= ~KDBG_PIDEXCLUDE;
1663 */
1664 p->p_kdebug = 0;
1665 }
1666 proc_rele(p);
1667 }
1668 } else {
1669 ret = EINVAL;
1670 }
1671
1672 return ret;
1673 }
1674
1675 /*
1676 * The following functions all operate on the typefilter singleton.
1677 */
1678
1679 static int
kdbg_copyin_typefilter(user_addr_t addr,size_t size)1680 kdbg_copyin_typefilter(user_addr_t addr, size_t size)
1681 {
1682 int ret = ENOMEM;
1683 typefilter_t tf;
1684
1685 ktrace_assert_lock_held();
1686
1687 if (size != KDBG_TYPEFILTER_BITMAP_SIZE) {
1688 return EINVAL;
1689 }
1690
1691 if ((tf = typefilter_create())) {
1692 if ((ret = copyin(addr, tf, KDBG_TYPEFILTER_BITMAP_SIZE)) == 0) {
1693 /* The kernel typefilter must always allow DBG_TRACE */
1694 typefilter_allow_class(tf, DBG_TRACE);
1695
1696 typefilter_copy(kdbg_typefilter, tf);
1697
1698 kdbg_enable_typefilter();
1699 _coproc_list_callback(KD_CALLBACK_TYPEFILTER_CHANGED, kdbg_typefilter);
1700 }
1701
1702 if (tf) {
1703 typefilter_deallocate(tf);
1704 }
1705 }
1706
1707 return ret;
1708 }
1709
1710 /*
1711 * Enable the flags in the control page for the typefilter. Assumes that
1712 * kdbg_typefilter has already been allocated, so events being written
1713 * don't see a bad typefilter.
1714 */
1715 static void
kdbg_enable_typefilter(void)1716 kdbg_enable_typefilter(void)
1717 {
1718 kd_control_trace.kdc_flags &= ~(KDBG_RANGECHECK | KDBG_VALCHECK);
1719 kd_control_trace.kdc_flags |= KDBG_TYPEFILTER_CHECK;
1720 if (kdebug_enable) {
1721 kd_control_trace.kdc_emit = _trace_emit_filter();
1722 }
1723 commpage_update_kdebug_state();
1724 }
1725
1726 // Disable the flags in the control page for the typefilter. The typefilter
1727 // may be safely deallocated shortly after this function returns.
1728 static void
kdbg_disable_typefilter(void)1729 kdbg_disable_typefilter(void)
1730 {
1731 bool notify_coprocs = kd_control_trace.kdc_flags & KDBG_TYPEFILTER_CHECK;
1732 kd_control_trace.kdc_flags &= ~KDBG_TYPEFILTER_CHECK;
1733
1734 commpage_update_kdebug_state();
1735
1736 if (notify_coprocs) {
1737 // Notify coprocessors that the typefilter will now allow everything.
1738 // Otherwise, they won't know a typefilter is no longer in effect.
1739 typefilter_allow_all(kdbg_typefilter);
1740 _coproc_list_callback(KD_CALLBACK_TYPEFILTER_CHANGED, kdbg_typefilter);
1741 }
1742 }
1743
1744 uint32_t
kdebug_commpage_state(void)1745 kdebug_commpage_state(void)
1746 {
1747 uint32_t state = 0;
1748 if (kdebug_enable) {
1749 state |= KDEBUG_COMMPAGE_ENABLE_TRACE;
1750 if (kd_control_trace.kdc_flags & KDBG_TYPEFILTER_CHECK) {
1751 state |= KDEBUG_COMMPAGE_ENABLE_TYPEFILTER;
1752 }
1753 if (kd_control_trace.kdc_flags & KDBG_CONTINUOUS_TIME) {
1754 state |= KDEBUG_COMMPAGE_CONTINUOUS;
1755 }
1756 }
1757 return state;
1758 }
1759
1760 static int
kdbg_setreg(kd_regtype * kdr)1761 kdbg_setreg(kd_regtype * kdr)
1762 {
1763 switch (kdr->type) {
1764 case KDBG_CLASSTYPE:
1765 kdlog_beg = KDBG_EVENTID(kdr->value1 & 0xff, 0, 0);
1766 kdlog_end = KDBG_EVENTID(kdr->value2 & 0xff, 0, 0);
1767 kd_control_trace.kdc_flags &= ~KDBG_VALCHECK;
1768 kd_control_trace.kdc_flags |= KDBG_RANGECHECK;
1769 break;
1770 case KDBG_SUBCLSTYPE:;
1771 unsigned int cls = kdr->value1 & 0xff;
1772 unsigned int subcls = kdr->value2 & 0xff;
1773 unsigned int subcls_end = subcls + 1;
1774 kdlog_beg = KDBG_EVENTID(cls, subcls, 0);
1775 kdlog_end = KDBG_EVENTID(cls, subcls_end, 0);
1776 kd_control_trace.kdc_flags &= ~KDBG_VALCHECK;
1777 kd_control_trace.kdc_flags |= KDBG_RANGECHECK;
1778 break;
1779 case KDBG_RANGETYPE:
1780 kdlog_beg = kdr->value1;
1781 kdlog_end = kdr->value2;
1782 kd_control_trace.kdc_flags &= ~KDBG_VALCHECK;
1783 kd_control_trace.kdc_flags |= KDBG_RANGECHECK;
1784 break;
1785 case KDBG_VALCHECK:
1786 kdlog_value1 = kdr->value1;
1787 kdlog_value2 = kdr->value2;
1788 kdlog_value3 = kdr->value3;
1789 kdlog_value4 = kdr->value4;
1790 kd_control_trace.kdc_flags &= ~KDBG_RANGECHECK;
1791 kd_control_trace.kdc_flags |= KDBG_VALCHECK;
1792 break;
1793 case KDBG_TYPENONE:
1794 kd_control_trace.kdc_flags &= ~(KDBG_RANGECHECK | KDBG_VALCHECK);
1795 kdlog_beg = 0;
1796 kdlog_end = 0;
1797 break;
1798 default:
1799 return EINVAL;
1800 }
1801 if (kdebug_enable) {
1802 kd_control_trace.kdc_emit = _trace_emit_filter();
1803 }
1804 return 0;
1805 }
1806
1807 static int
_copyin_event_disable_mask(user_addr_t uaddr,size_t usize)1808 _copyin_event_disable_mask(user_addr_t uaddr, size_t usize)
1809 {
1810 if (usize < 2 * sizeof(kd_event_matcher)) {
1811 return ERANGE;
1812 }
1813 int ret = copyin(uaddr, &kd_control_trace.disable_event_match,
1814 sizeof(kd_event_matcher));
1815 if (ret != 0) {
1816 return ret;
1817 }
1818 ret = copyin(uaddr + sizeof(kd_event_matcher),
1819 &kd_control_trace.disable_event_mask, sizeof(kd_event_matcher));
1820 if (ret != 0) {
1821 memset(&kd_control_trace.disable_event_match, 0,
1822 sizeof(kd_event_matcher));
1823 return ret;
1824 }
1825 return 0;
1826 }
1827
1828 static int
_copyout_event_disable_mask(user_addr_t uaddr,size_t usize)1829 _copyout_event_disable_mask(user_addr_t uaddr, size_t usize)
1830 {
1831 if (usize < 2 * sizeof(kd_event_matcher)) {
1832 return ERANGE;
1833 }
1834 int ret = copyout(&kd_control_trace.disable_event_match, uaddr,
1835 sizeof(kd_event_matcher));
1836 if (ret != 0) {
1837 return ret;
1838 }
1839 ret = copyout(&kd_control_trace.disable_event_mask,
1840 uaddr + sizeof(kd_event_matcher), sizeof(kd_event_matcher));
1841 if (ret != 0) {
1842 return ret;
1843 }
1844 return 0;
1845 }
1846
1847 static int
kdbg_write_to_vnode(caddr_t buffer,size_t size,vnode_t vp,vfs_context_t ctx,off_t file_offset)1848 kdbg_write_to_vnode(caddr_t buffer, size_t size, vnode_t vp, vfs_context_t ctx, off_t file_offset)
1849 {
1850 assert(size < INT_MAX);
1851 return vn_rdwr(UIO_WRITE, vp, buffer, (int)size, file_offset, UIO_SYSSPACE,
1852 IO_NODELOCKED | IO_UNIT, vfs_context_ucred(ctx), (int *) 0,
1853 vfs_context_proc(ctx));
1854 }
1855
1856 static errno_t
_copyout_cpu_map(int map_version,user_addr_t udst,size_t * usize)1857 _copyout_cpu_map(int map_version, user_addr_t udst, size_t *usize)
1858 {
1859 if ((kd_control_trace.kdc_flags & KDBG_BUFINIT) == 0) {
1860 return EINVAL;
1861 }
1862
1863 void *cpu_map = NULL;
1864 size_t size = 0;
1865 int error = _copy_cpu_map(map_version, &cpu_map, &size);
1866 if (0 == error) {
1867 if (udst) {
1868 size_t copy_size = MIN(*usize, size);
1869 error = copyout(cpu_map, udst, copy_size);
1870 }
1871 *usize = size;
1872 kmem_free(kernel_map, (vm_offset_t)cpu_map, size);
1873 }
1874 if (EINVAL == error && 0 == udst) {
1875 *usize = size;
1876 // User space only needs the size if it passes NULL;
1877 error = 0;
1878 }
1879 return error;
1880 }
1881
1882 int
kdbg_readcurthrmap(user_addr_t buffer,size_t * bufsize)1883 kdbg_readcurthrmap(user_addr_t buffer, size_t *bufsize)
1884 {
1885 kd_threadmap *mapptr;
1886 vm_size_t mapsize;
1887 vm_size_t mapcount;
1888 int ret = 0;
1889 size_t count = *bufsize / sizeof(kd_threadmap);
1890
1891 *bufsize = 0;
1892
1893 if ((mapptr = _thread_map_create_live(count, &mapsize, &mapcount))) {
1894 if (copyout(mapptr, buffer, mapcount * sizeof(kd_threadmap))) {
1895 ret = EFAULT;
1896 } else {
1897 *bufsize = (mapcount * sizeof(kd_threadmap));
1898 }
1899
1900 kfree_data(mapptr, mapsize);
1901 } else {
1902 ret = EINVAL;
1903 }
1904
1905 return ret;
1906 }
1907
1908 static int
_write_legacy_header(bool write_thread_map,vnode_t vp,vfs_context_t ctx)1909 _write_legacy_header(bool write_thread_map, vnode_t vp, vfs_context_t ctx)
1910 {
1911 int ret = 0;
1912 RAW_header header;
1913 clock_sec_t secs;
1914 clock_usec_t usecs;
1915 void *pad_buf;
1916 uint32_t pad_size;
1917 uint32_t extra_thread_count = 0;
1918 uint32_t cpumap_size;
1919 size_t map_size = 0;
1920 uint32_t map_count = 0;
1921
1922 if (write_thread_map) {
1923 assert(kd_control_trace.kdc_flags & KDBG_MAPINIT);
1924 if (kd_mapcount > UINT32_MAX) {
1925 return ERANGE;
1926 }
1927 map_count = (uint32_t)kd_mapcount;
1928 if (os_mul_overflow(map_count, sizeof(kd_threadmap), &map_size)) {
1929 return ERANGE;
1930 }
1931 if (map_size >= INT_MAX) {
1932 return ERANGE;
1933 }
1934 }
1935
1936 /*
1937 * Without the buffers initialized, we cannot construct a CPU map or a
1938 * thread map, and cannot write a header.
1939 */
1940 if (!(kd_control_trace.kdc_flags & KDBG_BUFINIT)) {
1941 return EINVAL;
1942 }
1943
1944 /*
1945 * To write a RAW_VERSION1+ file, we must embed a cpumap in the
1946 * "padding" used to page align the events following the threadmap. If
1947 * the threadmap happens to not require enough padding, we artificially
1948 * increase its footprint until it needs enough padding.
1949 */
1950
1951 assert(vp);
1952 assert(ctx);
1953
1954 pad_size = 16384 - ((sizeof(RAW_header) + map_size) & PAGE_MASK);
1955 cpumap_size = sizeof(kd_cpumap_header) + kd_control_trace.kdebug_cpus * sizeof(kd_cpumap);
1956
1957 if (cpumap_size > pad_size) {
1958 /* If the cpu map doesn't fit in the current available pad_size,
1959 * we increase the pad_size by 16K. We do this so that the event
1960 * data is always available on a page aligned boundary for both
1961 * 4k and 16k systems. We enforce this alignment for the event
1962 * data so that we can take advantage of optimized file/disk writes.
1963 */
1964 pad_size += 16384;
1965 }
1966
1967 /* The way we are silently embedding a cpumap in the "padding" is by artificially
1968 * increasing the number of thread entries. However, we'll also need to ensure that
1969 * the cpumap is embedded in the last 4K page before when the event data is expected.
1970 * This way the tools can read the data starting the next page boundary on both
1971 * 4K and 16K systems preserving compatibility with older versions of the tools
1972 */
1973 if (pad_size > 4096) {
1974 pad_size -= 4096;
1975 extra_thread_count = (pad_size / sizeof(kd_threadmap)) + 1;
1976 }
1977
1978 memset(&header, 0, sizeof(header));
1979 header.version_no = RAW_VERSION1;
1980 header.thread_count = map_count + extra_thread_count;
1981
1982 clock_get_calendar_microtime(&secs, &usecs);
1983 header.TOD_secs = secs;
1984 header.TOD_usecs = usecs;
1985
1986 ret = vn_rdwr(UIO_WRITE, vp, (caddr_t)&header, (int)sizeof(RAW_header), RAW_file_offset,
1987 UIO_SYSSPACE, IO_NODELOCKED | IO_UNIT, vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
1988 if (ret) {
1989 goto write_error;
1990 }
1991 RAW_file_offset += sizeof(RAW_header);
1992 RAW_file_written += sizeof(RAW_header);
1993
1994 if (write_thread_map) {
1995 assert(map_size < INT_MAX);
1996 ret = vn_rdwr(UIO_WRITE, vp, (caddr_t)kd_mapptr, (int)map_size, RAW_file_offset,
1997 UIO_SYSSPACE, IO_NODELOCKED | IO_UNIT, vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
1998 if (ret) {
1999 goto write_error;
2000 }
2001
2002 RAW_file_offset += map_size;
2003 RAW_file_written += map_size;
2004 }
2005
2006 if (extra_thread_count) {
2007 pad_size = extra_thread_count * sizeof(kd_threadmap);
2008 pad_buf = (char *)kalloc_data(pad_size, Z_WAITOK | Z_ZERO);
2009 if (!pad_buf) {
2010 ret = ENOMEM;
2011 goto write_error;
2012 }
2013
2014 assert(pad_size < INT_MAX);
2015 ret = vn_rdwr(UIO_WRITE, vp, (caddr_t)pad_buf, (int)pad_size, RAW_file_offset,
2016 UIO_SYSSPACE, IO_NODELOCKED | IO_UNIT, vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
2017 kfree_data(pad_buf, pad_size);
2018 if (ret) {
2019 goto write_error;
2020 }
2021
2022 RAW_file_offset += pad_size;
2023 RAW_file_written += pad_size;
2024 }
2025
2026 pad_size = PAGE_SIZE - (RAW_file_offset & PAGE_MASK);
2027 if (pad_size) {
2028 pad_buf = (char *)kalloc_data(pad_size, Z_WAITOK | Z_ZERO);
2029 if (!pad_buf) {
2030 ret = ENOMEM;
2031 goto write_error;
2032 }
2033
2034 /*
2035 * Embed the CPU map in the padding bytes -- old code will skip it,
2036 * while newer code knows it's there.
2037 */
2038 size_t temp = pad_size;
2039 errno_t error = _copy_cpu_map(RAW_VERSION1, &pad_buf, &temp);
2040 if (0 != error) {
2041 memset(pad_buf, 0, pad_size);
2042 }
2043
2044 assert(pad_size < INT_MAX);
2045 ret = vn_rdwr(UIO_WRITE, vp, (caddr_t)pad_buf, (int)pad_size, RAW_file_offset,
2046 UIO_SYSSPACE, IO_NODELOCKED | IO_UNIT, vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
2047 kfree_data(pad_buf, pad_size);
2048 if (ret) {
2049 goto write_error;
2050 }
2051
2052 RAW_file_offset += pad_size;
2053 RAW_file_written += pad_size;
2054 }
2055
2056 write_error:
2057 return ret;
2058 }
2059
2060 static void
_clear_thread_map(void)2061 _clear_thread_map(void)
2062 {
2063 ktrace_assert_lock_held();
2064
2065 if (kd_control_trace.kdc_flags & KDBG_MAPINIT) {
2066 assert(kd_mapptr != NULL);
2067 kfree_data(kd_mapptr, kd_mapsize);
2068 kd_mapptr = NULL;
2069 kd_mapsize = 0;
2070 kd_mapcount = 0;
2071 kd_control_trace.kdc_flags &= ~KDBG_MAPINIT;
2072 }
2073 }
2074
2075 /*
2076 * Write out a version 1 header and the thread map, if it is initialized, to a
2077 * vnode. Used by KDWRITEMAP and kdbg_dump_trace_to_file.
2078 *
2079 * Returns write errors from vn_rdwr if a write fails. Returns ENODATA if the
2080 * thread map has not been initialized, but the header will still be written.
2081 * Returns ENOMEM if padding could not be allocated. Returns 0 otherwise.
2082 */
2083 static int
kdbg_write_thread_map(vnode_t vp,vfs_context_t ctx)2084 kdbg_write_thread_map(vnode_t vp, vfs_context_t ctx)
2085 {
2086 int ret = 0;
2087 bool map_initialized;
2088
2089 ktrace_assert_lock_held();
2090 assert(ctx != NULL);
2091
2092 map_initialized = (kd_control_trace.kdc_flags & KDBG_MAPINIT);
2093
2094 ret = _write_legacy_header(map_initialized, vp, ctx);
2095 if (ret == 0) {
2096 if (map_initialized) {
2097 _clear_thread_map();
2098 } else {
2099 ret = ENODATA;
2100 }
2101 }
2102
2103 return ret;
2104 }
2105
2106 /*
2107 * Copy out the thread map to a user space buffer. Used by KDTHRMAP.
2108 *
2109 * Returns copyout errors if the copyout fails. Returns ENODATA if the thread
2110 * map has not been initialized. Returns EINVAL if the buffer provided is not
2111 * large enough for the entire thread map. Returns 0 otherwise.
2112 */
2113 static int
kdbg_copyout_thread_map(user_addr_t buffer,size_t * buffer_size)2114 kdbg_copyout_thread_map(user_addr_t buffer, size_t *buffer_size)
2115 {
2116 bool map_initialized;
2117 size_t map_size;
2118 int ret = 0;
2119
2120 ktrace_assert_lock_held();
2121 assert(buffer_size != NULL);
2122
2123 map_initialized = (kd_control_trace.kdc_flags & KDBG_MAPINIT);
2124 if (!map_initialized) {
2125 return ENODATA;
2126 }
2127
2128 map_size = kd_mapcount * sizeof(kd_threadmap);
2129 if (*buffer_size < map_size) {
2130 return EINVAL;
2131 }
2132
2133 ret = copyout(kd_mapptr, buffer, map_size);
2134 if (ret == 0) {
2135 _clear_thread_map();
2136 }
2137
2138 return ret;
2139 }
2140
2141 static void
kdbg_set_nkdbufs_trace(unsigned int req_nkdbufs_trace)2142 kdbg_set_nkdbufs_trace(unsigned int req_nkdbufs_trace)
2143 {
2144 /*
2145 * Only allow allocations of up to half the kernel's data range or "sane
2146 * size", whichever is smaller.
2147 */
2148 const uint64_t max_nkdbufs_trace_64 =
2149 MIN(kmem_range_id_size(KMEM_RANGE_ID_DATA), sane_size) / 2 /
2150 sizeof(kd_buf);
2151 /*
2152 * Can't allocate more than 2^38 (2^32 * 64) bytes of events without
2153 * switching to a 64-bit event count; should be fine.
2154 */
2155 const unsigned int max_nkdbufs_trace =
2156 (unsigned int)MIN(max_nkdbufs_trace_64, UINT_MAX);
2157
2158 kd_buffer_trace.kdb_event_count = MIN(req_nkdbufs_trace, max_nkdbufs_trace);
2159 }
2160
2161 /*
2162 * Block until there are `kd_buffer_trace.kdb_storage_threshold` storage units filled with
2163 * events or `timeout_ms` milliseconds have passed. If `locked_wait` is true,
2164 * `ktrace_lock` is held while waiting. This is necessary while waiting to
2165 * write events out of the buffers.
2166 *
2167 * Returns true if the threshold was reached and false otherwise.
2168 *
2169 * Called with `ktrace_lock` locked and interrupts enabled.
2170 */
2171 static bool
kdbg_wait(uint64_t timeout_ms)2172 kdbg_wait(uint64_t timeout_ms)
2173 {
2174 int wait_result = THREAD_AWAKENED;
2175 uint64_t deadline_mach = 0;
2176
2177 ktrace_assert_lock_held();
2178
2179 if (timeout_ms != 0) {
2180 uint64_t ns = timeout_ms * NSEC_PER_MSEC;
2181 nanoseconds_to_absolutetime(ns, &deadline_mach);
2182 clock_absolutetime_interval_to_deadline(deadline_mach, &deadline_mach);
2183 }
2184
2185 bool s = ml_set_interrupts_enabled(false);
2186 if (!s) {
2187 panic("kdbg_wait() called with interrupts disabled");
2188 }
2189 lck_spin_lock_grp(&kd_wait_lock, &kdebug_lck_grp);
2190
2191 /* drop the mutex to allow others to access trace */
2192 ktrace_unlock();
2193
2194 while (wait_result == THREAD_AWAKENED &&
2195 kd_control_trace.kdc_storage_used < kd_buffer_trace.kdb_storage_threshold) {
2196 kd_waiter = true;
2197
2198 if (deadline_mach) {
2199 wait_result = lck_spin_sleep_deadline(&kd_wait_lock, 0, &kd_waiter,
2200 THREAD_ABORTSAFE, deadline_mach);
2201 } else {
2202 wait_result = lck_spin_sleep(&kd_wait_lock, 0, &kd_waiter,
2203 THREAD_ABORTSAFE);
2204 }
2205 }
2206
2207 bool threshold_exceeded = (kd_control_trace.kdc_storage_used >= kd_buffer_trace.kdb_storage_threshold);
2208
2209 lck_spin_unlock(&kd_wait_lock);
2210 ml_set_interrupts_enabled(s);
2211
2212 ktrace_lock();
2213
2214 return threshold_exceeded;
2215 }
2216
2217 /*
2218 * Wakeup a thread waiting using `kdbg_wait` if there are at least
2219 * `kd_buffer_trace.kdb_storage_threshold` storage units in use.
2220 */
2221 static void
kdbg_wakeup(void)2222 kdbg_wakeup(void)
2223 {
2224 bool need_kds_wakeup = false;
2225
2226 /*
2227 * Try to take the lock here to synchronize with the waiter entering
2228 * the blocked state. Use the try mode to prevent deadlocks caused by
2229 * re-entering this routine due to various trace points triggered in the
2230 * lck_spin_sleep_xxxx routines used to actually enter one of our 2 wait
2231 * conditions. No problem if we fail, there will be lots of additional
2232 * events coming in that will eventually succeed in grabbing this lock.
2233 */
2234 bool s = ml_set_interrupts_enabled(false);
2235
2236 if (lck_spin_try_lock(&kd_wait_lock)) {
2237 if (kd_waiter &&
2238 (kd_control_trace.kdc_storage_used >= kd_buffer_trace.kdb_storage_threshold)) {
2239 kd_waiter = 0;
2240 need_kds_wakeup = true;
2241 }
2242 lck_spin_unlock(&kd_wait_lock);
2243 }
2244
2245 ml_set_interrupts_enabled(s);
2246
2247 if (need_kds_wakeup == true) {
2248 wakeup(&kd_waiter);
2249 }
2250 }
2251
2252 static int
_read_merged_trace_events(user_addr_t buffer,size_t * number,vnode_t vp,vfs_context_t ctx,bool chunk)2253 _read_merged_trace_events(user_addr_t buffer, size_t *number, vnode_t vp,
2254 vfs_context_t ctx, bool chunk)
2255 {
2256 ktrace_assert_lock_held();
2257 size_t count = *number / sizeof(kd_buf);
2258 if (count == 0 || !(kd_control_trace.kdc_flags & KDBG_BUFINIT) ||
2259 kd_buffer_trace.kdcopybuf == 0) {
2260 *number = 0;
2261 return EINVAL;
2262 }
2263
2264 // Before merging, make sure coprocessors have provided up-to-date events.
2265 _coproc_list_callback(KD_CALLBACK_SYNC_FLUSH, NULL);
2266 return kernel_debug_read(&kd_control_trace, &kd_buffer_trace, buffer,
2267 number, vp, ctx, chunk);
2268 }
2269
2270 struct event_chunk_header {
2271 uint32_t tag;
2272 uint32_t sub_tag;
2273 uint64_t length;
2274 uint64_t future_events_timestamp;
2275 };
2276
2277 static int
_write_event_chunk_header(user_addr_t udst,vnode_t vp,vfs_context_t ctx,uint64_t length)2278 _write_event_chunk_header(user_addr_t udst, vnode_t vp, vfs_context_t ctx,
2279 uint64_t length)
2280 {
2281 struct event_chunk_header header = {
2282 .tag = V3_RAW_EVENTS,
2283 .sub_tag = 1,
2284 .length = length,
2285 };
2286
2287 if (vp) {
2288 assert(udst == USER_ADDR_NULL);
2289 assert(ctx != NULL);
2290 int error = kdbg_write_to_vnode((caddr_t)&header, sizeof(header), vp,
2291 ctx, RAW_file_offset);
2292 if (0 == error) {
2293 RAW_file_offset += sizeof(header);
2294 }
2295 return error;
2296 } else {
2297 assert(udst != USER_ADDR_NULL);
2298 return copyout(&header, udst, sizeof(header));
2299 }
2300 }
2301
2302 int
kernel_debug_trace_write_to_file(user_addr_t * buffer,size_t * number,size_t * count,size_t tempbuf_number,vnode_t vp,vfs_context_t ctx,bool chunk)2303 kernel_debug_trace_write_to_file(user_addr_t *buffer, size_t *number,
2304 size_t *count, size_t tempbuf_number, vnode_t vp, vfs_context_t ctx,
2305 bool chunk)
2306 {
2307 int error = 0;
2308
2309 if (chunk) {
2310 error = _write_event_chunk_header(*buffer, vp, ctx,
2311 tempbuf_number * sizeof(kd_buf));
2312 if (error) {
2313 return error;
2314 }
2315 if (buffer) {
2316 *buffer += sizeof(struct event_chunk_header);
2317 }
2318
2319 assert(*count >= sizeof(struct event_chunk_header));
2320 *count -= sizeof(struct event_chunk_header);
2321 *number += sizeof(struct event_chunk_header);
2322 }
2323 if (vp) {
2324 size_t write_size = tempbuf_number * sizeof(kd_buf);
2325 error = kdbg_write_to_vnode((caddr_t)kd_buffer_trace.kdcopybuf,
2326 write_size, vp, ctx, RAW_file_offset);
2327 if (!error) {
2328 RAW_file_offset += write_size;
2329 }
2330
2331 if (RAW_file_written >= RAW_FLUSH_SIZE) {
2332 error = VNOP_FSYNC(vp, MNT_NOWAIT, ctx);
2333
2334 RAW_file_written = 0;
2335 }
2336 } else {
2337 error = copyout(kd_buffer_trace.kdcopybuf, *buffer, tempbuf_number * sizeof(kd_buf));
2338 *buffer += (tempbuf_number * sizeof(kd_buf));
2339 }
2340
2341 return error;
2342 }
2343
2344 #pragma mark - User space interface
2345
2346 static int
_kd_sysctl_internal(int op,int value,user_addr_t where,size_t * sizep)2347 _kd_sysctl_internal(int op, int value, user_addr_t where, size_t *sizep)
2348 {
2349 size_t size = *sizep;
2350 kd_regtype kd_Reg;
2351 proc_t p;
2352
2353 bool read_only = (op == KERN_KDGETBUF || op == KERN_KDREADCURTHRMAP);
2354 int perm_error = read_only ? ktrace_read_check() :
2355 ktrace_configure(KTRACE_KDEBUG);
2356 if (perm_error != 0) {
2357 return perm_error;
2358 }
2359
2360 switch (op) {
2361 case KERN_KDGETBUF:;
2362 pid_t owning_pid = ktrace_get_owning_pid();
2363 kbufinfo_t info = {
2364 .nkdbufs = kd_buffer_trace.kdb_event_count,
2365 .nkdthreads = (int)MIN(kd_mapcount, INT_MAX),
2366 .nolog = kd_control_trace.kdc_emit == KDEMIT_DISABLE,
2367 .flags = kd_control_trace.kdc_flags | kd_control_trace.kdc_live_flags,
2368 .bufid = owning_pid ?: -1,
2369 };
2370 #if defined(__LP64__)
2371 info.flags |= KDBG_LP64;
2372 #endif // defined(__LP64__)
2373
2374 size = MIN(size, sizeof(info));
2375 return copyout(&info, where, size);
2376 case KERN_KDREADCURTHRMAP:
2377 return kdbg_readcurthrmap(where, sizep);
2378 case KERN_KDEFLAGS:
2379 value &= KDBG_USERFLAGS;
2380 kd_control_trace.kdc_flags |= value;
2381 return 0;
2382 case KERN_KDDFLAGS:
2383 value &= KDBG_USERFLAGS;
2384 kd_control_trace.kdc_flags &= ~value;
2385 return 0;
2386 case KERN_KDENABLE:
2387 if (value) {
2388 if (!(kd_control_trace.kdc_flags & KDBG_BUFINIT) ||
2389 !(value == KDEBUG_ENABLE_TRACE || value == KDEBUG_ENABLE_PPT)) {
2390 return EINVAL;
2391 }
2392 _threadmap_init();
2393
2394 kdbg_set_tracing_enabled(true, value);
2395 } else {
2396 if (!kdebug_enable) {
2397 return 0;
2398 }
2399
2400 kernel_debug_disable();
2401 }
2402 return 0;
2403 case KERN_KDSETBUF:
2404 kdbg_set_nkdbufs_trace(value);
2405 return 0;
2406 case KERN_KDSETUP:
2407 return kdbg_reinit(EXTRA_COPROC_COUNT);
2408 case KERN_KDREMOVE:
2409 ktrace_reset(KTRACE_KDEBUG);
2410 return 0;
2411 case KERN_KDSETREG:
2412 if (size < sizeof(kd_regtype)) {
2413 return EINVAL;
2414 }
2415 if (copyin(where, &kd_Reg, sizeof(kd_regtype))) {
2416 return EINVAL;
2417 }
2418 return kdbg_setreg(&kd_Reg);
2419 case KERN_KDGETREG:
2420 return EINVAL;
2421 case KERN_KDREADTR:
2422 return _read_merged_trace_events(where, sizep, NULL, NULL, false);
2423 case KERN_KDWRITETR:
2424 case KERN_KDWRITETR_V3:
2425 case KERN_KDWRITEMAP: {
2426 struct vfs_context context;
2427 struct fileproc *fp;
2428 size_t number;
2429 vnode_t vp;
2430 int fd;
2431 int ret = 0;
2432
2433 if (op == KERN_KDWRITETR || op == KERN_KDWRITETR_V3) {
2434 (void)kdbg_wait(size);
2435 // Re-check whether this process can configure ktrace, since waiting
2436 // will drop the ktrace lock.
2437 int no_longer_owner_error = ktrace_configure(KTRACE_KDEBUG);
2438 if (no_longer_owner_error != 0) {
2439 return no_longer_owner_error;
2440 }
2441 }
2442
2443 p = current_proc();
2444 fd = value;
2445
2446 if (fp_get_ftype(p, fd, DTYPE_VNODE, EBADF, &fp)) {
2447 return EBADF;
2448 }
2449
2450 vp = fp_get_data(fp);
2451 context.vc_thread = current_thread();
2452 context.vc_ucred = fp->fp_glob->fg_cred;
2453
2454 if ((ret = vnode_getwithref(vp)) == 0) {
2455 RAW_file_offset = fp->fp_glob->fg_offset;
2456 if (op == KERN_KDWRITETR || op == KERN_KDWRITETR_V3) {
2457 number = kd_buffer_trace.kdb_event_count * sizeof(kd_buf);
2458
2459 KDBG_RELEASE(TRACE_WRITING_EVENTS | DBG_FUNC_START);
2460 ret = _read_merged_trace_events(0, &number, vp, &context,
2461 op == KERN_KDWRITETR_V3);
2462 KDBG_RELEASE(TRACE_WRITING_EVENTS | DBG_FUNC_END, number);
2463
2464 *sizep = number;
2465 } else {
2466 number = kd_mapcount * sizeof(kd_threadmap);
2467 ret = kdbg_write_thread_map(vp, &context);
2468 }
2469 fp->fp_glob->fg_offset = RAW_file_offset;
2470 vnode_put(vp);
2471 }
2472 fp_drop(p, fd, fp, 0);
2473
2474 return ret;
2475 }
2476 case KERN_KDBUFWAIT:
2477 *sizep = kdbg_wait(size);
2478 return 0;
2479 case KERN_KDPIDTR:
2480 if (size < sizeof(kd_regtype)) {
2481 return EINVAL;
2482 }
2483 if (copyin(where, &kd_Reg, sizeof(kd_regtype))) {
2484 return EINVAL;
2485 }
2486 return kdbg_setpid(&kd_Reg);
2487 case KERN_KDPIDEX:
2488 if (size < sizeof(kd_regtype)) {
2489 return EINVAL;
2490 }
2491 if (copyin(where, &kd_Reg, sizeof(kd_regtype))) {
2492 return EINVAL;
2493 }
2494 return kdbg_setpidex(&kd_Reg);
2495 case KERN_KDCPUMAP:
2496 return _copyout_cpu_map(RAW_VERSION1, where, sizep);
2497 case KERN_KDCPUMAP_EXT:
2498 return _copyout_cpu_map(1, where, sizep);
2499 case KERN_KDTHRMAP:
2500 return kdbg_copyout_thread_map(where, sizep);
2501 case KERN_KDSET_TYPEFILTER:
2502 return kdbg_copyin_typefilter(where, size);
2503 case KERN_KDSET_EDM:
2504 return _copyin_event_disable_mask(where, size);
2505 case KERN_KDGET_EDM:
2506 return _copyout_event_disable_mask(where, size);
2507 #if DEVELOPMENT || DEBUG
2508 case KERN_KDTEST:
2509 return kdbg_test(size);
2510 #endif // DEVELOPMENT || DEBUG
2511
2512 default:
2513 return ENOTSUP;
2514 }
2515 }
2516
2517 static int
2518 kdebug_sysctl SYSCTL_HANDLER_ARGS
2519 {
2520 int *names = arg1;
2521 int name_count = arg2;
2522 user_addr_t udst = req->oldptr;
2523 size_t *usize = &req->oldlen;
2524 int value = 0;
2525
2526 if (name_count == 0) {
2527 return ENOTSUP;
2528 }
2529
2530 int op = names[0];
2531
2532 // Some operations have an argument stuffed into the next OID argument.
2533 switch (op) {
2534 case KERN_KDWRITETR:
2535 case KERN_KDWRITETR_V3:
2536 case KERN_KDWRITEMAP:
2537 case KERN_KDEFLAGS:
2538 case KERN_KDDFLAGS:
2539 case KERN_KDENABLE:
2540 case KERN_KDSETBUF:
2541 if (name_count < 2) {
2542 return EINVAL;
2543 }
2544 value = names[1];
2545 break;
2546 default:
2547 break;
2548 }
2549
2550 ktrace_lock();
2551 int ret = _kd_sysctl_internal(op, value, udst, usize);
2552 ktrace_unlock();
2553 if (0 == ret) {
2554 req->oldidx += req->oldlen;
2555 }
2556 return ret;
2557 }
2558 SYSCTL_PROC(_kern, KERN_KDEBUG, kdebug,
2559 CTLTYPE_NODE | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0, kdebug_sysctl, NULL, "");
2560
2561 #pragma mark - Tests
2562
2563 #if DEVELOPMENT || DEBUG
2564
2565 static int test_coproc = 0;
2566 static int sync_flush_coproc = 0;
2567
2568 #define KDEBUG_TEST_CODE(code) BSDDBG_CODE(DBG_BSD_KDEBUG_TEST, (code))
2569
2570 /*
2571 * A test IOP for the SYNC_FLUSH callback.
2572 */
2573
2574 static void
sync_flush_callback(void * __unused context,kd_callback_type reason,void * __unused arg)2575 sync_flush_callback(void * __unused context, kd_callback_type reason,
2576 void * __unused arg)
2577 {
2578 assert(sync_flush_coproc > 0);
2579
2580 if (reason == KD_CALLBACK_SYNC_FLUSH) {
2581 kernel_debug_enter(sync_flush_coproc, KDEBUG_TEST_CODE(0xff),
2582 kdebug_timestamp(), 0, 0, 0, 0, 0);
2583 }
2584 }
2585
2586 static struct kd_callback sync_flush_kdcb = {
2587 .func = sync_flush_callback,
2588 .iop_name = "test_sf",
2589 };
2590
2591 #define TEST_COPROC_CTX 0xabadcafe
2592
2593 static void
test_coproc_cb(__assert_only void * context,kd_callback_type __unused reason,void * __unused arg)2594 test_coproc_cb(__assert_only void *context, kd_callback_type __unused reason,
2595 void * __unused arg)
2596 {
2597 assert((uintptr_t)context == TEST_COPROC_CTX);
2598 }
2599
2600 static int
kdbg_test(size_t flavor)2601 kdbg_test(size_t flavor)
2602 {
2603 int code = 0;
2604 int dummy_iop = 0;
2605
2606 switch (flavor) {
2607 case KDTEST_KERNEL_MACROS:
2608 /* try each macro */
2609 KDBG(KDEBUG_TEST_CODE(code)); code++;
2610 KDBG(KDEBUG_TEST_CODE(code), 1); code++;
2611 KDBG(KDEBUG_TEST_CODE(code), 1, 2); code++;
2612 KDBG(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
2613 KDBG(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
2614
2615 KDBG_RELEASE(KDEBUG_TEST_CODE(code)); code++;
2616 KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1); code++;
2617 KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1, 2); code++;
2618 KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
2619 KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
2620
2621 KDBG_FILTERED(KDEBUG_TEST_CODE(code)); code++;
2622 KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1); code++;
2623 KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1, 2); code++;
2624 KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
2625 KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
2626
2627 KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code)); code++;
2628 KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code), 1); code++;
2629 KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code), 1, 2); code++;
2630 KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
2631 KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
2632
2633 KDBG_DEBUG(KDEBUG_TEST_CODE(code)); code++;
2634 KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1); code++;
2635 KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1, 2); code++;
2636 KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
2637 KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
2638 break;
2639
2640 case KDTEST_OLD_TIMESTAMP:
2641 if (kd_control_trace.kdc_coprocs) {
2642 /* avoid the assertion in kernel_debug_enter for a valid IOP */
2643 dummy_iop = kd_control_trace.kdc_coprocs[0].cpu_id;
2644 }
2645
2646 /* ensure old timestamps are not emitted from kernel_debug_enter */
2647 kernel_debug_enter(dummy_iop, KDEBUG_TEST_CODE(code),
2648 100 /* very old timestamp */, 0, 0, 0, 0, 0);
2649 code++;
2650 kernel_debug_enter(dummy_iop, KDEBUG_TEST_CODE(code),
2651 kdebug_timestamp(), 0, 0, 0, 0, 0);
2652 code++;
2653 break;
2654
2655 case KDTEST_FUTURE_TIMESTAMP:
2656 if (kd_control_trace.kdc_coprocs) {
2657 dummy_iop = kd_control_trace.kdc_coprocs[0].cpu_id;
2658 }
2659 kernel_debug_enter(dummy_iop, KDEBUG_TEST_CODE(code),
2660 kdebug_timestamp() * 2 /* !!! */, 0, 0, 0, 0, 0);
2661 break;
2662
2663 case KDTEST_SETUP_IOP:
2664 if (!sync_flush_coproc) {
2665 ktrace_unlock();
2666 int new_sync_flush_coproc = kernel_debug_register_callback(
2667 sync_flush_kdcb);
2668 assert(new_sync_flush_coproc > 0);
2669 ktrace_lock();
2670 if (!sync_flush_coproc) {
2671 sync_flush_coproc = new_sync_flush_coproc;
2672 }
2673 }
2674 break;
2675
2676 case KDTEST_SETUP_COPROCESSOR:
2677 if (!test_coproc) {
2678 ktrace_unlock();
2679 int new_test_coproc = kdebug_register_coproc("test_coproc",
2680 KDCP_CONTINUOUS_TIME, test_coproc_cb, (void *)TEST_COPROC_CTX);
2681 assert(new_test_coproc > 0);
2682 ktrace_lock();
2683 if (!test_coproc) {
2684 test_coproc = new_test_coproc;
2685 }
2686 }
2687 break;
2688
2689 case KDTEST_ABSOLUTE_TIMESTAMP:;
2690 uint64_t atime = mach_absolute_time();
2691 kernel_debug_enter(sync_flush_coproc, KDEBUG_TEST_CODE(0),
2692 atime, (uintptr_t)atime, (uintptr_t)(atime >> 32), 0, 0, 0);
2693 break;
2694
2695 case KDTEST_CONTINUOUS_TIMESTAMP:;
2696 uint64_t ctime = mach_continuous_time();
2697 kernel_debug_enter(test_coproc, KDEBUG_TEST_CODE(1),
2698 ctime, (uintptr_t)ctime, (uintptr_t)(ctime >> 32), 0, 0, 0);
2699 break;
2700
2701 case KDTEST_PAST_EVENT:;
2702 uint64_t old_time = 1;
2703 kernel_debug_enter(test_coproc, KDEBUG_TEST_CODE(1), old_time, 0, 0, 0,
2704 0, 0);
2705 kernel_debug_enter(test_coproc, KDEBUG_TEST_CODE(1), kdebug_timestamp(),
2706 0, 0, 0, 0, 0);
2707 break;
2708
2709 default:
2710 return ENOTSUP;
2711 }
2712
2713 return 0;
2714 }
2715
2716 #undef KDEBUG_TEST_CODE
2717
2718 #endif /* DEVELOPMENT || DEBUG */
2719
2720 static void
_deferred_coproc_notify(mpsc_queue_chain_t e,mpsc_daemon_queue_t queue __unused)2721 _deferred_coproc_notify(mpsc_queue_chain_t e, mpsc_daemon_queue_t queue __unused)
2722 {
2723 struct kd_coproc *coproc = mpsc_queue_element(e, struct kd_coproc, chain);
2724 if (kd_control_trace.kdc_emit == KDEMIT_TYPEFILTER) {
2725 coproc->callback.func(coproc->callback.context,
2726 KD_CALLBACK_TYPEFILTER_CHANGED, kdbg_typefilter);
2727 }
2728 if (kdebug_enable) {
2729 coproc->callback.func(coproc->callback.context,
2730 KD_CALLBACK_KDEBUG_ENABLED, kdbg_typefilter);
2731 }
2732 }
2733
2734 void
kdebug_init(unsigned int n_events,char * filter_desc,enum kdebug_opts opts)2735 kdebug_init(unsigned int n_events, char *filter_desc, enum kdebug_opts opts)
2736 {
2737 assert(filter_desc != NULL);
2738
2739 kdbg_typefilter = typefilter_create();
2740 assert(kdbg_typefilter != NULL);
2741 kdbg_typefilter_memory_entry = typefilter_create_memory_entry(kdbg_typefilter);
2742 assert(kdbg_typefilter_memory_entry != MACH_PORT_NULL);
2743
2744 (void)mpsc_daemon_queue_init_with_thread_call(&_coproc_notify_queue,
2745 _deferred_coproc_notify, THREAD_CALL_PRIORITY_KERNEL,
2746 MPSC_DAEMON_INIT_NONE);
2747
2748 kdebug_trace_start(n_events, filter_desc, opts);
2749 }
2750
2751 static void
kdbg_set_typefilter_string(const char * filter_desc)2752 kdbg_set_typefilter_string(const char *filter_desc)
2753 {
2754 char *end = NULL;
2755
2756 ktrace_assert_lock_held();
2757
2758 assert(filter_desc != NULL);
2759
2760 typefilter_reject_all(kdbg_typefilter);
2761 typefilter_allow_class(kdbg_typefilter, DBG_TRACE);
2762
2763 /* if the filter description starts with a number, assume it's a csc */
2764 if (filter_desc[0] >= '0' && filter_desc[0] <= '9') {
2765 unsigned long csc = strtoul(filter_desc, NULL, 0);
2766 if (filter_desc != end && csc <= KDBG_CSC_MAX) {
2767 typefilter_allow_csc(kdbg_typefilter, (uint16_t)csc);
2768 }
2769 return;
2770 }
2771
2772 while (filter_desc[0] != '\0') {
2773 unsigned long allow_value;
2774
2775 char filter_type = filter_desc[0];
2776 if (filter_type != 'C' && filter_type != 'S') {
2777 printf("kdebug: unexpected filter type `%c'\n", filter_type);
2778 return;
2779 }
2780 filter_desc++;
2781
2782 allow_value = strtoul(filter_desc, &end, 0);
2783 if (filter_desc == end) {
2784 printf("kdebug: cannot parse `%s' as integer\n", filter_desc);
2785 return;
2786 }
2787
2788 switch (filter_type) {
2789 case 'C':
2790 if (allow_value > KDBG_CLASS_MAX) {
2791 printf("kdebug: class 0x%lx is invalid\n", allow_value);
2792 return;
2793 }
2794 printf("kdebug: C 0x%lx\n", allow_value);
2795 typefilter_allow_class(kdbg_typefilter, (uint8_t)allow_value);
2796 break;
2797 case 'S':
2798 if (allow_value > KDBG_CSC_MAX) {
2799 printf("kdebug: class-subclass 0x%lx is invalid\n", allow_value);
2800 return;
2801 }
2802 printf("kdebug: S 0x%lx\n", allow_value);
2803 typefilter_allow_csc(kdbg_typefilter, (uint16_t)allow_value);
2804 break;
2805 default:
2806 __builtin_unreachable();
2807 }
2808
2809 /* advance to next filter entry */
2810 filter_desc = end;
2811 if (filter_desc[0] == ',') {
2812 filter_desc++;
2813 }
2814 }
2815 }
2816
2817 uint64_t
kdebug_wake(void)2818 kdebug_wake(void)
2819 {
2820 if (!wake_nkdbufs) {
2821 return 0;
2822 }
2823 uint64_t start = mach_absolute_time();
2824 kdebug_trace_start(wake_nkdbufs, NULL, trace_wrap ? KDOPT_WRAPPING : 0);
2825 return mach_absolute_time() - start;
2826 }
2827
2828 /*
2829 * This function is meant to be called from the bootstrap thread or kdebug_wake.
2830 */
2831 void
kdebug_trace_start(unsigned int n_events,const char * filter_desc,enum kdebug_opts opts)2832 kdebug_trace_start(unsigned int n_events, const char *filter_desc,
2833 enum kdebug_opts opts)
2834 {
2835 if (!n_events) {
2836 kd_early_done = true;
2837 return;
2838 }
2839
2840 ktrace_start_single_threaded();
2841
2842 ktrace_kernel_configure(KTRACE_KDEBUG);
2843
2844 kdbg_set_nkdbufs_trace(n_events);
2845
2846 kernel_debug_string_early("start_kern_tracing");
2847
2848 int error = kdbg_reinit(EXTRA_COPROC_COUNT_BOOT);
2849 if (error != 0) {
2850 printf("kdebug: allocation failed, kernel tracing not started: %d\n",
2851 error);
2852 kd_early_done = true;
2853 goto out;
2854 }
2855
2856 /*
2857 * Wrapping is disabled because boot and wake tracing is interested in
2858 * the earliest events, at the expense of later ones.
2859 */
2860 if ((opts & KDOPT_WRAPPING) == 0) {
2861 kd_control_trace.kdc_live_flags |= KDBG_NOWRAP;
2862 }
2863
2864 if (filter_desc && filter_desc[0] != '\0') {
2865 kdbg_set_typefilter_string(filter_desc);
2866 kdbg_enable_typefilter();
2867 }
2868
2869 /*
2870 * Hold off interrupts between getting a thread map and enabling trace
2871 * and until the early traces are recorded.
2872 */
2873 bool s = ml_set_interrupts_enabled(false);
2874
2875 if (!(opts & KDOPT_ATBOOT)) {
2876 _threadmap_init();
2877 }
2878
2879 kdbg_set_tracing_enabled(true, KDEBUG_ENABLE_TRACE);
2880
2881 if ((opts & KDOPT_ATBOOT)) {
2882 /*
2883 * Transfer all very early events from the static buffer into the real
2884 * buffers.
2885 */
2886 kernel_debug_early_end();
2887 }
2888
2889 ml_set_interrupts_enabled(s);
2890
2891 printf("kernel tracing started with %u events, filter = %s\n", n_events,
2892 filter_desc ?: "none");
2893
2894 out:
2895 ktrace_end_single_threaded();
2896 }
2897
2898 void
kdbg_dump_trace_to_file(const char * filename,bool reenable)2899 kdbg_dump_trace_to_file(const char *filename, bool reenable)
2900 {
2901 vfs_context_t ctx;
2902 vnode_t vp;
2903 size_t write_size;
2904 int ret;
2905 int reenable_trace = 0;
2906
2907 ktrace_lock();
2908
2909 if (!(kdebug_enable & KDEBUG_ENABLE_TRACE)) {
2910 goto out;
2911 }
2912
2913 if (ktrace_get_owning_pid() != 0) {
2914 /*
2915 * Another process owns ktrace and is still active, disable tracing to
2916 * prevent wrapping.
2917 */
2918 kdebug_enable = 0;
2919 kd_control_trace.enabled = 0;
2920 commpage_update_kdebug_state();
2921 goto out;
2922 }
2923
2924 KDBG_RELEASE(TRACE_WRITING_EVENTS | DBG_FUNC_START);
2925
2926 reenable_trace = reenable ? kdebug_enable : 0;
2927 kdebug_enable = 0;
2928 kd_control_trace.enabled = 0;
2929 commpage_update_kdebug_state();
2930
2931 ctx = vfs_context_kernel();
2932
2933 if (vnode_open(filename, (O_CREAT | FWRITE | O_NOFOLLOW), 0600, 0, &vp, ctx)) {
2934 goto out;
2935 }
2936
2937 kdbg_write_thread_map(vp, ctx);
2938
2939 write_size = kd_buffer_trace.kdb_event_count * sizeof(kd_buf);
2940 ret = _read_merged_trace_events(0, &write_size, vp, ctx, false);
2941 if (ret) {
2942 goto out_close;
2943 }
2944
2945 /*
2946 * Wait to synchronize the file to capture the I/O in the
2947 * TRACE_WRITING_EVENTS interval.
2948 */
2949 ret = VNOP_FSYNC(vp, MNT_WAIT, ctx);
2950 if (ret == KERN_SUCCESS) {
2951 ret = VNOP_IOCTL(vp, F_FULLFSYNC, (caddr_t)NULL, 0, ctx);
2952 }
2953
2954 /*
2955 * Balance the starting TRACE_WRITING_EVENTS tracepoint manually.
2956 */
2957 kd_buf end_event = {
2958 .debugid = TRACE_WRITING_EVENTS | DBG_FUNC_END,
2959 .arg1 = write_size,
2960 .arg2 = ret,
2961 .arg5 = (kd_buf_argtype)thread_tid(current_thread()),
2962 };
2963 kdbg_set_timestamp_and_cpu(&end_event, kdebug_timestamp(),
2964 cpu_number());
2965
2966 /* this is best effort -- ignore any errors */
2967 (void)kdbg_write_to_vnode((caddr_t)&end_event, sizeof(kd_buf), vp, ctx,
2968 RAW_file_offset);
2969
2970 out_close:
2971 vnode_close(vp, FWRITE, ctx);
2972 sync(current_proc(), (void *)NULL, (int *)NULL);
2973
2974 out:
2975 if (reenable_trace != 0) {
2976 kdebug_enable = reenable_trace;
2977 kd_control_trace.enabled = 1;
2978 commpage_update_kdebug_state();
2979 }
2980
2981 ktrace_unlock();
2982 }
2983
2984 SYSCTL_NODE(_kern, OID_AUTO, kdbg, CTLFLAG_RD | CTLFLAG_LOCKED, 0,
2985 "kdbg");
2986
2987 SYSCTL_INT(_kern_kdbg, OID_AUTO, debug,
2988 CTLFLAG_RW | CTLFLAG_LOCKED,
2989 &kdbg_debug, 0, "Set kdebug debug mode");
2990
2991 SYSCTL_QUAD(_kern_kdbg, OID_AUTO, oldest_time,
2992 CTLTYPE_QUAD | CTLFLAG_RD | CTLFLAG_LOCKED,
2993 &kd_control_trace.kdc_oldest_time,
2994 "Find the oldest timestamp still in trace");
2995