xref: /xnu-8796.101.5/bsd/kern/kdebug.c (revision aca3beaa3dfbd42498b42c5e5ce20a938e6554e5)
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);
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 (32)
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 		kdbg_wakeup();
943 	}
944 }
945 
946 // Returns true if debugid should only be traced from the kernel.
947 static int
_kernel_only_event(uint32_t debugid)948 _kernel_only_event(uint32_t debugid)
949 {
950 	return KDBG_EXTRACT_CLASS(debugid) == DBG_TRACE;
951 }
952 
953 /*
954  * Support syscall SYS_kdebug_typefilter.
955  */
956 int
kdebug_typefilter(__unused struct proc * p,struct kdebug_typefilter_args * uap,__unused int * retval)957 kdebug_typefilter(__unused struct proc* p, struct kdebug_typefilter_args* uap,
958     __unused int *retval)
959 {
960 	if (uap->addr == USER_ADDR_NULL || uap->size == USER_ADDR_NULL) {
961 		return EINVAL;
962 	}
963 
964 	mach_vm_offset_t user_addr = 0;
965 	vm_map_t user_map = current_map();
966 	const bool copy = false;
967 	kern_return_t kr = mach_vm_map_kernel(user_map, &user_addr,
968 	    TYPEFILTER_ALLOC_SIZE, 0, VM_MAP_KERNEL_FLAGS_ANYWHERE(),
969 	    kdbg_typefilter_memory_entry, 0, copy,
970 	    VM_PROT_READ, VM_PROT_READ, VM_INHERIT_SHARE);
971 	if (kr != KERN_SUCCESS) {
972 		return mach_to_bsd_errno(kr);
973 	}
974 
975 	vm_size_t user_ptr_size = vm_map_is_64bit(user_map) ? 8 : 4;
976 	int error = copyout((void *)&user_addr, uap->addr, user_ptr_size);
977 	if (error != 0) {
978 		mach_vm_deallocate(user_map, user_addr, TYPEFILTER_ALLOC_SIZE);
979 	}
980 	return error;
981 }
982 
983 // Support SYS_kdebug_trace.
984 int
kdebug_trace(struct proc * p,struct kdebug_trace_args * uap,int32_t * retval)985 kdebug_trace(struct proc *p, struct kdebug_trace_args *uap, int32_t *retval)
986 {
987 	struct kdebug_trace64_args uap64 = {
988 		.code = uap->code,
989 		.arg1 = uap->arg1,
990 		.arg2 = uap->arg2,
991 		.arg3 = uap->arg3,
992 		.arg4 = uap->arg4,
993 	};
994 	return kdebug_trace64(p, &uap64, retval);
995 }
996 
997 // Support kdebug_trace(2).  64-bit arguments on K32 will get truncated
998 // to fit in the 32-bit record format.
999 //
1000 // It is intentional that error conditions are not checked until kdebug is
1001 // enabled. This is to match the userspace wrapper behavior, which is optimizing
1002 // for non-error case performance.
1003 int
kdebug_trace64(__unused struct proc * p,struct kdebug_trace64_args * uap,__unused int32_t * retval)1004 kdebug_trace64(__unused struct proc *p, struct kdebug_trace64_args *uap,
1005     __unused int32_t *retval)
1006 {
1007 	if (__probable(kdebug_enable == 0)) {
1008 		return 0;
1009 	}
1010 	if (_kernel_only_event(uap->code)) {
1011 		return EPERM;
1012 	}
1013 	kernel_debug_internal(uap->code, (uintptr_t)uap->arg1,
1014 	    (uintptr_t)uap->arg2, (uintptr_t)uap->arg3, (uintptr_t)uap->arg4,
1015 	    (uintptr_t)thread_tid(current_thread()), 0);
1016 	return 0;
1017 }
1018 
1019 /*
1020  * Adding enough padding to contain a full tracepoint for the last
1021  * portion of the string greatly simplifies the logic of splitting the
1022  * string between tracepoints.  Full tracepoints can be generated using
1023  * the buffer itself, without having to manually add zeros to pad the
1024  * arguments.
1025  */
1026 
1027 /* 2 string args in first tracepoint and 9 string data tracepoints */
1028 #define STR_BUF_ARGS (2 + (32 * 4))
1029 /* times the size of each arg on K64 */
1030 #define MAX_STR_LEN  (STR_BUF_ARGS * sizeof(uint64_t))
1031 /* on K32, ending straddles a tracepoint, so reserve blanks */
1032 #define STR_BUF_SIZE (MAX_STR_LEN + (2 * sizeof(uint32_t)))
1033 
1034 /*
1035  * This function does no error checking and assumes that it is called with
1036  * the correct arguments, including that the buffer pointed to by str is at
1037  * least STR_BUF_SIZE bytes.  However, str must be aligned to word-size and
1038  * be NUL-terminated.  In cases where a string can fit evenly into a final
1039  * tracepoint without its NUL-terminator, this function will not end those
1040  * strings with a NUL in trace.  It's up to clients to look at the function
1041  * qualifier for DBG_FUNC_END in this case, to end the string.
1042  */
1043 static uint64_t
kernel_debug_string_internal(uint32_t debugid,uint64_t str_id,void * vstr,size_t str_len)1044 kernel_debug_string_internal(uint32_t debugid, uint64_t str_id, void *vstr,
1045     size_t str_len)
1046 {
1047 	/* str must be word-aligned */
1048 	uintptr_t *str = vstr;
1049 	size_t written = 0;
1050 	uintptr_t thread_id;
1051 	int i;
1052 	uint32_t trace_debugid = TRACEDBG_CODE(DBG_TRACE_STRING,
1053 	    TRACE_STRING_GLOBAL);
1054 
1055 	thread_id = (uintptr_t)thread_tid(current_thread());
1056 
1057 	/* if the ID is being invalidated, just emit that */
1058 	if (str_id != 0 && str_len == 0) {
1059 		kernel_debug_internal(trace_debugid | DBG_FUNC_START | DBG_FUNC_END,
1060 		    (uintptr_t)debugid, (uintptr_t)str_id, 0, 0, thread_id, 0);
1061 		return str_id;
1062 	}
1063 
1064 	/* generate an ID, if necessary */
1065 	if (str_id == 0) {
1066 		str_id = OSIncrementAtomic64((SInt64 *)&g_curr_str_id);
1067 		str_id = (str_id & STR_ID_MASK) | g_str_id_signature;
1068 	}
1069 
1070 	trace_debugid |= DBG_FUNC_START;
1071 	/* string can fit in a single tracepoint */
1072 	if (str_len <= (2 * sizeof(uintptr_t))) {
1073 		trace_debugid |= DBG_FUNC_END;
1074 	}
1075 
1076 	kernel_debug_internal(trace_debugid, (uintptr_t)debugid, (uintptr_t)str_id,
1077 	    str[0], str[1], thread_id, 0);
1078 
1079 	trace_debugid &= KDBG_EVENTID_MASK;
1080 	i = 2;
1081 	written += 2 * sizeof(uintptr_t);
1082 
1083 	for (; written < str_len; i += 4, written += 4 * sizeof(uintptr_t)) {
1084 		if ((written + (4 * sizeof(uintptr_t))) >= str_len) {
1085 			trace_debugid |= DBG_FUNC_END;
1086 		}
1087 		kernel_debug_internal(trace_debugid, str[i],
1088 		    str[i + 1],
1089 		    str[i + 2],
1090 		    str[i + 3], thread_id, 0);
1091 	}
1092 
1093 	return str_id;
1094 }
1095 
1096 /*
1097  * Returns true if the current process can emit events, and false otherwise.
1098  * Trace system and scheduling events circumvent this check, as do events
1099  * emitted in interrupt context.
1100  */
1101 static bool
kdebug_current_proc_enabled(uint32_t debugid)1102 kdebug_current_proc_enabled(uint32_t debugid)
1103 {
1104 	/* can't determine current process in interrupt context */
1105 	if (ml_at_interrupt_context()) {
1106 		return true;
1107 	}
1108 
1109 	/* always emit trace system and scheduling events */
1110 	if ((KDBG_EXTRACT_CLASS(debugid) == DBG_TRACE ||
1111 	    (debugid & KDBG_CSC_MASK) == MACHDBG_CODE(DBG_MACH_SCHED, 0))) {
1112 		return true;
1113 	}
1114 
1115 	if (kd_control_trace.kdc_flags & KDBG_PIDCHECK) {
1116 		proc_t cur_proc = kdebug_current_proc_unsafe();
1117 
1118 		/* only the process with the kdebug bit set is allowed */
1119 		if (cur_proc && !(cur_proc->p_kdebug)) {
1120 			return false;
1121 		}
1122 	} else if (kd_control_trace.kdc_flags & KDBG_PIDEXCLUDE) {
1123 		proc_t cur_proc = kdebug_current_proc_unsafe();
1124 
1125 		/* every process except the one with the kdebug bit set is allowed */
1126 		if (cur_proc && cur_proc->p_kdebug) {
1127 			return false;
1128 		}
1129 	}
1130 
1131 	return true;
1132 }
1133 
1134 bool
kdebug_debugid_enabled(uint32_t debugid)1135 kdebug_debugid_enabled(uint32_t debugid)
1136 {
1137 	return _should_emit_debugid(kd_control_trace.kdc_emit, debugid);
1138 }
1139 
1140 bool
kdebug_debugid_explicitly_enabled(uint32_t debugid)1141 kdebug_debugid_explicitly_enabled(uint32_t debugid)
1142 {
1143 	if (kd_control_trace.kdc_flags & KDBG_TYPEFILTER_CHECK) {
1144 		return typefilter_is_debugid_allowed(kdbg_typefilter, debugid);
1145 	} else if (KDBG_EXTRACT_CLASS(debugid) == DBG_TRACE) {
1146 		return true;
1147 	} else if (kd_control_trace.kdc_flags & KDBG_RANGECHECK) {
1148 		if (debugid < kdlog_beg || debugid > kdlog_end) {
1149 			return false;
1150 		}
1151 	} else if (kd_control_trace.kdc_flags & KDBG_VALCHECK) {
1152 		if ((debugid & KDBG_EVENTID_MASK) != kdlog_value1 &&
1153 		    (debugid & KDBG_EVENTID_MASK) != kdlog_value2 &&
1154 		    (debugid & KDBG_EVENTID_MASK) != kdlog_value3 &&
1155 		    (debugid & KDBG_EVENTID_MASK) != kdlog_value4) {
1156 			return false;
1157 		}
1158 	}
1159 
1160 	return true;
1161 }
1162 
1163 /*
1164  * Returns 0 if a string can be traced with these arguments.  Returns errno
1165  * value if error occurred.
1166  */
1167 static errno_t
kdebug_check_trace_string(uint32_t debugid,uint64_t str_id)1168 kdebug_check_trace_string(uint32_t debugid, uint64_t str_id)
1169 {
1170 	if (debugid & (DBG_FUNC_START | DBG_FUNC_END)) {
1171 		return EINVAL;
1172 	}
1173 	if (_kernel_only_event(debugid)) {
1174 		return EPERM;
1175 	}
1176 	if (str_id != 0 && (str_id & STR_ID_SIG_MASK) != g_str_id_signature) {
1177 		return EINVAL;
1178 	}
1179 	return 0;
1180 }
1181 
1182 /*
1183  * Implementation of KPI kernel_debug_string.
1184  */
1185 int
kernel_debug_string(uint32_t debugid,uint64_t * str_id,const char * str)1186 kernel_debug_string(uint32_t debugid, uint64_t *str_id, const char *str)
1187 {
1188 	/* arguments to tracepoints must be word-aligned */
1189 	__attribute__((aligned(sizeof(uintptr_t)))) char str_buf[STR_BUF_SIZE];
1190 	static_assert(sizeof(str_buf) > MAX_STR_LEN);
1191 	vm_size_t len_copied;
1192 	int err;
1193 
1194 	assert(str_id);
1195 
1196 	if (__probable(kdebug_enable == 0)) {
1197 		return 0;
1198 	}
1199 
1200 	if (!kdebug_current_proc_enabled(debugid)) {
1201 		return 0;
1202 	}
1203 
1204 	if (!kdebug_debugid_enabled(debugid)) {
1205 		return 0;
1206 	}
1207 
1208 	if ((err = kdebug_check_trace_string(debugid, *str_id)) != 0) {
1209 		return err;
1210 	}
1211 
1212 	if (str == NULL) {
1213 		if (str_id == 0) {
1214 			return EINVAL;
1215 		}
1216 
1217 		*str_id = kernel_debug_string_internal(debugid, *str_id, NULL, 0);
1218 		return 0;
1219 	}
1220 
1221 	memset(str_buf, 0, sizeof(str_buf));
1222 	len_copied = strlcpy(str_buf, str, MAX_STR_LEN + 1);
1223 	*str_id = kernel_debug_string_internal(debugid, *str_id, str_buf,
1224 	    len_copied);
1225 	return 0;
1226 }
1227 
1228 // Support kdebug_trace_string(2).
1229 int
kdebug_trace_string(__unused struct proc * p,struct kdebug_trace_string_args * uap,uint64_t * retval)1230 kdebug_trace_string(__unused struct proc *p,
1231     struct kdebug_trace_string_args *uap,
1232     uint64_t *retval)
1233 {
1234 	__attribute__((aligned(sizeof(uintptr_t)))) char str_buf[STR_BUF_SIZE];
1235 	static_assert(sizeof(str_buf) > MAX_STR_LEN);
1236 	size_t len_copied;
1237 	int err;
1238 
1239 	if (__probable(kdebug_enable == 0)) {
1240 		return 0;
1241 	}
1242 
1243 	if (!kdebug_current_proc_enabled(uap->debugid)) {
1244 		return 0;
1245 	}
1246 
1247 	if (!kdebug_debugid_enabled(uap->debugid)) {
1248 		return 0;
1249 	}
1250 
1251 	if ((err = kdebug_check_trace_string(uap->debugid, uap->str_id)) != 0) {
1252 		return err;
1253 	}
1254 
1255 	if (uap->str == USER_ADDR_NULL) {
1256 		if (uap->str_id == 0) {
1257 			return EINVAL;
1258 		}
1259 
1260 		*retval = kernel_debug_string_internal(uap->debugid, uap->str_id,
1261 		    NULL, 0);
1262 		return 0;
1263 	}
1264 
1265 	memset(str_buf, 0, sizeof(str_buf));
1266 	err = copyinstr(uap->str, str_buf, MAX_STR_LEN + 1, &len_copied);
1267 
1268 	/* it's alright to truncate the string, so allow ENAMETOOLONG */
1269 	if (err == ENAMETOOLONG) {
1270 		str_buf[MAX_STR_LEN] = '\0';
1271 	} else if (err) {
1272 		return err;
1273 	}
1274 
1275 	if (len_copied <= 1) {
1276 		return EINVAL;
1277 	}
1278 
1279 	/* convert back to a length */
1280 	len_copied--;
1281 
1282 	*retval = kernel_debug_string_internal(uap->debugid, uap->str_id, str_buf,
1283 	    len_copied);
1284 	return 0;
1285 }
1286 
1287 int
kdbg_reinit(unsigned int extra_cpus)1288 kdbg_reinit(unsigned int extra_cpus)
1289 {
1290 	kernel_debug_disable();
1291 	// Wait for any event writers to see the disable status.
1292 	IOSleep(100);
1293 	delete_buffers_trace();
1294 
1295 	_clear_thread_map();
1296 	kd_control_trace.kdc_live_flags &= ~KDBG_WRAPPED;
1297 
1298 	RAW_file_offset = 0;
1299 	RAW_file_written = 0;
1300 
1301 	return create_buffers_trace(extra_cpus);
1302 }
1303 
1304 void
kdbg_trace_data(struct proc * proc,long * arg_pid,long * arg_uniqueid)1305 kdbg_trace_data(struct proc *proc, long *arg_pid, long *arg_uniqueid)
1306 {
1307 	if (proc) {
1308 		*arg_pid = proc_getpid(proc);
1309 		*arg_uniqueid = (long)proc_uniqueid(proc);
1310 		if ((uint64_t)*arg_uniqueid != proc_uniqueid(proc)) {
1311 			*arg_uniqueid = 0;
1312 		}
1313 	} else {
1314 		*arg_pid = 0;
1315 		*arg_uniqueid = 0;
1316 	}
1317 }
1318 
1319 void kdebug_proc_name_args(struct proc *proc, long args[static 4]);
1320 void
kdebug_proc_name_args(struct proc * proc,long args[static4])1321 kdebug_proc_name_args(struct proc *proc, long args[static 4])
1322 {
1323 	if (proc) {
1324 		strncpy((char *)args, proc_best_name(proc), 4 * sizeof(args[0]));
1325 	}
1326 }
1327 
1328 static void
_copy_ap_name(unsigned int cpuid,void * dst,size_t size)1329 _copy_ap_name(unsigned int cpuid, void *dst, size_t size)
1330 {
1331 	const char *name = "AP";
1332 #if defined(__arm64__)
1333 	const ml_topology_info_t *topology = ml_get_topology_info();
1334 	switch (topology->cpus[cpuid].cluster_type) {
1335 	case CLUSTER_TYPE_E:
1336 		name = "AP-E";
1337 		break;
1338 	case CLUSTER_TYPE_P:
1339 		name = "AP-P";
1340 		break;
1341 	default:
1342 		break;
1343 	}
1344 #else /* defined(__arm64__) */
1345 #pragma unused(cpuid)
1346 #endif /* !defined(__arm64__) */
1347 	strlcpy(dst, name, size);
1348 }
1349 
1350 // Write the specified `map_version` of CPU map to the `dst` buffer, using at
1351 // most `size` bytes.  Returns 0 on success and sets `size` to the number of
1352 // bytes written, and either ENOMEM or EINVAL on failure.
1353 //
1354 // If the value pointed to by `dst` is NULL, memory is allocated, and `size` is
1355 // adjusted to the allocated buffer's size.
1356 //
1357 // NB: `coprocs` is used to determine whether the stashed CPU map captured at
1358 // the start of tracing should be used.
1359 static errno_t
_copy_cpu_map(int map_version,void ** dst,size_t * size)1360 _copy_cpu_map(int map_version, void **dst, size_t *size)
1361 {
1362 	_coproc_lock();
1363 	struct kd_coproc *coprocs = kd_control_trace.kdc_coprocs;
1364 	unsigned int cpu_count = kd_control_trace.kdebug_cpus;
1365 	_coproc_unlock();
1366 
1367 	assert(cpu_count != 0);
1368 	assert(coprocs == NULL || coprocs[0].cpu_id + 1 == cpu_count);
1369 
1370 	bool ext = map_version != RAW_VERSION1;
1371 	size_t stride = ext ? sizeof(kd_cpumap_ext) : sizeof(kd_cpumap);
1372 
1373 	size_t size_needed = sizeof(kd_cpumap_header) + cpu_count * stride;
1374 	size_t size_avail = *size;
1375 	*size = size_needed;
1376 
1377 	if (*dst == NULL) {
1378 		kern_return_t alloc_ret = kmem_alloc(kernel_map, (vm_offset_t *)dst,
1379 		    (vm_size_t)size_needed, KMA_DATA | KMA_ZERO, VM_KERN_MEMORY_DIAG);
1380 		if (alloc_ret != KERN_SUCCESS) {
1381 			return ENOMEM;
1382 		}
1383 	} else if (size_avail < size_needed) {
1384 		return EINVAL;
1385 	}
1386 
1387 	kd_cpumap_header *header = *dst;
1388 	header->version_no = map_version;
1389 	header->cpu_count = cpu_count;
1390 
1391 	void *cpus = &header[1];
1392 	size_t name_size = ext ? sizeof(((kd_cpumap_ext *)NULL)->name) :
1393 	    sizeof(((kd_cpumap *)NULL)->name);
1394 
1395 	int i = cpu_count - 1;
1396 	for (struct kd_coproc *cur_coproc = coprocs; cur_coproc != NULL;
1397 	    cur_coproc = cur_coproc->next, i--) {
1398 		kd_cpumap_ext *cpu = (kd_cpumap_ext *)((uintptr_t)cpus + stride * i);
1399 		cpu->cpu_id = cur_coproc->cpu_id;
1400 		cpu->flags = KDBG_CPUMAP_IS_IOP;
1401 		strlcpy((void *)&cpu->name, cur_coproc->full_name, name_size);
1402 	}
1403 	for (; i >= 0; i--) {
1404 		kd_cpumap *cpu = (kd_cpumap *)((uintptr_t)cpus + stride * i);
1405 		cpu->cpu_id = i;
1406 		cpu->flags = 0;
1407 		_copy_ap_name(i, &cpu->name, name_size);
1408 	}
1409 
1410 	return 0;
1411 }
1412 
1413 static void
_threadmap_init(void)1414 _threadmap_init(void)
1415 {
1416 	ktrace_assert_lock_held();
1417 
1418 	if (kd_control_trace.kdc_flags & KDBG_MAPINIT) {
1419 		return;
1420 	}
1421 
1422 	kd_mapptr = _thread_map_create_live(0, &kd_mapsize, &kd_mapcount);
1423 
1424 	if (kd_mapptr) {
1425 		kd_control_trace.kdc_flags |= KDBG_MAPINIT;
1426 	}
1427 }
1428 
1429 struct kd_resolver {
1430 	kd_threadmap *krs_map;
1431 	vm_size_t krs_count;
1432 	vm_size_t krs_maxcount;
1433 };
1434 
1435 static int
_resolve_iterator(proc_t proc,void * opaque)1436 _resolve_iterator(proc_t proc, void *opaque)
1437 {
1438 	if (proc == kernproc) {
1439 		/* Handled specially as it lacks uthreads. */
1440 		return PROC_RETURNED;
1441 	}
1442 	struct kd_resolver *resolver = opaque;
1443 	struct uthread *uth = NULL;
1444 	const char *proc_name = proc_best_name(proc);
1445 	pid_t pid = proc_getpid(proc);
1446 
1447 	proc_lock(proc);
1448 	TAILQ_FOREACH(uth, &proc->p_uthlist, uu_list) {
1449 		if (resolver->krs_count >= resolver->krs_maxcount) {
1450 			break;
1451 		}
1452 		kd_threadmap *map = &resolver->krs_map[resolver->krs_count];
1453 		map->thread = (uintptr_t)uthread_tid(uth);
1454 		(void)strlcpy(map->command, proc_name, sizeof(map->command));
1455 		map->valid = pid;
1456 		resolver->krs_count++;
1457 	}
1458 	proc_unlock(proc);
1459 
1460 	bool done = resolver->krs_count >= resolver->krs_maxcount;
1461 	return done ? PROC_RETURNED_DONE : PROC_RETURNED;
1462 }
1463 
1464 static void
_resolve_kernel_task(thread_t thread,void * opaque)1465 _resolve_kernel_task(thread_t thread, void *opaque)
1466 {
1467 	struct kd_resolver *resolver = opaque;
1468 	if (resolver->krs_count >= resolver->krs_maxcount) {
1469 		return;
1470 	}
1471 	kd_threadmap *map = &resolver->krs_map[resolver->krs_count];
1472 	map->thread = (uintptr_t)thread_tid(thread);
1473 	(void)strlcpy(map->command, "kernel_task", sizeof(map->command));
1474 	map->valid = 1;
1475 	resolver->krs_count++;
1476 }
1477 
1478 static vm_size_t
_resolve_threads(kd_threadmap * map,vm_size_t nthreads)1479 _resolve_threads(kd_threadmap *map, vm_size_t nthreads)
1480 {
1481 	struct kd_resolver resolver = {
1482 		.krs_map = map, .krs_count = 0, .krs_maxcount = nthreads,
1483 	};
1484 
1485 	// Handle kernel_task specially, as it lacks uthreads.
1486 	extern void task_act_iterate_wth_args(task_t, void (*)(thread_t, void *),
1487 	    void *);
1488 	task_act_iterate_wth_args(kernel_task, _resolve_kernel_task, &resolver);
1489 	proc_iterate(PROC_ALLPROCLIST | PROC_NOWAITTRANS, _resolve_iterator,
1490 	    &resolver, NULL, NULL);
1491 	return resolver.krs_count;
1492 }
1493 
1494 static kd_threadmap *
_thread_map_create_live(size_t maxthreads,vm_size_t * mapsize,vm_size_t * mapcount)1495 _thread_map_create_live(size_t maxthreads, vm_size_t *mapsize,
1496     vm_size_t *mapcount)
1497 {
1498 	kd_threadmap *thread_map = NULL;
1499 
1500 	assert(mapsize != NULL);
1501 	assert(mapcount != NULL);
1502 
1503 	extern int threads_count;
1504 	vm_size_t nthreads = threads_count;
1505 
1506 	// Allow 25% more threads to be started while iterating processes.
1507 	if (os_add_overflow(nthreads, nthreads / 4, &nthreads)) {
1508 		return NULL;
1509 	}
1510 
1511 	*mapcount = nthreads;
1512 	if (os_mul_overflow(nthreads, sizeof(kd_threadmap), mapsize)) {
1513 		return NULL;
1514 	}
1515 
1516 	// Wait until the out-parameters have been filled with the needed size to
1517 	// do the bounds checking on the provided maximum.
1518 	if (maxthreads != 0 && maxthreads < nthreads) {
1519 		return NULL;
1520 	}
1521 
1522 	// This allocation can be too large for `Z_NOFAIL`.
1523 	thread_map = kalloc_data_tag(*mapsize, Z_WAITOK | Z_ZERO,
1524 	    VM_KERN_MEMORY_DIAG);
1525 	if (thread_map != NULL) {
1526 		*mapcount = _resolve_threads(thread_map, nthreads);
1527 	}
1528 	return thread_map;
1529 }
1530 
1531 static void
kdbg_clear(void)1532 kdbg_clear(void)
1533 {
1534 	kernel_debug_disable();
1535 	kdbg_disable_typefilter();
1536 
1537 	// Wait for any event writers to see the disable status.
1538 	IOSleep(100);
1539 
1540 	// Reset kdebug status for each process.
1541 	if (kd_control_trace.kdc_flags & (KDBG_PIDCHECK | KDBG_PIDEXCLUDE)) {
1542 		proc_list_lock();
1543 		proc_t p;
1544 		ALLPROC_FOREACH(p) {
1545 			p->p_kdebug = 0;
1546 		}
1547 		proc_list_unlock();
1548 	}
1549 
1550 	kd_control_trace.kdc_flags &= (unsigned int)~KDBG_CKTYPES;
1551 	kd_control_trace.kdc_flags &= ~(KDBG_RANGECHECK | KDBG_VALCHECK);
1552 	kd_control_trace.kdc_flags &= ~(KDBG_PIDCHECK | KDBG_PIDEXCLUDE);
1553 	kd_control_trace.kdc_flags &= ~KDBG_CONTINUOUS_TIME;
1554 	kd_control_trace.kdc_flags &= ~KDBG_DISABLE_COPROCS;
1555 	kd_control_trace.kdc_flags &= ~KDBG_MATCH_DISABLE;
1556 	kd_control_trace.kdc_live_flags &= ~(KDBG_NOWRAP | KDBG_WRAPPED);
1557 
1558 	kd_control_trace.kdc_oldest_time = 0;
1559 
1560 	delete_buffers_trace();
1561 	kd_buffer_trace.kdb_event_count = 0;
1562 
1563 	_clear_thread_map();
1564 
1565 	RAW_file_offset = 0;
1566 	RAW_file_written = 0;
1567 }
1568 
1569 void
kdebug_reset(void)1570 kdebug_reset(void)
1571 {
1572 	ktrace_assert_lock_held();
1573 
1574 	kdbg_clear();
1575 	typefilter_reject_all(kdbg_typefilter);
1576 	typefilter_allow_class(kdbg_typefilter, DBG_TRACE);
1577 }
1578 
1579 void
kdebug_free_early_buf(void)1580 kdebug_free_early_buf(void)
1581 {
1582 #if defined(__x86_64__)
1583 	ml_static_mfree((vm_offset_t)&kd_early_buffer, sizeof(kd_early_buffer));
1584 #endif /* defined(__x86_64__) */
1585 	// ARM handles this as part of the BOOTDATA segment.
1586 }
1587 
1588 int
kdbg_setpid(kd_regtype * kdr)1589 kdbg_setpid(kd_regtype *kdr)
1590 {
1591 	pid_t pid;
1592 	int flag, ret = 0;
1593 	struct proc *p;
1594 
1595 	pid = (pid_t)kdr->value1;
1596 	flag = (int)kdr->value2;
1597 
1598 	if (pid >= 0) {
1599 		if ((p = proc_find(pid)) == NULL) {
1600 			ret = ESRCH;
1601 		} else {
1602 			if (flag == 1) {
1603 				/*
1604 				 * turn on pid check for this and all pids
1605 				 */
1606 				kd_control_trace.kdc_flags |= KDBG_PIDCHECK;
1607 				kd_control_trace.kdc_flags &= ~KDBG_PIDEXCLUDE;
1608 
1609 				p->p_kdebug = 1;
1610 			} else {
1611 				/*
1612 				 * turn off pid check for this pid value
1613 				 * Don't turn off all pid checking though
1614 				 *
1615 				 * kd_control_trace.kdc_flags &= ~KDBG_PIDCHECK;
1616 				 */
1617 				p->p_kdebug = 0;
1618 			}
1619 			proc_rele(p);
1620 		}
1621 	} else {
1622 		ret = EINVAL;
1623 	}
1624 
1625 	return ret;
1626 }
1627 
1628 /* This is for pid exclusion in the trace buffer */
1629 int
kdbg_setpidex(kd_regtype * kdr)1630 kdbg_setpidex(kd_regtype *kdr)
1631 {
1632 	pid_t pid;
1633 	int flag, ret = 0;
1634 	struct proc *p;
1635 
1636 	pid = (pid_t)kdr->value1;
1637 	flag = (int)kdr->value2;
1638 
1639 	if (pid >= 0) {
1640 		if ((p = proc_find(pid)) == NULL) {
1641 			ret = ESRCH;
1642 		} else {
1643 			if (flag == 1) {
1644 				/*
1645 				 * turn on pid exclusion
1646 				 */
1647 				kd_control_trace.kdc_flags |= KDBG_PIDEXCLUDE;
1648 				kd_control_trace.kdc_flags &= ~KDBG_PIDCHECK;
1649 
1650 				p->p_kdebug = 1;
1651 			} else {
1652 				/*
1653 				 * turn off pid exclusion for this pid value
1654 				 * Don't turn off all pid exclusion though
1655 				 *
1656 				 * kd_control_trace.kdc_flags &= ~KDBG_PIDEXCLUDE;
1657 				 */
1658 				p->p_kdebug = 0;
1659 			}
1660 			proc_rele(p);
1661 		}
1662 	} else {
1663 		ret = EINVAL;
1664 	}
1665 
1666 	return ret;
1667 }
1668 
1669 /*
1670  * The following functions all operate on the typefilter singleton.
1671  */
1672 
1673 static int
kdbg_copyin_typefilter(user_addr_t addr,size_t size)1674 kdbg_copyin_typefilter(user_addr_t addr, size_t size)
1675 {
1676 	int ret = ENOMEM;
1677 	typefilter_t tf;
1678 
1679 	ktrace_assert_lock_held();
1680 
1681 	if (size != KDBG_TYPEFILTER_BITMAP_SIZE) {
1682 		return EINVAL;
1683 	}
1684 
1685 	if ((tf = typefilter_create())) {
1686 		if ((ret = copyin(addr, tf, KDBG_TYPEFILTER_BITMAP_SIZE)) == 0) {
1687 			/* The kernel typefilter must always allow DBG_TRACE */
1688 			typefilter_allow_class(tf, DBG_TRACE);
1689 
1690 			typefilter_copy(kdbg_typefilter, tf);
1691 
1692 			kdbg_enable_typefilter();
1693 			_coproc_list_callback(KD_CALLBACK_TYPEFILTER_CHANGED, kdbg_typefilter);
1694 		}
1695 
1696 		if (tf) {
1697 			typefilter_deallocate(tf);
1698 		}
1699 	}
1700 
1701 	return ret;
1702 }
1703 
1704 /*
1705  * Enable the flags in the control page for the typefilter.  Assumes that
1706  * kdbg_typefilter has already been allocated, so events being written
1707  * don't see a bad typefilter.
1708  */
1709 static void
kdbg_enable_typefilter(void)1710 kdbg_enable_typefilter(void)
1711 {
1712 	kd_control_trace.kdc_flags &= ~(KDBG_RANGECHECK | KDBG_VALCHECK);
1713 	kd_control_trace.kdc_flags |= KDBG_TYPEFILTER_CHECK;
1714 	if (kdebug_enable) {
1715 		kd_control_trace.kdc_emit = _trace_emit_filter();
1716 	}
1717 	commpage_update_kdebug_state();
1718 }
1719 
1720 // Disable the flags in the control page for the typefilter.  The typefilter
1721 // may be safely deallocated shortly after this function returns.
1722 static void
kdbg_disable_typefilter(void)1723 kdbg_disable_typefilter(void)
1724 {
1725 	bool notify_coprocs = kd_control_trace.kdc_flags & KDBG_TYPEFILTER_CHECK;
1726 	kd_control_trace.kdc_flags &= ~KDBG_TYPEFILTER_CHECK;
1727 
1728 	commpage_update_kdebug_state();
1729 
1730 	if (notify_coprocs) {
1731 		// Notify coprocessors that the typefilter will now allow everything.
1732 		// Otherwise, they won't know a typefilter is no longer in effect.
1733 		typefilter_allow_all(kdbg_typefilter);
1734 		_coproc_list_callback(KD_CALLBACK_TYPEFILTER_CHANGED, kdbg_typefilter);
1735 	}
1736 }
1737 
1738 uint32_t
kdebug_commpage_state(void)1739 kdebug_commpage_state(void)
1740 {
1741 	uint32_t state = 0;
1742 	if (kdebug_enable) {
1743 		state |= KDEBUG_COMMPAGE_ENABLE_TRACE;
1744 		if (kd_control_trace.kdc_flags & KDBG_TYPEFILTER_CHECK) {
1745 			state |= KDEBUG_COMMPAGE_ENABLE_TYPEFILTER;
1746 		}
1747 		if (kd_control_trace.kdc_flags & KDBG_CONTINUOUS_TIME) {
1748 			state |= KDEBUG_COMMPAGE_CONTINUOUS;
1749 		}
1750 	}
1751 	return state;
1752 }
1753 
1754 static int
kdbg_setreg(kd_regtype * kdr)1755 kdbg_setreg(kd_regtype * kdr)
1756 {
1757 	switch (kdr->type) {
1758 	case KDBG_CLASSTYPE:
1759 		kdlog_beg = KDBG_EVENTID(kdr->value1 & 0xff, 0, 0);
1760 		kdlog_end = KDBG_EVENTID(kdr->value2 & 0xff, 0, 0);
1761 		kd_control_trace.kdc_flags &= ~KDBG_VALCHECK;
1762 		kd_control_trace.kdc_flags |= KDBG_RANGECHECK;
1763 		break;
1764 	case KDBG_SUBCLSTYPE:;
1765 		unsigned int cls = kdr->value1 & 0xff;
1766 		unsigned int subcls = kdr->value2 & 0xff;
1767 		unsigned int subcls_end = subcls + 1;
1768 		kdlog_beg = KDBG_EVENTID(cls, subcls, 0);
1769 		kdlog_end = KDBG_EVENTID(cls, subcls_end, 0);
1770 		kd_control_trace.kdc_flags &= ~KDBG_VALCHECK;
1771 		kd_control_trace.kdc_flags |= KDBG_RANGECHECK;
1772 		break;
1773 	case KDBG_RANGETYPE:
1774 		kdlog_beg = kdr->value1;
1775 		kdlog_end = kdr->value2;
1776 		kd_control_trace.kdc_flags &= ~KDBG_VALCHECK;
1777 		kd_control_trace.kdc_flags |= KDBG_RANGECHECK;
1778 		break;
1779 	case KDBG_VALCHECK:
1780 		kdlog_value1 = kdr->value1;
1781 		kdlog_value2 = kdr->value2;
1782 		kdlog_value3 = kdr->value3;
1783 		kdlog_value4 = kdr->value4;
1784 		kd_control_trace.kdc_flags &= ~KDBG_RANGECHECK;
1785 		kd_control_trace.kdc_flags |= KDBG_VALCHECK;
1786 		break;
1787 	case KDBG_TYPENONE:
1788 		kd_control_trace.kdc_flags &= ~(KDBG_RANGECHECK | KDBG_VALCHECK);
1789 		kdlog_beg = 0;
1790 		kdlog_end = 0;
1791 		break;
1792 	default:
1793 		return EINVAL;
1794 	}
1795 	if (kdebug_enable) {
1796 		kd_control_trace.kdc_emit = _trace_emit_filter();
1797 	}
1798 	return 0;
1799 }
1800 
1801 static int
_copyin_event_disable_mask(user_addr_t uaddr,size_t usize)1802 _copyin_event_disable_mask(user_addr_t uaddr, size_t usize)
1803 {
1804 	if (usize < 2 * sizeof(kd_event_matcher)) {
1805 		return ERANGE;
1806 	}
1807 	int ret = copyin(uaddr, &kd_control_trace.disable_event_match,
1808 	    sizeof(kd_event_matcher));
1809 	if (ret != 0) {
1810 		return ret;
1811 	}
1812 	ret = copyin(uaddr + sizeof(kd_event_matcher),
1813 	    &kd_control_trace.disable_event_mask, sizeof(kd_event_matcher));
1814 	if (ret != 0) {
1815 		memset(&kd_control_trace.disable_event_match, 0,
1816 		    sizeof(kd_event_matcher));
1817 		return ret;
1818 	}
1819 	return 0;
1820 }
1821 
1822 static int
_copyout_event_disable_mask(user_addr_t uaddr,size_t usize)1823 _copyout_event_disable_mask(user_addr_t uaddr, size_t usize)
1824 {
1825 	if (usize < 2 * sizeof(kd_event_matcher)) {
1826 		return ERANGE;
1827 	}
1828 	int ret = copyout(&kd_control_trace.disable_event_match, uaddr,
1829 	    sizeof(kd_event_matcher));
1830 	if (ret != 0) {
1831 		return ret;
1832 	}
1833 	ret = copyout(&kd_control_trace.disable_event_mask,
1834 	    uaddr + sizeof(kd_event_matcher), sizeof(kd_event_matcher));
1835 	if (ret != 0) {
1836 		return ret;
1837 	}
1838 	return 0;
1839 }
1840 
1841 static int
kdbg_write_to_vnode(caddr_t buffer,size_t size,vnode_t vp,vfs_context_t ctx,off_t file_offset)1842 kdbg_write_to_vnode(caddr_t buffer, size_t size, vnode_t vp, vfs_context_t ctx, off_t file_offset)
1843 {
1844 	assert(size < INT_MAX);
1845 	return vn_rdwr(UIO_WRITE, vp, buffer, (int)size, file_offset, UIO_SYSSPACE,
1846 	           IO_NODELOCKED | IO_UNIT, vfs_context_ucred(ctx), (int *) 0,
1847 	           vfs_context_proc(ctx));
1848 }
1849 
1850 static errno_t
_copyout_cpu_map(int map_version,user_addr_t udst,size_t * usize)1851 _copyout_cpu_map(int map_version, user_addr_t udst, size_t *usize)
1852 {
1853 	if ((kd_control_trace.kdc_flags & KDBG_BUFINIT) == 0) {
1854 		return EINVAL;
1855 	}
1856 
1857 	void *cpu_map = NULL;
1858 	size_t size = 0;
1859 	int error = _copy_cpu_map(map_version, &cpu_map, &size);
1860 	if (0 == error) {
1861 		if (udst) {
1862 			size_t copy_size = MIN(*usize, size);
1863 			error = copyout(cpu_map, udst, copy_size);
1864 		}
1865 		*usize = size;
1866 		kmem_free(kernel_map, (vm_offset_t)cpu_map, size);
1867 	}
1868 	if (EINVAL == error && 0 == udst) {
1869 		*usize = size;
1870 		// User space only needs the size if it passes NULL;
1871 		error = 0;
1872 	}
1873 	return error;
1874 }
1875 
1876 int
kdbg_readcurthrmap(user_addr_t buffer,size_t * bufsize)1877 kdbg_readcurthrmap(user_addr_t buffer, size_t *bufsize)
1878 {
1879 	kd_threadmap *mapptr;
1880 	vm_size_t mapsize;
1881 	vm_size_t mapcount;
1882 	int ret = 0;
1883 	size_t count = *bufsize / sizeof(kd_threadmap);
1884 
1885 	*bufsize = 0;
1886 
1887 	if ((mapptr = _thread_map_create_live(count, &mapsize, &mapcount))) {
1888 		if (copyout(mapptr, buffer, mapcount * sizeof(kd_threadmap))) {
1889 			ret = EFAULT;
1890 		} else {
1891 			*bufsize = (mapcount * sizeof(kd_threadmap));
1892 		}
1893 
1894 		kfree_data(mapptr, mapsize);
1895 	} else {
1896 		ret = EINVAL;
1897 	}
1898 
1899 	return ret;
1900 }
1901 
1902 static int
_write_legacy_header(bool write_thread_map,vnode_t vp,vfs_context_t ctx)1903 _write_legacy_header(bool write_thread_map, vnode_t vp, vfs_context_t ctx)
1904 {
1905 	int ret = 0;
1906 	RAW_header header;
1907 	clock_sec_t secs;
1908 	clock_usec_t usecs;
1909 	void *pad_buf;
1910 	uint32_t pad_size;
1911 	uint32_t extra_thread_count = 0;
1912 	uint32_t cpumap_size;
1913 	size_t map_size = 0;
1914 	uint32_t map_count = 0;
1915 
1916 	if (write_thread_map) {
1917 		assert(kd_control_trace.kdc_flags & KDBG_MAPINIT);
1918 		if (kd_mapcount > UINT32_MAX) {
1919 			return ERANGE;
1920 		}
1921 		map_count = (uint32_t)kd_mapcount;
1922 		if (os_mul_overflow(map_count, sizeof(kd_threadmap), &map_size)) {
1923 			return ERANGE;
1924 		}
1925 		if (map_size >= INT_MAX) {
1926 			return ERANGE;
1927 		}
1928 	}
1929 
1930 	/*
1931 	 * Without the buffers initialized, we cannot construct a CPU map or a
1932 	 * thread map, and cannot write a header.
1933 	 */
1934 	if (!(kd_control_trace.kdc_flags & KDBG_BUFINIT)) {
1935 		return EINVAL;
1936 	}
1937 
1938 	/*
1939 	 * To write a RAW_VERSION1+ file, we must embed a cpumap in the
1940 	 * "padding" used to page align the events following the threadmap. If
1941 	 * the threadmap happens to not require enough padding, we artificially
1942 	 * increase its footprint until it needs enough padding.
1943 	 */
1944 
1945 	assert(vp);
1946 	assert(ctx);
1947 
1948 	pad_size = 16384 - ((sizeof(RAW_header) + map_size) & PAGE_MASK);
1949 	cpumap_size = sizeof(kd_cpumap_header) + kd_control_trace.kdebug_cpus * sizeof(kd_cpumap);
1950 
1951 	if (cpumap_size > pad_size) {
1952 		/* If the cpu map doesn't fit in the current available pad_size,
1953 		 * we increase the pad_size by 16K. We do this so that the event
1954 		 * data is always  available on a page aligned boundary for both
1955 		 * 4k and 16k systems. We enforce this alignment for the event
1956 		 * data so that we can take advantage of optimized file/disk writes.
1957 		 */
1958 		pad_size += 16384;
1959 	}
1960 
1961 	/* The way we are silently embedding a cpumap in the "padding" is by artificially
1962 	 * increasing the number of thread entries. However, we'll also need to ensure that
1963 	 * the cpumap is embedded in the last 4K page before when the event data is expected.
1964 	 * This way the tools can read the data starting the next page boundary on both
1965 	 * 4K and 16K systems preserving compatibility with older versions of the tools
1966 	 */
1967 	if (pad_size > 4096) {
1968 		pad_size -= 4096;
1969 		extra_thread_count = (pad_size / sizeof(kd_threadmap)) + 1;
1970 	}
1971 
1972 	memset(&header, 0, sizeof(header));
1973 	header.version_no = RAW_VERSION1;
1974 	header.thread_count = map_count + extra_thread_count;
1975 
1976 	clock_get_calendar_microtime(&secs, &usecs);
1977 	header.TOD_secs = secs;
1978 	header.TOD_usecs = usecs;
1979 
1980 	ret = vn_rdwr(UIO_WRITE, vp, (caddr_t)&header, (int)sizeof(RAW_header), RAW_file_offset,
1981 	    UIO_SYSSPACE, IO_NODELOCKED | IO_UNIT, vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
1982 	if (ret) {
1983 		goto write_error;
1984 	}
1985 	RAW_file_offset += sizeof(RAW_header);
1986 	RAW_file_written += sizeof(RAW_header);
1987 
1988 	if (write_thread_map) {
1989 		assert(map_size < INT_MAX);
1990 		ret = vn_rdwr(UIO_WRITE, vp, (caddr_t)kd_mapptr, (int)map_size, RAW_file_offset,
1991 		    UIO_SYSSPACE, IO_NODELOCKED | IO_UNIT, vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
1992 		if (ret) {
1993 			goto write_error;
1994 		}
1995 
1996 		RAW_file_offset += map_size;
1997 		RAW_file_written += map_size;
1998 	}
1999 
2000 	if (extra_thread_count) {
2001 		pad_size = extra_thread_count * sizeof(kd_threadmap);
2002 		pad_buf = (char *)kalloc_data(pad_size, Z_WAITOK | Z_ZERO);
2003 		if (!pad_buf) {
2004 			ret = ENOMEM;
2005 			goto write_error;
2006 		}
2007 
2008 		assert(pad_size < INT_MAX);
2009 		ret = vn_rdwr(UIO_WRITE, vp, (caddr_t)pad_buf, (int)pad_size, RAW_file_offset,
2010 		    UIO_SYSSPACE, IO_NODELOCKED | IO_UNIT, vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
2011 		kfree_data(pad_buf, pad_size);
2012 		if (ret) {
2013 			goto write_error;
2014 		}
2015 
2016 		RAW_file_offset += pad_size;
2017 		RAW_file_written += pad_size;
2018 	}
2019 
2020 	pad_size = PAGE_SIZE - (RAW_file_offset & PAGE_MASK);
2021 	if (pad_size) {
2022 		pad_buf = (char *)kalloc_data(pad_size, Z_WAITOK | Z_ZERO);
2023 		if (!pad_buf) {
2024 			ret = ENOMEM;
2025 			goto write_error;
2026 		}
2027 
2028 		/*
2029 		 * Embed the CPU map in the padding bytes -- old code will skip it,
2030 		 * while newer code knows it's there.
2031 		 */
2032 		size_t temp = pad_size;
2033 		errno_t error = _copy_cpu_map(RAW_VERSION1, &pad_buf, &temp);
2034 		if (0 != error) {
2035 			memset(pad_buf, 0, pad_size);
2036 		}
2037 
2038 		assert(pad_size < INT_MAX);
2039 		ret = vn_rdwr(UIO_WRITE, vp, (caddr_t)pad_buf, (int)pad_size, RAW_file_offset,
2040 		    UIO_SYSSPACE, IO_NODELOCKED | IO_UNIT, vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
2041 		kfree_data(pad_buf, pad_size);
2042 		if (ret) {
2043 			goto write_error;
2044 		}
2045 
2046 		RAW_file_offset += pad_size;
2047 		RAW_file_written += pad_size;
2048 	}
2049 
2050 write_error:
2051 	return ret;
2052 }
2053 
2054 static void
_clear_thread_map(void)2055 _clear_thread_map(void)
2056 {
2057 	ktrace_assert_lock_held();
2058 
2059 	if (kd_control_trace.kdc_flags & KDBG_MAPINIT) {
2060 		assert(kd_mapptr != NULL);
2061 		kfree_data(kd_mapptr, kd_mapsize);
2062 		kd_mapptr = NULL;
2063 		kd_mapsize = 0;
2064 		kd_mapcount = 0;
2065 		kd_control_trace.kdc_flags &= ~KDBG_MAPINIT;
2066 	}
2067 }
2068 
2069 /*
2070  * Write out a version 1 header and the thread map, if it is initialized, to a
2071  * vnode.  Used by KDWRITEMAP and kdbg_dump_trace_to_file.
2072  *
2073  * Returns write errors from vn_rdwr if a write fails.  Returns ENODATA if the
2074  * thread map has not been initialized, but the header will still be written.
2075  * Returns ENOMEM if padding could not be allocated.  Returns 0 otherwise.
2076  */
2077 static int
kdbg_write_thread_map(vnode_t vp,vfs_context_t ctx)2078 kdbg_write_thread_map(vnode_t vp, vfs_context_t ctx)
2079 {
2080 	int ret = 0;
2081 	bool map_initialized;
2082 
2083 	ktrace_assert_lock_held();
2084 	assert(ctx != NULL);
2085 
2086 	map_initialized = (kd_control_trace.kdc_flags & KDBG_MAPINIT);
2087 
2088 	ret = _write_legacy_header(map_initialized, vp, ctx);
2089 	if (ret == 0) {
2090 		if (map_initialized) {
2091 			_clear_thread_map();
2092 		} else {
2093 			ret = ENODATA;
2094 		}
2095 	}
2096 
2097 	return ret;
2098 }
2099 
2100 /*
2101  * Copy out the thread map to a user space buffer.  Used by KDTHRMAP.
2102  *
2103  * Returns copyout errors if the copyout fails.  Returns ENODATA if the thread
2104  * map has not been initialized.  Returns EINVAL if the buffer provided is not
2105  * large enough for the entire thread map.  Returns 0 otherwise.
2106  */
2107 static int
kdbg_copyout_thread_map(user_addr_t buffer,size_t * buffer_size)2108 kdbg_copyout_thread_map(user_addr_t buffer, size_t *buffer_size)
2109 {
2110 	bool map_initialized;
2111 	size_t map_size;
2112 	int ret = 0;
2113 
2114 	ktrace_assert_lock_held();
2115 	assert(buffer_size != NULL);
2116 
2117 	map_initialized = (kd_control_trace.kdc_flags & KDBG_MAPINIT);
2118 	if (!map_initialized) {
2119 		return ENODATA;
2120 	}
2121 
2122 	map_size = kd_mapcount * sizeof(kd_threadmap);
2123 	if (*buffer_size < map_size) {
2124 		return EINVAL;
2125 	}
2126 
2127 	ret = copyout(kd_mapptr, buffer, map_size);
2128 	if (ret == 0) {
2129 		_clear_thread_map();
2130 	}
2131 
2132 	return ret;
2133 }
2134 
2135 static void
kdbg_set_nkdbufs_trace(unsigned int req_nkdbufs_trace)2136 kdbg_set_nkdbufs_trace(unsigned int req_nkdbufs_trace)
2137 {
2138 	/*
2139 	 * Only allow allocations of up to half the kernel's data range or "sane
2140 	 * size", whichever is smaller.
2141 	 */
2142 	const uint64_t max_nkdbufs_trace_64 =
2143 	    MIN(kmem_range_id_size(KMEM_RANGE_ID_DATA), sane_size) / 2 /
2144 	    sizeof(kd_buf);
2145 	/*
2146 	 * Can't allocate more than 2^38 (2^32 * 64) bytes of events without
2147 	 * switching to a 64-bit event count; should be fine.
2148 	 */
2149 	const unsigned int max_nkdbufs_trace =
2150 	    (unsigned int)MIN(max_nkdbufs_trace_64, UINT_MAX);
2151 
2152 	kd_buffer_trace.kdb_event_count = MIN(req_nkdbufs_trace, max_nkdbufs_trace);
2153 }
2154 
2155 /*
2156  * Block until there are `kd_buffer_trace.kdb_storage_threshold` storage units filled with
2157  * events or `timeout_ms` milliseconds have passed.  If `locked_wait` is true,
2158  * `ktrace_lock` is held while waiting.  This is necessary while waiting to
2159  * write events out of the buffers.
2160  *
2161  * Returns true if the threshold was reached and false otherwise.
2162  *
2163  * Called with `ktrace_lock` locked and interrupts enabled.
2164  */
2165 static bool
kdbg_wait(uint64_t timeout_ms)2166 kdbg_wait(uint64_t timeout_ms)
2167 {
2168 	int wait_result = THREAD_AWAKENED;
2169 	uint64_t deadline_mach = 0;
2170 
2171 	ktrace_assert_lock_held();
2172 
2173 	if (timeout_ms != 0) {
2174 		uint64_t ns = timeout_ms * NSEC_PER_MSEC;
2175 		nanoseconds_to_absolutetime(ns, &deadline_mach);
2176 		clock_absolutetime_interval_to_deadline(deadline_mach, &deadline_mach);
2177 	}
2178 
2179 	bool s = ml_set_interrupts_enabled(false);
2180 	if (!s) {
2181 		panic("kdbg_wait() called with interrupts disabled");
2182 	}
2183 	lck_spin_lock_grp(&kd_wait_lock, &kdebug_lck_grp);
2184 
2185 	/* drop the mutex to allow others to access trace */
2186 	ktrace_unlock();
2187 
2188 	while (wait_result == THREAD_AWAKENED &&
2189 	    kd_control_trace.kdc_storage_used < kd_buffer_trace.kdb_storage_threshold) {
2190 		kd_waiter = true;
2191 
2192 		if (deadline_mach) {
2193 			wait_result = lck_spin_sleep_deadline(&kd_wait_lock, 0, &kd_waiter,
2194 			    THREAD_ABORTSAFE, deadline_mach);
2195 		} else {
2196 			wait_result = lck_spin_sleep(&kd_wait_lock, 0, &kd_waiter,
2197 			    THREAD_ABORTSAFE);
2198 		}
2199 	}
2200 
2201 	bool threshold_exceeded = (kd_control_trace.kdc_storage_used >= kd_buffer_trace.kdb_storage_threshold);
2202 
2203 	lck_spin_unlock(&kd_wait_lock);
2204 	ml_set_interrupts_enabled(s);
2205 
2206 	ktrace_lock();
2207 
2208 	return threshold_exceeded;
2209 }
2210 
2211 /*
2212  * Wakeup a thread waiting using `kdbg_wait` if there are at least
2213  * `kd_buffer_trace.kdb_storage_threshold` storage units in use.
2214  */
2215 static void
kdbg_wakeup(void)2216 kdbg_wakeup(void)
2217 {
2218 	bool need_kds_wakeup = false;
2219 
2220 	/*
2221 	 * Try to take the lock here to synchronize with the waiter entering
2222 	 * the blocked state.  Use the try mode to prevent deadlocks caused by
2223 	 * re-entering this routine due to various trace points triggered in the
2224 	 * lck_spin_sleep_xxxx routines used to actually enter one of our 2 wait
2225 	 * conditions.  No problem if we fail, there will be lots of additional
2226 	 * events coming in that will eventually succeed in grabbing this lock.
2227 	 */
2228 	bool s = ml_set_interrupts_enabled(false);
2229 
2230 	if (lck_spin_try_lock(&kd_wait_lock)) {
2231 		if (kd_waiter &&
2232 		    (kd_control_trace.kdc_storage_used >= kd_buffer_trace.kdb_storage_threshold)) {
2233 			kd_waiter = 0;
2234 			need_kds_wakeup = true;
2235 		}
2236 		lck_spin_unlock(&kd_wait_lock);
2237 	}
2238 
2239 	ml_set_interrupts_enabled(s);
2240 
2241 	if (need_kds_wakeup == true) {
2242 		wakeup(&kd_waiter);
2243 	}
2244 }
2245 
2246 static int
_read_merged_trace_events(user_addr_t buffer,size_t * number,vnode_t vp,vfs_context_t ctx,bool chunk)2247 _read_merged_trace_events(user_addr_t buffer, size_t *number, vnode_t vp,
2248     vfs_context_t ctx, bool chunk)
2249 {
2250 	ktrace_assert_lock_held();
2251 	size_t count = *number / sizeof(kd_buf);
2252 	if (count == 0 || !(kd_control_trace.kdc_flags & KDBG_BUFINIT) ||
2253 	    kd_buffer_trace.kdcopybuf == 0) {
2254 		*number = 0;
2255 		return EINVAL;
2256 	}
2257 
2258 	// Before merging, make sure coprocessors have provided up-to-date events.
2259 	_coproc_list_callback(KD_CALLBACK_SYNC_FLUSH, NULL);
2260 	return kernel_debug_read(&kd_control_trace, &kd_buffer_trace, buffer,
2261 	           number, vp, ctx, chunk);
2262 }
2263 
2264 struct event_chunk_header {
2265 	uint32_t tag;
2266 	uint32_t sub_tag;
2267 	uint64_t length;
2268 	uint64_t future_events_timestamp;
2269 };
2270 
2271 static int
_write_event_chunk_header(user_addr_t udst,vnode_t vp,vfs_context_t ctx,uint64_t length)2272 _write_event_chunk_header(user_addr_t udst, vnode_t vp, vfs_context_t ctx,
2273     uint64_t length)
2274 {
2275 	struct event_chunk_header header = {
2276 		.tag = V3_RAW_EVENTS,
2277 		.sub_tag = 1,
2278 		.length = length,
2279 	};
2280 
2281 	if (vp) {
2282 		assert(udst == USER_ADDR_NULL);
2283 		assert(ctx != NULL);
2284 		int error = kdbg_write_to_vnode((caddr_t)&header, sizeof(header), vp,
2285 		    ctx, RAW_file_offset);
2286 		if (0 == error) {
2287 			RAW_file_offset += sizeof(header);
2288 		}
2289 		return error;
2290 	} else {
2291 		assert(udst != USER_ADDR_NULL);
2292 		return copyout(&header, udst, sizeof(header));
2293 	}
2294 }
2295 
2296 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)2297 kernel_debug_trace_write_to_file(user_addr_t *buffer, size_t *number,
2298     size_t *count, size_t tempbuf_number, vnode_t vp, vfs_context_t ctx,
2299     bool chunk)
2300 {
2301 	int error = 0;
2302 
2303 	if (chunk) {
2304 		error = _write_event_chunk_header(*buffer, vp, ctx,
2305 		    tempbuf_number * sizeof(kd_buf));
2306 		if (error) {
2307 			return error;
2308 		}
2309 		if (buffer) {
2310 			*buffer += sizeof(struct event_chunk_header);
2311 		}
2312 
2313 		assert(*count >= sizeof(struct event_chunk_header));
2314 		*count -= sizeof(struct event_chunk_header);
2315 		*number += sizeof(struct event_chunk_header);
2316 	}
2317 	if (vp) {
2318 		size_t write_size = tempbuf_number * sizeof(kd_buf);
2319 		error = kdbg_write_to_vnode((caddr_t)kd_buffer_trace.kdcopybuf,
2320 		    write_size, vp, ctx, RAW_file_offset);
2321 		if (!error) {
2322 			RAW_file_offset += write_size;
2323 		}
2324 
2325 		if (RAW_file_written >= RAW_FLUSH_SIZE) {
2326 			error = VNOP_FSYNC(vp, MNT_NOWAIT, ctx);
2327 
2328 			RAW_file_written = 0;
2329 		}
2330 	} else {
2331 		error = copyout(kd_buffer_trace.kdcopybuf, *buffer, tempbuf_number * sizeof(kd_buf));
2332 		*buffer += (tempbuf_number * sizeof(kd_buf));
2333 	}
2334 
2335 	return error;
2336 }
2337 
2338 #pragma mark - User space interface
2339 
2340 static int
_kd_sysctl_internal(int op,int value,user_addr_t where,size_t * sizep)2341 _kd_sysctl_internal(int op, int value, user_addr_t where, size_t *sizep)
2342 {
2343 	size_t size = *sizep;
2344 	kd_regtype kd_Reg;
2345 	proc_t p;
2346 
2347 	bool read_only = (op == KERN_KDGETBUF || op == KERN_KDREADCURTHRMAP);
2348 	int perm_error = read_only ? ktrace_read_check() :
2349 	    ktrace_configure(KTRACE_KDEBUG);
2350 	if (perm_error != 0) {
2351 		return perm_error;
2352 	}
2353 
2354 	switch (op) {
2355 	case KERN_KDGETBUF:;
2356 		pid_t owning_pid = ktrace_get_owning_pid();
2357 		kbufinfo_t info = {
2358 			.nkdbufs = kd_buffer_trace.kdb_event_count,
2359 			.nkdthreads = (int)MIN(kd_mapcount, INT_MAX),
2360 			.nolog = kd_control_trace.kdc_emit == KDEMIT_DISABLE,
2361 			.flags = kd_control_trace.kdc_flags | kd_control_trace.kdc_live_flags,
2362 			.bufid = owning_pid ?: -1,
2363 		};
2364 #if defined(__LP64__)
2365 		info.flags |= KDBG_LP64;
2366 #endif // defined(__LP64__)
2367 
2368 		size = MIN(size, sizeof(info));
2369 		return copyout(&info, where, size);
2370 	case KERN_KDREADCURTHRMAP:
2371 		return kdbg_readcurthrmap(where, sizep);
2372 	case KERN_KDEFLAGS:
2373 		value &= KDBG_USERFLAGS;
2374 		kd_control_trace.kdc_flags |= value;
2375 		return 0;
2376 	case KERN_KDDFLAGS:
2377 		value &= KDBG_USERFLAGS;
2378 		kd_control_trace.kdc_flags &= ~value;
2379 		return 0;
2380 	case KERN_KDENABLE:
2381 		if (value) {
2382 			if (!(kd_control_trace.kdc_flags & KDBG_BUFINIT) ||
2383 			    !(value == KDEBUG_ENABLE_TRACE || value == KDEBUG_ENABLE_PPT)) {
2384 				return EINVAL;
2385 			}
2386 			_threadmap_init();
2387 
2388 			kdbg_set_tracing_enabled(true, value);
2389 		} else {
2390 			if (!kdebug_enable) {
2391 				return 0;
2392 			}
2393 
2394 			kernel_debug_disable();
2395 		}
2396 		return 0;
2397 	case KERN_KDSETBUF:
2398 		kdbg_set_nkdbufs_trace(value);
2399 		return 0;
2400 	case KERN_KDSETUP:
2401 		return kdbg_reinit(0);
2402 	case KERN_KDREMOVE:
2403 		ktrace_reset(KTRACE_KDEBUG);
2404 		return 0;
2405 	case KERN_KDSETREG:
2406 		if (size < sizeof(kd_regtype)) {
2407 			return EINVAL;
2408 		}
2409 		if (copyin(where, &kd_Reg, sizeof(kd_regtype))) {
2410 			return EINVAL;
2411 		}
2412 		return kdbg_setreg(&kd_Reg);
2413 	case KERN_KDGETREG:
2414 		return EINVAL;
2415 	case KERN_KDREADTR:
2416 		return _read_merged_trace_events(where, sizep, NULL, NULL, false);
2417 	case KERN_KDWRITETR:
2418 	case KERN_KDWRITETR_V3:
2419 	case KERN_KDWRITEMAP: {
2420 		struct  vfs_context context;
2421 		struct  fileproc *fp;
2422 		size_t  number;
2423 		vnode_t vp;
2424 		int     fd;
2425 		int ret = 0;
2426 
2427 		if (op == KERN_KDWRITETR || op == KERN_KDWRITETR_V3) {
2428 			(void)kdbg_wait(size);
2429 			// Re-check whether this process can configure ktrace, since waiting
2430 			// will drop the ktrace lock.
2431 			int no_longer_owner_error = ktrace_configure(KTRACE_KDEBUG);
2432 			if (no_longer_owner_error != 0) {
2433 				return no_longer_owner_error;
2434 			}
2435 		}
2436 
2437 		p = current_proc();
2438 		fd = value;
2439 
2440 		if (fp_get_ftype(p, fd, DTYPE_VNODE, EBADF, &fp)) {
2441 			return EBADF;
2442 		}
2443 
2444 		vp = fp_get_data(fp);
2445 		context.vc_thread = current_thread();
2446 		context.vc_ucred = fp->fp_glob->fg_cred;
2447 
2448 		if ((ret = vnode_getwithref(vp)) == 0) {
2449 			RAW_file_offset = fp->fp_glob->fg_offset;
2450 			if (op == KERN_KDWRITETR || op == KERN_KDWRITETR_V3) {
2451 				number = kd_buffer_trace.kdb_event_count * sizeof(kd_buf);
2452 
2453 				KDBG_RELEASE(TRACE_WRITING_EVENTS | DBG_FUNC_START);
2454 				ret = _read_merged_trace_events(0, &number, vp, &context,
2455 				    op == KERN_KDWRITETR_V3);
2456 				KDBG_RELEASE(TRACE_WRITING_EVENTS | DBG_FUNC_END, number);
2457 
2458 				*sizep = number;
2459 			} else {
2460 				number = kd_mapcount * sizeof(kd_threadmap);
2461 				ret = kdbg_write_thread_map(vp, &context);
2462 			}
2463 			fp->fp_glob->fg_offset = RAW_file_offset;
2464 			vnode_put(vp);
2465 		}
2466 		fp_drop(p, fd, fp, 0);
2467 
2468 		return ret;
2469 	}
2470 	case KERN_KDBUFWAIT:
2471 		*sizep = kdbg_wait(size);
2472 		return 0;
2473 	case KERN_KDPIDTR:
2474 		if (size < sizeof(kd_regtype)) {
2475 			return EINVAL;
2476 		}
2477 		if (copyin(where, &kd_Reg, sizeof(kd_regtype))) {
2478 			return EINVAL;
2479 		}
2480 		return kdbg_setpid(&kd_Reg);
2481 	case KERN_KDPIDEX:
2482 		if (size < sizeof(kd_regtype)) {
2483 			return EINVAL;
2484 		}
2485 		if (copyin(where, &kd_Reg, sizeof(kd_regtype))) {
2486 			return EINVAL;
2487 		}
2488 		return kdbg_setpidex(&kd_Reg);
2489 	case KERN_KDCPUMAP:
2490 		return _copyout_cpu_map(RAW_VERSION1, where, sizep);
2491 	case KERN_KDCPUMAP_EXT:
2492 		return _copyout_cpu_map(1, where, sizep);
2493 	case KERN_KDTHRMAP:
2494 		return kdbg_copyout_thread_map(where, sizep);
2495 	case KERN_KDSET_TYPEFILTER:
2496 		return kdbg_copyin_typefilter(where, size);
2497 	case KERN_KDSET_EDM:
2498 		return _copyin_event_disable_mask(where, size);
2499 	case KERN_KDGET_EDM:
2500 		return _copyout_event_disable_mask(where, size);
2501 #if DEVELOPMENT || DEBUG
2502 	case KERN_KDTEST:
2503 		return kdbg_test(size);
2504 #endif // DEVELOPMENT || DEBUG
2505 
2506 	default:
2507 		return ENOTSUP;
2508 	}
2509 }
2510 
2511 static int
2512 kdebug_sysctl SYSCTL_HANDLER_ARGS
2513 {
2514 	int *names = arg1;
2515 	int name_count = arg2;
2516 	user_addr_t udst = req->oldptr;
2517 	size_t *usize = &req->oldlen;
2518 	int value = 0;
2519 
2520 	if (name_count == 0) {
2521 		return ENOTSUP;
2522 	}
2523 
2524 	int op = names[0];
2525 
2526 	// Some operations have an argument stuffed into the next OID argument.
2527 	switch (op) {
2528 	case KERN_KDWRITETR:
2529 	case KERN_KDWRITETR_V3:
2530 	case KERN_KDWRITEMAP:
2531 	case KERN_KDEFLAGS:
2532 	case KERN_KDDFLAGS:
2533 	case KERN_KDENABLE:
2534 	case KERN_KDSETBUF:
2535 		if (name_count < 2) {
2536 			return EINVAL;
2537 		}
2538 		value = names[1];
2539 		break;
2540 	default:
2541 		break;
2542 	}
2543 
2544 	ktrace_lock();
2545 	int ret = _kd_sysctl_internal(op, value, udst, usize);
2546 	ktrace_unlock();
2547 	if (0 == ret) {
2548 		req->oldidx += req->oldlen;
2549 	}
2550 	return ret;
2551 }
2552 SYSCTL_PROC(_kern, KERN_KDEBUG, kdebug,
2553     CTLTYPE_NODE | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0, kdebug_sysctl, NULL, "");
2554 
2555 #pragma mark - Tests
2556 
2557 #if DEVELOPMENT || DEBUG
2558 
2559 static int test_coproc = 0;
2560 static int sync_flush_coproc = 0;
2561 
2562 #define KDEBUG_TEST_CODE(code) BSDDBG_CODE(DBG_BSD_KDEBUG_TEST, (code))
2563 
2564 /*
2565  * A test IOP for the SYNC_FLUSH callback.
2566  */
2567 
2568 static void
sync_flush_callback(void * __unused context,kd_callback_type reason,void * __unused arg)2569 sync_flush_callback(void * __unused context, kd_callback_type reason,
2570     void * __unused arg)
2571 {
2572 	assert(sync_flush_coproc > 0);
2573 
2574 	if (reason == KD_CALLBACK_SYNC_FLUSH) {
2575 		kernel_debug_enter(sync_flush_coproc, KDEBUG_TEST_CODE(0xff),
2576 		    kdebug_timestamp(), 0, 0, 0, 0, 0);
2577 	}
2578 }
2579 
2580 static struct kd_callback sync_flush_kdcb = {
2581 	.func = sync_flush_callback,
2582 	.iop_name = "test_sf",
2583 };
2584 
2585 #define TEST_COPROC_CTX 0xabadcafe
2586 
2587 static void
test_coproc_cb(void * context,kd_callback_type __unused reason,void * __unused arg)2588 test_coproc_cb(void *context, kd_callback_type __unused reason,
2589     void * __unused arg)
2590 {
2591 	assert((uintptr_t)context == TEST_COPROC_CTX);
2592 }
2593 
2594 static int
kdbg_test(size_t flavor)2595 kdbg_test(size_t flavor)
2596 {
2597 	int code = 0;
2598 	int dummy_iop = 0;
2599 
2600 	switch (flavor) {
2601 	case KDTEST_KERNEL_MACROS:
2602 		/* try each macro */
2603 		KDBG(KDEBUG_TEST_CODE(code)); code++;
2604 		KDBG(KDEBUG_TEST_CODE(code), 1); code++;
2605 		KDBG(KDEBUG_TEST_CODE(code), 1, 2); code++;
2606 		KDBG(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
2607 		KDBG(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
2608 
2609 		KDBG_RELEASE(KDEBUG_TEST_CODE(code)); code++;
2610 		KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1); code++;
2611 		KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1, 2); code++;
2612 		KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
2613 		KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
2614 
2615 		KDBG_FILTERED(KDEBUG_TEST_CODE(code)); code++;
2616 		KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1); code++;
2617 		KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1, 2); code++;
2618 		KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
2619 		KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
2620 
2621 		KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code)); code++;
2622 		KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code), 1); code++;
2623 		KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code), 1, 2); code++;
2624 		KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
2625 		KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
2626 
2627 		KDBG_DEBUG(KDEBUG_TEST_CODE(code)); code++;
2628 		KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1); code++;
2629 		KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1, 2); code++;
2630 		KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
2631 		KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
2632 		break;
2633 
2634 	case KDTEST_OLD_TIMESTAMP:
2635 		if (kd_control_trace.kdc_coprocs) {
2636 			/* avoid the assertion in kernel_debug_enter for a valid IOP */
2637 			dummy_iop = kd_control_trace.kdc_coprocs[0].cpu_id;
2638 		}
2639 
2640 		/* ensure old timestamps are not emitted from kernel_debug_enter */
2641 		kernel_debug_enter(dummy_iop, KDEBUG_TEST_CODE(code),
2642 		    100 /* very old timestamp */, 0, 0, 0, 0, 0);
2643 		code++;
2644 		kernel_debug_enter(dummy_iop, KDEBUG_TEST_CODE(code),
2645 		    kdebug_timestamp(), 0, 0, 0, 0, 0);
2646 		code++;
2647 		break;
2648 
2649 	case KDTEST_FUTURE_TIMESTAMP:
2650 		if (kd_control_trace.kdc_coprocs) {
2651 			dummy_iop = kd_control_trace.kdc_coprocs[0].cpu_id;
2652 		}
2653 		kernel_debug_enter(dummy_iop, KDEBUG_TEST_CODE(code),
2654 		    kdebug_timestamp() * 2 /* !!! */, 0, 0, 0, 0, 0);
2655 		break;
2656 
2657 	case KDTEST_SETUP_IOP:
2658 		if (!sync_flush_coproc) {
2659 			ktrace_unlock();
2660 			int new_sync_flush_coproc = kernel_debug_register_callback(
2661 				sync_flush_kdcb);
2662 			assert(new_sync_flush_coproc > 0);
2663 			ktrace_lock();
2664 			if (!sync_flush_coproc) {
2665 				sync_flush_coproc = new_sync_flush_coproc;
2666 			}
2667 		}
2668 		break;
2669 
2670 	case KDTEST_SETUP_COPROCESSOR:
2671 		if (!test_coproc) {
2672 			ktrace_unlock();
2673 			int new_test_coproc = kdebug_register_coproc("test_coproc",
2674 			    KDCP_CONTINUOUS_TIME, test_coproc_cb, (void *)TEST_COPROC_CTX);
2675 			assert(new_test_coproc > 0);
2676 			ktrace_lock();
2677 			if (!test_coproc) {
2678 				test_coproc = new_test_coproc;
2679 			}
2680 		}
2681 		break;
2682 
2683 	case KDTEST_ABSOLUTE_TIMESTAMP:;
2684 		uint64_t atime = mach_absolute_time();
2685 		kernel_debug_enter(sync_flush_coproc, KDEBUG_TEST_CODE(0),
2686 		    atime, (uintptr_t)atime, (uintptr_t)(atime >> 32), 0, 0, 0);
2687 		break;
2688 
2689 	case KDTEST_CONTINUOUS_TIMESTAMP:;
2690 		uint64_t ctime = mach_continuous_time();
2691 		kernel_debug_enter(test_coproc, KDEBUG_TEST_CODE(1),
2692 		    ctime, (uintptr_t)ctime, (uintptr_t)(ctime >> 32), 0, 0, 0);
2693 		break;
2694 
2695 	case KDTEST_PAST_EVENT:;
2696 		uint64_t old_time = 1;
2697 		kernel_debug_enter(test_coproc, KDEBUG_TEST_CODE(1), old_time, 0, 0, 0,
2698 		    0, 0);
2699 		kernel_debug_enter(test_coproc, KDEBUG_TEST_CODE(1), kdebug_timestamp(),
2700 		    0, 0, 0, 0, 0);
2701 		break;
2702 
2703 	default:
2704 		return ENOTSUP;
2705 	}
2706 
2707 	return 0;
2708 }
2709 
2710 #undef KDEBUG_TEST_CODE
2711 
2712 #endif /* DEVELOPMENT || DEBUG */
2713 
2714 static void
_deferred_coproc_notify(mpsc_queue_chain_t e,mpsc_daemon_queue_t queue __unused)2715 _deferred_coproc_notify(mpsc_queue_chain_t e, mpsc_daemon_queue_t queue __unused)
2716 {
2717 	struct kd_coproc *coproc = mpsc_queue_element(e, struct kd_coproc, chain);
2718 	if (kd_control_trace.kdc_emit == KDEMIT_TYPEFILTER) {
2719 		coproc->callback.func(coproc->callback.context,
2720 		    KD_CALLBACK_TYPEFILTER_CHANGED, kdbg_typefilter);
2721 	}
2722 	if (kdebug_enable) {
2723 		coproc->callback.func(coproc->callback.context,
2724 		    KD_CALLBACK_KDEBUG_ENABLED, kdbg_typefilter);
2725 	}
2726 }
2727 
2728 void
kdebug_init(unsigned int n_events,char * filter_desc,enum kdebug_opts opts)2729 kdebug_init(unsigned int n_events, char *filter_desc, enum kdebug_opts opts)
2730 {
2731 	assert(filter_desc != NULL);
2732 
2733 	kdbg_typefilter = typefilter_create();
2734 	assert(kdbg_typefilter != NULL);
2735 	kdbg_typefilter_memory_entry = typefilter_create_memory_entry(kdbg_typefilter);
2736 	assert(kdbg_typefilter_memory_entry != MACH_PORT_NULL);
2737 
2738 	(void)mpsc_daemon_queue_init_with_thread_call(&_coproc_notify_queue,
2739 	    _deferred_coproc_notify, THREAD_CALL_PRIORITY_KERNEL,
2740 	    MPSC_DAEMON_INIT_NONE);
2741 
2742 	kdebug_trace_start(n_events, filter_desc, opts);
2743 }
2744 
2745 static void
kdbg_set_typefilter_string(const char * filter_desc)2746 kdbg_set_typefilter_string(const char *filter_desc)
2747 {
2748 	char *end = NULL;
2749 
2750 	ktrace_assert_lock_held();
2751 
2752 	assert(filter_desc != NULL);
2753 
2754 	typefilter_reject_all(kdbg_typefilter);
2755 	typefilter_allow_class(kdbg_typefilter, DBG_TRACE);
2756 
2757 	/* if the filter description starts with a number, assume it's a csc */
2758 	if (filter_desc[0] >= '0' && filter_desc[0] <= '9') {
2759 		unsigned long csc = strtoul(filter_desc, NULL, 0);
2760 		if (filter_desc != end && csc <= KDBG_CSC_MAX) {
2761 			typefilter_allow_csc(kdbg_typefilter, (uint16_t)csc);
2762 		}
2763 		return;
2764 	}
2765 
2766 	while (filter_desc[0] != '\0') {
2767 		unsigned long allow_value;
2768 
2769 		char filter_type = filter_desc[0];
2770 		if (filter_type != 'C' && filter_type != 'S') {
2771 			printf("kdebug: unexpected filter type `%c'\n", filter_type);
2772 			return;
2773 		}
2774 		filter_desc++;
2775 
2776 		allow_value = strtoul(filter_desc, &end, 0);
2777 		if (filter_desc == end) {
2778 			printf("kdebug: cannot parse `%s' as integer\n", filter_desc);
2779 			return;
2780 		}
2781 
2782 		switch (filter_type) {
2783 		case 'C':
2784 			if (allow_value > KDBG_CLASS_MAX) {
2785 				printf("kdebug: class 0x%lx is invalid\n", allow_value);
2786 				return;
2787 			}
2788 			printf("kdebug: C 0x%lx\n", allow_value);
2789 			typefilter_allow_class(kdbg_typefilter, (uint8_t)allow_value);
2790 			break;
2791 		case 'S':
2792 			if (allow_value > KDBG_CSC_MAX) {
2793 				printf("kdebug: class-subclass 0x%lx is invalid\n", allow_value);
2794 				return;
2795 			}
2796 			printf("kdebug: S 0x%lx\n", allow_value);
2797 			typefilter_allow_csc(kdbg_typefilter, (uint16_t)allow_value);
2798 			break;
2799 		default:
2800 			__builtin_unreachable();
2801 		}
2802 
2803 		/* advance to next filter entry */
2804 		filter_desc = end;
2805 		if (filter_desc[0] == ',') {
2806 			filter_desc++;
2807 		}
2808 	}
2809 }
2810 
2811 uint64_t
kdebug_wake(void)2812 kdebug_wake(void)
2813 {
2814 	if (!wake_nkdbufs) {
2815 		return 0;
2816 	}
2817 	uint64_t start = mach_absolute_time();
2818 	kdebug_trace_start(wake_nkdbufs, NULL, trace_wrap ? KDOPT_WRAPPING : 0);
2819 	return mach_absolute_time() - start;
2820 }
2821 
2822 /*
2823  * This function is meant to be called from the bootstrap thread or kdebug_wake.
2824  */
2825 void
kdebug_trace_start(unsigned int n_events,const char * filter_desc,enum kdebug_opts opts)2826 kdebug_trace_start(unsigned int n_events, const char *filter_desc,
2827     enum kdebug_opts opts)
2828 {
2829 	if (!n_events) {
2830 		kd_early_done = true;
2831 		return;
2832 	}
2833 
2834 	ktrace_start_single_threaded();
2835 
2836 	ktrace_kernel_configure(KTRACE_KDEBUG);
2837 
2838 	kdbg_set_nkdbufs_trace(n_events);
2839 
2840 	kernel_debug_string_early("start_kern_tracing");
2841 
2842 	int error = kdbg_reinit(EXTRA_COPROC_COUNT);
2843 	if (error != 0) {
2844 		printf("kdebug: allocation failed, kernel tracing not started: %d\n",
2845 		    error);
2846 		kd_early_done = true;
2847 		goto out;
2848 	}
2849 
2850 	/*
2851 	 * Wrapping is disabled because boot and wake tracing is interested in
2852 	 * the earliest events, at the expense of later ones.
2853 	 */
2854 	if ((opts & KDOPT_WRAPPING) == 0) {
2855 		kd_control_trace.kdc_live_flags |= KDBG_NOWRAP;
2856 	}
2857 
2858 	if (filter_desc && filter_desc[0] != '\0') {
2859 		kdbg_set_typefilter_string(filter_desc);
2860 		kdbg_enable_typefilter();
2861 	}
2862 
2863 	/*
2864 	 * Hold off interrupts between getting a thread map and enabling trace
2865 	 * and until the early traces are recorded.
2866 	 */
2867 	bool s = ml_set_interrupts_enabled(false);
2868 
2869 	if (!(opts & KDOPT_ATBOOT)) {
2870 		_threadmap_init();
2871 	}
2872 
2873 	kdbg_set_tracing_enabled(true, KDEBUG_ENABLE_TRACE);
2874 
2875 	if ((opts & KDOPT_ATBOOT)) {
2876 		/*
2877 		 * Transfer all very early events from the static buffer into the real
2878 		 * buffers.
2879 		 */
2880 		kernel_debug_early_end();
2881 	}
2882 
2883 	ml_set_interrupts_enabled(s);
2884 
2885 	printf("kernel tracing started with %u events, filter = %s\n", n_events,
2886 	    filter_desc ?: "none");
2887 
2888 out:
2889 	ktrace_end_single_threaded();
2890 }
2891 
2892 void
kdbg_dump_trace_to_file(const char * filename,bool reenable)2893 kdbg_dump_trace_to_file(const char *filename, bool reenable)
2894 {
2895 	vfs_context_t ctx;
2896 	vnode_t vp;
2897 	size_t write_size;
2898 	int ret;
2899 	int reenable_trace = 0;
2900 
2901 	ktrace_lock();
2902 
2903 	if (!(kdebug_enable & KDEBUG_ENABLE_TRACE)) {
2904 		goto out;
2905 	}
2906 
2907 	if (ktrace_get_owning_pid() != 0) {
2908 		/*
2909 		 * Another process owns ktrace and is still active, disable tracing to
2910 		 * prevent wrapping.
2911 		 */
2912 		kdebug_enable = 0;
2913 		kd_control_trace.enabled = 0;
2914 		commpage_update_kdebug_state();
2915 		goto out;
2916 	}
2917 
2918 	KDBG_RELEASE(TRACE_WRITING_EVENTS | DBG_FUNC_START);
2919 
2920 	reenable_trace = reenable ? kdebug_enable : 0;
2921 	kdebug_enable = 0;
2922 	kd_control_trace.enabled = 0;
2923 	commpage_update_kdebug_state();
2924 
2925 	ctx = vfs_context_kernel();
2926 
2927 	if (vnode_open(filename, (O_CREAT | FWRITE | O_NOFOLLOW), 0600, 0, &vp, ctx)) {
2928 		goto out;
2929 	}
2930 
2931 	kdbg_write_thread_map(vp, ctx);
2932 
2933 	write_size = kd_buffer_trace.kdb_event_count * sizeof(kd_buf);
2934 	ret = _read_merged_trace_events(0, &write_size, vp, ctx, false);
2935 	if (ret) {
2936 		goto out_close;
2937 	}
2938 
2939 	/*
2940 	 * Wait to synchronize the file to capture the I/O in the
2941 	 * TRACE_WRITING_EVENTS interval.
2942 	 */
2943 	ret = VNOP_FSYNC(vp, MNT_WAIT, ctx);
2944 	if (ret == KERN_SUCCESS) {
2945 		ret = VNOP_IOCTL(vp, F_FULLFSYNC, (caddr_t)NULL, 0, ctx);
2946 	}
2947 
2948 	/*
2949 	 * Balance the starting TRACE_WRITING_EVENTS tracepoint manually.
2950 	 */
2951 	kd_buf end_event = {
2952 		.debugid = TRACE_WRITING_EVENTS | DBG_FUNC_END,
2953 		.arg1 = write_size,
2954 		.arg2 = ret,
2955 		.arg5 = (kd_buf_argtype)thread_tid(current_thread()),
2956 	};
2957 	kdbg_set_timestamp_and_cpu(&end_event, kdebug_timestamp(),
2958 	    cpu_number());
2959 
2960 	/* this is best effort -- ignore any errors */
2961 	(void)kdbg_write_to_vnode((caddr_t)&end_event, sizeof(kd_buf), vp, ctx,
2962 	    RAW_file_offset);
2963 
2964 out_close:
2965 	vnode_close(vp, FWRITE, ctx);
2966 	sync(current_proc(), (void *)NULL, (int *)NULL);
2967 
2968 out:
2969 	if (reenable_trace != 0) {
2970 		kdebug_enable = reenable_trace;
2971 		kd_control_trace.enabled = 1;
2972 		commpage_update_kdebug_state();
2973 	}
2974 
2975 	ktrace_unlock();
2976 }
2977 
2978 SYSCTL_NODE(_kern, OID_AUTO, kdbg, CTLFLAG_RD | CTLFLAG_LOCKED, 0,
2979     "kdbg");
2980 
2981 SYSCTL_INT(_kern_kdbg, OID_AUTO, debug,
2982     CTLFLAG_RW | CTLFLAG_LOCKED,
2983     &kdbg_debug, 0, "Set kdebug debug mode");
2984 
2985 SYSCTL_QUAD(_kern_kdbg, OID_AUTO, oldest_time,
2986     CTLTYPE_QUAD | CTLFLAG_RD | CTLFLAG_LOCKED,
2987     &kd_control_trace.kdc_oldest_time,
2988     "Find the oldest timestamp still in trace");
2989