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