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