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