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