]> git.saurik.com Git - apple/xnu.git/blob - bsd/kern/kdebug.c
xnu-7195.101.1.tar.gz
[apple/xnu.git] / bsd / kern / kdebug.c
1 /*
2 * Copyright (c) 2000-2019 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/param.h>
25 #include <sys/systm.h>
26 #include <sys/proc_internal.h>
27 #include <sys/vm.h>
28 #include <sys/sysctl.h>
29 #include <sys/kdebug.h>
30 #include <sys/kauth.h>
31 #include <sys/ktrace.h>
32 #include <sys/sysproto.h>
33 #include <sys/bsdtask_info.h>
34 #include <sys/random.h>
35
36 #include <mach/clock_types.h>
37 #include <mach/mach_types.h>
38 #include <mach/mach_time.h>
39 #include <mach/mach_vm.h>
40 #include <machine/atomic.h>
41 #include <machine/machine_routines.h>
42
43 #include <mach/machine.h>
44 #include <mach/vm_map.h>
45
46 #if defined(__i386__) || defined(__x86_64__)
47 #include <i386/rtclock_protos.h>
48 #include <i386/mp.h>
49 #include <i386/machine_routines.h>
50 #include <i386/tsc.h>
51 #endif
52
53 #include <kern/clock.h>
54
55 #include <kern/thread.h>
56 #include <kern/task.h>
57 #include <kern/debug.h>
58 #include <kern/kalloc.h>
59 #include <kern/cpu_number.h>
60 #include <kern/cpu_data.h>
61 #include <kern/assert.h>
62 #include <kern/telemetry.h>
63 #include <kern/sched_prim.h>
64 #include <vm/vm_kern.h>
65 #include <sys/lock.h>
66 #include <kperf/kperf.h>
67 #include <pexpert/device_tree.h>
68
69 #include <sys/malloc.h>
70 #include <sys/mcache.h>
71
72 #include <sys/vnode.h>
73 #include <sys/vnode_internal.h>
74 #include <sys/fcntl.h>
75 #include <sys/file_internal.h>
76 #include <sys/ubc.h>
77 #include <sys/param.h> /* for isset() */
78
79 #include <mach/mach_host.h> /* for host_info() */
80 #include <libkern/OSAtomic.h>
81
82 #include <machine/pal_routines.h>
83 #include <machine/atomic.h>
84
85 extern unsigned int wake_nkdbufs;
86 extern unsigned int trace_wrap;
87
88 /*
89 * IOP(s)
90 *
91 * IOP(s) are auxiliary cores that want to participate in kdebug event logging.
92 * They are registered dynamically. Each is assigned a cpu_id at registration.
93 *
94 * NOTE: IOP trace events may not use the same clock hardware as "normal"
95 * cpus. There is an effort made to synchronize the IOP timebase with the
96 * AP, but it should be understood that there may be discrepancies.
97 *
98 * Once registered, an IOP is permanent, it cannot be unloaded/unregistered.
99 * The current implementation depends on this for thread safety.
100 *
101 * New registrations occur by allocating an kd_iop struct and assigning
102 * a provisional cpu_id of list_head->cpu_id + 1. Then a CAS to claim the
103 * list_head pointer resolves any races.
104 *
105 * You may safely walk the kd_iops list at any time, without holding locks.
106 *
107 * When allocating buffers, the current kd_iops head is captured. Any operations
108 * that depend on the buffer state (such as flushing IOP traces on reads,
109 * etc.) should use the captured list head. This will allow registrations to
110 * take place while trace is in use.
111 */
112
113 typedef struct kd_iop {
114 kd_callback_t callback;
115 uint32_t cpu_id;
116 uint64_t last_timestamp; /* Prevent timer rollback */
117 struct kd_iop* next;
118 } kd_iop_t;
119
120 static kd_iop_t* kd_iops = NULL;
121
122 /*
123 * Typefilter(s)
124 *
125 * A typefilter is a 8KB bitmap that is used to selectively filter events
126 * being recorded. It is able to individually address every class & subclass.
127 *
128 * There is a shared typefilter in the kernel which is lazily allocated. Once
129 * allocated, the shared typefilter is never deallocated. The shared typefilter
130 * is also mapped on demand into userspace processes that invoke kdebug_trace
131 * API from Libsyscall. When mapped into a userspace process, the memory is
132 * read only, and does not have a fixed address.
133 *
134 * It is a requirement that the kernel's shared typefilter always pass DBG_TRACE
135 * events. This is enforced automatically, by having the needed bits set any
136 * time the shared typefilter is mutated.
137 */
138
139 typedef uint8_t* typefilter_t;
140
141 static typefilter_t kdbg_typefilter;
142 static mach_port_t kdbg_typefilter_memory_entry;
143
144 /*
145 * There are 3 combinations of page sizes:
146 *
147 * 4KB / 4KB
148 * 4KB / 16KB
149 * 16KB / 16KB
150 *
151 * The typefilter is exactly 8KB. In the first two scenarios, we would like
152 * to use 2 pages exactly; in the third scenario we must make certain that
153 * a full page is allocated so we do not inadvertantly share 8KB of random
154 * data to userspace. The round_page_32 macro rounds to kernel page size.
155 */
156 #define TYPEFILTER_ALLOC_SIZE MAX(round_page_32(KDBG_TYPEFILTER_BITMAP_SIZE), KDBG_TYPEFILTER_BITMAP_SIZE)
157
158 static typefilter_t
159 typefilter_create(void)
160 {
161 typefilter_t tf;
162 if (KERN_SUCCESS == kmem_alloc(kernel_map, (vm_offset_t*)&tf, TYPEFILTER_ALLOC_SIZE, VM_KERN_MEMORY_DIAG)) {
163 memset(&tf[KDBG_TYPEFILTER_BITMAP_SIZE], 0, TYPEFILTER_ALLOC_SIZE - KDBG_TYPEFILTER_BITMAP_SIZE);
164 return tf;
165 }
166 return NULL;
167 }
168
169 static void
170 typefilter_deallocate(typefilter_t tf)
171 {
172 assert(tf != NULL);
173 assert(tf != kdbg_typefilter);
174 kmem_free(kernel_map, (vm_offset_t)tf, TYPEFILTER_ALLOC_SIZE);
175 }
176
177 static void
178 typefilter_copy(typefilter_t dst, typefilter_t src)
179 {
180 assert(src != NULL);
181 assert(dst != NULL);
182 memcpy(dst, src, KDBG_TYPEFILTER_BITMAP_SIZE);
183 }
184
185 static void
186 typefilter_reject_all(typefilter_t tf)
187 {
188 assert(tf != NULL);
189 memset(tf, 0, KDBG_TYPEFILTER_BITMAP_SIZE);
190 }
191
192 static void
193 typefilter_allow_all(typefilter_t tf)
194 {
195 assert(tf != NULL);
196 memset(tf, ~0, KDBG_TYPEFILTER_BITMAP_SIZE);
197 }
198
199 static void
200 typefilter_allow_class(typefilter_t tf, uint8_t class)
201 {
202 assert(tf != NULL);
203 const uint32_t BYTES_PER_CLASS = 256 / 8; // 256 subclasses, 1 bit each
204 memset(&tf[class * BYTES_PER_CLASS], 0xFF, BYTES_PER_CLASS);
205 }
206
207 static void
208 typefilter_allow_csc(typefilter_t tf, uint16_t csc)
209 {
210 assert(tf != NULL);
211 setbit(tf, csc);
212 }
213
214 static bool
215 typefilter_is_debugid_allowed(typefilter_t tf, uint32_t id)
216 {
217 assert(tf != NULL);
218 return isset(tf, KDBG_EXTRACT_CSC(id));
219 }
220
221 static mach_port_t
222 typefilter_create_memory_entry(typefilter_t tf)
223 {
224 assert(tf != NULL);
225
226 mach_port_t memory_entry = MACH_PORT_NULL;
227 memory_object_size_t size = TYPEFILTER_ALLOC_SIZE;
228
229 mach_make_memory_entry_64(kernel_map,
230 &size,
231 (memory_object_offset_t)tf,
232 VM_PROT_READ,
233 &memory_entry,
234 MACH_PORT_NULL);
235
236 return memory_entry;
237 }
238
239 static int kdbg_copyin_typefilter(user_addr_t addr, size_t size);
240 static void kdbg_enable_typefilter(void);
241 static void kdbg_disable_typefilter(void);
242
243 /*
244 * External prototypes
245 */
246
247 void task_act_iterate_wth_args(task_t, void (*)(thread_t, void *), void *);
248 void commpage_update_kdebug_state(void); /* XXX sign */
249
250 extern int log_leaks;
251
252 /*
253 * This flag is for testing purposes only -- it's highly experimental and tools
254 * have not been updated to support it.
255 */
256 static bool kdbg_continuous_time = false;
257
258 static inline uint64_t
259 kdbg_timestamp(void)
260 {
261 if (kdbg_continuous_time) {
262 return mach_continuous_time();
263 } else {
264 return mach_absolute_time();
265 }
266 }
267
268 static int kdbg_debug = 0;
269
270 int kdbg_control(int *, u_int, user_addr_t, size_t *);
271
272 static int kdbg_read(user_addr_t, size_t *, vnode_t, vfs_context_t, uint32_t);
273 static int kdbg_readcpumap(user_addr_t, size_t *);
274 static int kdbg_readthrmap_v3(user_addr_t, size_t, int);
275 static int kdbg_readcurthrmap(user_addr_t, size_t *);
276 static int kdbg_setreg(kd_regtype *);
277 static int kdbg_setpidex(kd_regtype *);
278 static int kdbg_setpid(kd_regtype *);
279 static void kdbg_thrmap_init(void);
280 static int kdbg_reinit(bool);
281 static int kdbg_bootstrap(bool);
282 static int kdbg_test(size_t flavor);
283
284 static int kdbg_write_v1_header(bool write_thread_map, vnode_t vp, vfs_context_t ctx);
285 static int kdbg_write_thread_map(vnode_t vp, vfs_context_t ctx);
286 static int kdbg_copyout_thread_map(user_addr_t buffer, size_t *buffer_size);
287 static void kdbg_clear_thread_map(void);
288
289 static bool kdbg_wait(uint64_t timeout_ms, bool locked_wait);
290 static void kdbg_wakeup(void);
291
292 int kdbg_cpumap_init_internal(kd_iop_t* iops, uint32_t cpu_count,
293 uint8_t** cpumap, uint32_t* cpumap_size);
294
295 static kd_threadmap *kdbg_thrmap_init_internal(size_t max_count,
296 vm_size_t *map_size, vm_size_t *map_count);
297
298 static bool kdebug_current_proc_enabled(uint32_t debugid);
299 static errno_t kdebug_check_trace_string(uint32_t debugid, uint64_t str_id);
300
301 int kdbg_write_v3_header(user_addr_t, size_t *, int);
302 int kdbg_write_v3_chunk_header(user_addr_t buffer, uint32_t tag,
303 uint32_t sub_tag, uint64_t length,
304 vnode_t vp, vfs_context_t ctx);
305
306 user_addr_t kdbg_write_v3_event_chunk_header(user_addr_t buffer, uint32_t tag,
307 uint64_t length, vnode_t vp,
308 vfs_context_t ctx);
309
310 // Helper functions
311
312 static int create_buffers(bool);
313 static void delete_buffers(void);
314
315 extern int tasks_count;
316 extern int threads_count;
317 extern void IOSleep(int);
318
319 /* trace enable status */
320 unsigned int kdebug_enable = 0;
321
322 /* A static buffer to record events prior to the start of regular logging */
323
324 #define KD_EARLY_BUFFER_SIZE (16 * 1024)
325 #define KD_EARLY_BUFFER_NBUFS (KD_EARLY_BUFFER_SIZE / sizeof(kd_buf))
326 #if defined(__x86_64__)
327 __attribute__((aligned(KD_EARLY_BUFFER_SIZE)))
328 static kd_buf kd_early_buffer[KD_EARLY_BUFFER_NBUFS];
329 #else /* defined(__x86_64__) */
330 /*
331 * On ARM, the space for this is carved out by osfmk/arm/data.s -- clang
332 * has problems aligning to greater than 4K.
333 */
334 extern kd_buf kd_early_buffer[KD_EARLY_BUFFER_NBUFS];
335 #endif /* !defined(__x86_64__) */
336
337 static unsigned int kd_early_index = 0;
338 static bool kd_early_overflow = false;
339 static bool kd_early_done = false;
340
341 #define SLOW_NOLOG 0x01
342 #define SLOW_CHECKS 0x02
343
344 #define EVENTS_PER_STORAGE_UNIT 2048
345 #define MIN_STORAGE_UNITS_PER_CPU 4
346
347 #define POINTER_FROM_KDS_PTR(x) (&kd_bufs[x.buffer_index].kdsb_addr[x.offset])
348
349 union kds_ptr {
350 struct {
351 uint32_t buffer_index:21;
352 uint16_t offset:11;
353 };
354 uint32_t raw;
355 };
356
357 struct kd_storage {
358 union kds_ptr kds_next;
359 uint32_t kds_bufindx;
360 uint32_t kds_bufcnt;
361 uint32_t kds_readlast;
362 bool kds_lostevents;
363 uint64_t kds_timestamp;
364
365 kd_buf kds_records[EVENTS_PER_STORAGE_UNIT];
366 };
367
368 #define MAX_BUFFER_SIZE (1024 * 1024 * 128)
369 #define N_STORAGE_UNITS_PER_BUFFER (MAX_BUFFER_SIZE / sizeof(struct kd_storage))
370 static_assert(N_STORAGE_UNITS_PER_BUFFER <= 0x7ff,
371 "shoudn't overflow kds_ptr.offset");
372
373 struct kd_storage_buffers {
374 struct kd_storage *kdsb_addr;
375 uint32_t kdsb_size;
376 };
377
378 #define KDS_PTR_NULL 0xffffffff
379 struct kd_storage_buffers *kd_bufs = NULL;
380 int n_storage_units = 0;
381 unsigned int n_storage_buffers = 0;
382 int n_storage_threshold = 0;
383 int kds_waiter = 0;
384
385 #pragma pack(0)
386 struct kd_bufinfo {
387 union kds_ptr kd_list_head;
388 union kds_ptr kd_list_tail;
389 bool kd_lostevents;
390 uint32_t _pad;
391 uint64_t kd_prev_timebase;
392 uint32_t num_bufs;
393 } __attribute__((aligned(MAX_CPU_CACHE_LINE_SIZE)));
394
395
396 /*
397 * In principle, this control block can be shared in DRAM with other
398 * coprocessors and runtimes, for configuring what tracing is enabled.
399 */
400 struct kd_ctrl_page_t {
401 union kds_ptr kds_free_list;
402 uint32_t enabled :1;
403 uint32_t _pad0 :31;
404 int kds_inuse_count;
405 uint32_t kdebug_flags;
406 uint32_t kdebug_slowcheck;
407 uint64_t oldest_time;
408 /*
409 * The number of kd_bufinfo structs allocated may not match the current
410 * number of active cpus. We capture the iops list head at initialization
411 * which we could use to calculate the number of cpus we allocated data for,
412 * unless it happens to be null. To avoid that case, we explicitly also
413 * capture a cpu count.
414 */
415 kd_iop_t* kdebug_iops;
416 uint32_t kdebug_cpus;
417 } kd_ctrl_page = {
418 .kds_free_list = {.raw = KDS_PTR_NULL},
419 .kdebug_slowcheck = SLOW_NOLOG,
420 .oldest_time = 0
421 };
422
423 #pragma pack()
424
425 struct kd_bufinfo *kdbip = NULL;
426
427 #define KDCOPYBUF_COUNT 8192
428 #define KDCOPYBUF_SIZE (KDCOPYBUF_COUNT * sizeof(kd_buf))
429
430 #define PAGE_4KB 4096
431 #define PAGE_16KB 16384
432
433 kd_buf *kdcopybuf = NULL;
434
435 unsigned int nkdbufs = 0;
436 unsigned int kdlog_beg = 0;
437 unsigned int kdlog_end = 0;
438 unsigned int kdlog_value1 = 0;
439 unsigned int kdlog_value2 = 0;
440 unsigned int kdlog_value3 = 0;
441 unsigned int kdlog_value4 = 0;
442
443 static LCK_GRP_DECLARE(kdebug_lck_grp, "kdebug");
444 static LCK_SPIN_DECLARE(kdw_spin_lock, &kdebug_lck_grp);
445 static LCK_SPIN_DECLARE(kds_spin_lock, &kdebug_lck_grp);
446
447 kd_threadmap *kd_mapptr = 0;
448 vm_size_t kd_mapsize = 0;
449 vm_size_t kd_mapcount = 0;
450
451 off_t RAW_file_offset = 0;
452 int RAW_file_written = 0;
453
454 #define RAW_FLUSH_SIZE (2 * 1024 * 1024)
455
456 /*
457 * A globally increasing counter for identifying strings in trace. Starts at
458 * 1 because 0 is a reserved return value.
459 */
460 __attribute__((aligned(MAX_CPU_CACHE_LINE_SIZE)))
461 static uint64_t g_curr_str_id = 1;
462
463 #define STR_ID_SIG_OFFSET (48)
464 #define STR_ID_MASK ((1ULL << STR_ID_SIG_OFFSET) - 1)
465 #define STR_ID_SIG_MASK (~STR_ID_MASK)
466
467 /*
468 * A bit pattern for identifying string IDs generated by
469 * kdebug_trace_string(2).
470 */
471 static uint64_t g_str_id_signature = (0x70acULL << STR_ID_SIG_OFFSET);
472
473 #define INTERRUPT 0x01050000
474 #define MACH_vmfault 0x01300008
475 #define BSC_SysCall 0x040c0000
476 #define MACH_SysCall 0x010c0000
477
478 struct kd_task_name {
479 task_t ktn_task;
480 pid_t ktn_pid;
481 char ktn_name[20];
482 };
483
484 struct kd_resolver {
485 kd_threadmap *krs_map;
486 vm_size_t krs_count;
487 vm_size_t krs_maxcount;
488 struct kd_task_name *krs_task;
489 };
490
491 /*
492 * TRACE file formats...
493 *
494 * RAW_VERSION0
495 *
496 * uint32_t #threadmaps
497 * kd_threadmap[]
498 * kd_buf[]
499 *
500 * RAW_VERSION1
501 *
502 * RAW_header, with version_no set to RAW_VERSION1
503 * kd_threadmap[]
504 * Empty space to pad alignment to the nearest page boundary.
505 * kd_buf[]
506 *
507 * RAW_VERSION1+
508 *
509 * RAW_header, with version_no set to RAW_VERSION1
510 * kd_threadmap[]
511 * kd_cpumap_header, with version_no set to RAW_VERSION1
512 * kd_cpumap[]
513 * Empty space to pad alignment to the nearest page boundary.
514 * kd_buf[]
515 *
516 * V1+ implementation details...
517 *
518 * It would have been nice to add the cpumap data "correctly", but there were
519 * several obstacles. Existing code attempts to parse both V1 and V0 files.
520 * Due to the fact that V0 has no versioning or header, the test looks like
521 * this:
522 *
523 * // Read header
524 * if (header.version_no != RAW_VERSION1) { // Assume V0 }
525 *
526 * If we add a VERSION2 file format, all existing code is going to treat that
527 * as a VERSION0 file when reading it, and crash terribly when trying to read
528 * RAW_VERSION2 threadmap entries.
529 *
530 * To differentiate between a V1 and V1+ file, read as V1 until you reach
531 * the padding bytes. Then:
532 *
533 * boolean_t is_v1plus = FALSE;
534 * if (padding_bytes >= sizeof(kd_cpumap_header)) {
535 * kd_cpumap_header header = // read header;
536 * if (header.version_no == RAW_VERSION1) {
537 * is_v1plus = TRUE;
538 * }
539 * }
540 *
541 */
542
543 #define RAW_VERSION3 0x00001000
544
545 // Version 3 header
546 // The header chunk has the tag 0x00001000 which also serves as a magic word
547 // that identifies the file as a version 3 trace file. The header payload is
548 // a set of fixed fields followed by a variable number of sub-chunks:
549 /*
550 * ____________________________________________________________________________
551 | Offset | Size | Field |
552 | ----------------------------------------------------------------------------
553 | 0 | 4 | Tag (0x00001000) |
554 | 4 | 4 | Sub-tag. Represents the version of the header. |
555 | 8 | 8 | Length of header payload (40+8x) |
556 | 16 | 8 | Time base info. Two 32-bit numbers, numer/denom, |
557 | | | for converting timestamps to nanoseconds. |
558 | 24 | 8 | Timestamp of trace start. |
559 | 32 | 8 | Wall time seconds since Unix epoch. |
560 | | | As returned by gettimeofday(). |
561 | 40 | 4 | Wall time microseconds. As returned by gettimeofday(). |
562 | 44 | 4 | Local time zone offset in minutes. ( " ) |
563 | 48 | 4 | Type of daylight savings time correction to apply. ( " ) |
564 | 52 | 4 | Flags. 1 = 64-bit. Remaining bits should be written |
565 | | | as 0 and ignored when reading. |
566 | 56 | 8x | Variable number of sub-chunks. None are required. |
567 | | | Ignore unknown chunks. |
568 | ----------------------------------------------------------------------------
569 */
570 // NOTE: The header sub-chunks are considered part of the header chunk,
571 // so they must be included in the header chunk’s length field.
572 // The CPU map is an optional sub-chunk of the header chunk. It provides
573 // information about the CPUs that are referenced from the trace events.
574 typedef struct {
575 uint32_t tag;
576 uint32_t sub_tag;
577 uint64_t length;
578 uint32_t timebase_numer;
579 uint32_t timebase_denom;
580 uint64_t timestamp;
581 uint64_t walltime_secs;
582 uint32_t walltime_usecs;
583 uint32_t timezone_minuteswest;
584 uint32_t timezone_dst;
585 uint32_t flags;
586 } __attribute__((packed)) kd_header_v3;
587
588 typedef struct {
589 uint32_t tag;
590 uint32_t sub_tag;
591 uint64_t length;
592 } __attribute__((packed)) kd_chunk_header_v3;
593
594 #define V3_CONFIG 0x00001b00
595 #define V3_CPU_MAP 0x00001c00
596 #define V3_THREAD_MAP 0x00001d00
597 #define V3_RAW_EVENTS 0x00001e00
598 #define V3_NULL_CHUNK 0x00002000
599
600 // The current version of all kernel managed chunks is 1. The
601 // V3_CURRENT_CHUNK_VERSION is added to ease the simple case
602 // when most/all the kernel managed chunks have the same version.
603
604 #define V3_CURRENT_CHUNK_VERSION 1
605 #define V3_HEADER_VERSION V3_CURRENT_CHUNK_VERSION
606 #define V3_CPUMAP_VERSION V3_CURRENT_CHUNK_VERSION
607 #define V3_THRMAP_VERSION V3_CURRENT_CHUNK_VERSION
608 #define V3_EVENT_DATA_VERSION V3_CURRENT_CHUNK_VERSION
609
610 typedef struct krt krt_t;
611
612 static uint32_t
613 kdbg_cpu_count(bool early_trace)
614 {
615 if (early_trace) {
616 #if defined(__x86_64__)
617 return max_ncpus;
618 #else /* defined(__x86_64__) */
619 return ml_get_cpu_count();
620 #endif /* !defined(__x86_64__) */
621 }
622
623 #if defined(__x86_64__)
624 host_basic_info_data_t hinfo;
625 mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
626 host_info((host_t)1 /* BSD_HOST */, HOST_BASIC_INFO, (host_info_t)&hinfo, &count);
627 assert(hinfo.logical_cpu_max > 0);
628 return hinfo.logical_cpu_max;
629 #else /* defined(__x86_64__) */
630 return ml_get_topology_info()->max_cpu_id + 1;
631 #endif /* !defined(__x86_64__) */
632 }
633
634 #if MACH_ASSERT
635
636 static bool
637 kdbg_iop_list_is_valid(kd_iop_t* iop)
638 {
639 if (iop) {
640 /* Is list sorted by cpu_id? */
641 kd_iop_t* temp = iop;
642 do {
643 assert(!temp->next || temp->next->cpu_id == temp->cpu_id - 1);
644 assert(temp->next || (temp->cpu_id == kdbg_cpu_count(false) || temp->cpu_id == kdbg_cpu_count(true)));
645 } while ((temp = temp->next));
646
647 /* Does each entry have a function and a name? */
648 temp = iop;
649 do {
650 assert(temp->callback.func);
651 assert(strlen(temp->callback.iop_name) < sizeof(temp->callback.iop_name));
652 } while ((temp = temp->next));
653 }
654
655 return true;
656 }
657
658 #endif /* MACH_ASSERT */
659
660 static void
661 kdbg_iop_list_callback(kd_iop_t* iop, kd_callback_type type, void* arg)
662 {
663 while (iop) {
664 iop->callback.func(iop->callback.context, type, arg);
665 iop = iop->next;
666 }
667 }
668
669 static void
670 kdbg_set_tracing_enabled(bool enabled, uint32_t trace_type)
671 {
672 /*
673 * Drain any events from IOPs before making the state change. On
674 * enabling, this removes any stale events from before tracing. On
675 * disabling, this saves any events up to the point tracing is disabled.
676 */
677 kdbg_iop_list_callback(kd_ctrl_page.kdebug_iops, KD_CALLBACK_SYNC_FLUSH,
678 NULL);
679
680 int s = ml_set_interrupts_enabled(false);
681 lck_spin_lock_grp(&kds_spin_lock, &kdebug_lck_grp);
682
683 if (enabled) {
684 /*
685 * The oldest valid time is now; reject past events from IOPs.
686 */
687 kd_ctrl_page.oldest_time = kdbg_timestamp();
688 kdebug_enable |= trace_type;
689 kd_ctrl_page.kdebug_slowcheck &= ~SLOW_NOLOG;
690 kd_ctrl_page.enabled = 1;
691 commpage_update_kdebug_state();
692 } else {
693 kdebug_enable &= ~(KDEBUG_ENABLE_TRACE | KDEBUG_ENABLE_PPT);
694 kd_ctrl_page.kdebug_slowcheck |= SLOW_NOLOG;
695 kd_ctrl_page.enabled = 0;
696 commpage_update_kdebug_state();
697 }
698 lck_spin_unlock(&kds_spin_lock);
699 ml_set_interrupts_enabled(s);
700
701 if (enabled) {
702 kdbg_iop_list_callback(kd_ctrl_page.kdebug_iops,
703 KD_CALLBACK_KDEBUG_ENABLED, NULL);
704 } else {
705 kdbg_iop_list_callback(kd_ctrl_page.kdebug_iops,
706 KD_CALLBACK_KDEBUG_DISABLED, NULL);
707 }
708 }
709
710 static void
711 kdbg_set_flags(int slowflag, int enableflag, bool enabled)
712 {
713 int s = ml_set_interrupts_enabled(false);
714 lck_spin_lock_grp(&kds_spin_lock, &kdebug_lck_grp);
715
716 if (enabled) {
717 kd_ctrl_page.kdebug_slowcheck |= slowflag;
718 kdebug_enable |= enableflag;
719 } else {
720 kd_ctrl_page.kdebug_slowcheck &= ~slowflag;
721 kdebug_enable &= ~enableflag;
722 }
723
724 lck_spin_unlock(&kds_spin_lock);
725 ml_set_interrupts_enabled(s);
726 }
727
728 /*
729 * Disable wrapping and return true if trace wrapped, false otherwise.
730 */
731 static bool
732 disable_wrap(uint32_t *old_slowcheck, uint32_t *old_flags)
733 {
734 bool wrapped;
735 int s = ml_set_interrupts_enabled(false);
736 lck_spin_lock_grp(&kds_spin_lock, &kdebug_lck_grp);
737
738 *old_slowcheck = kd_ctrl_page.kdebug_slowcheck;
739 *old_flags = kd_ctrl_page.kdebug_flags;
740
741 wrapped = kd_ctrl_page.kdebug_flags & KDBG_WRAPPED;
742 kd_ctrl_page.kdebug_flags &= ~KDBG_WRAPPED;
743 kd_ctrl_page.kdebug_flags |= KDBG_NOWRAP;
744
745 lck_spin_unlock(&kds_spin_lock);
746 ml_set_interrupts_enabled(s);
747
748 return wrapped;
749 }
750
751 static void
752 enable_wrap(uint32_t old_slowcheck)
753 {
754 int s = ml_set_interrupts_enabled(false);
755 lck_spin_lock_grp(&kds_spin_lock, &kdebug_lck_grp);
756
757 kd_ctrl_page.kdebug_flags &= ~KDBG_NOWRAP;
758
759 if (!(old_slowcheck & SLOW_NOLOG)) {
760 kd_ctrl_page.kdebug_slowcheck &= ~SLOW_NOLOG;
761 }
762
763 lck_spin_unlock(&kds_spin_lock);
764 ml_set_interrupts_enabled(s);
765 }
766
767 static int
768 create_buffers(bool early_trace)
769 {
770 unsigned int i;
771 unsigned int p_buffer_size;
772 unsigned int f_buffer_size;
773 unsigned int f_buffers;
774 int error = 0;
775
776 /*
777 * For the duration of this allocation, trace code will only reference
778 * kdebug_iops. Any iops registered after this enabling will not be
779 * messaged until the buffers are reallocated.
780 *
781 * TLDR; Must read kd_iops once and only once!
782 */
783 kd_ctrl_page.kdebug_iops = kd_iops;
784
785 assert(kdbg_iop_list_is_valid(kd_ctrl_page.kdebug_iops));
786
787 /*
788 * If the list is valid, it is sorted, newest -> oldest. Each iop entry
789 * has a cpu_id of "the older entry + 1", so the highest cpu_id will
790 * be the list head + 1.
791 */
792
793 kd_ctrl_page.kdebug_cpus = kd_ctrl_page.kdebug_iops ? kd_ctrl_page.kdebug_iops->cpu_id + 1 : kdbg_cpu_count(early_trace);
794
795 if (kmem_alloc(kernel_map, (vm_offset_t *)&kdbip, sizeof(struct kd_bufinfo) * kd_ctrl_page.kdebug_cpus, VM_KERN_MEMORY_DIAG) != KERN_SUCCESS) {
796 error = ENOSPC;
797 goto out;
798 }
799
800 if (nkdbufs < (kd_ctrl_page.kdebug_cpus * EVENTS_PER_STORAGE_UNIT * MIN_STORAGE_UNITS_PER_CPU)) {
801 n_storage_units = kd_ctrl_page.kdebug_cpus * MIN_STORAGE_UNITS_PER_CPU;
802 } else {
803 n_storage_units = nkdbufs / EVENTS_PER_STORAGE_UNIT;
804 }
805
806 nkdbufs = n_storage_units * EVENTS_PER_STORAGE_UNIT;
807
808 f_buffers = n_storage_units / N_STORAGE_UNITS_PER_BUFFER;
809 n_storage_buffers = f_buffers;
810
811 f_buffer_size = N_STORAGE_UNITS_PER_BUFFER * sizeof(struct kd_storage);
812 p_buffer_size = (n_storage_units % N_STORAGE_UNITS_PER_BUFFER) * sizeof(struct kd_storage);
813
814 if (p_buffer_size) {
815 n_storage_buffers++;
816 }
817
818 kd_bufs = NULL;
819
820 if (kdcopybuf == 0) {
821 if (kmem_alloc(kernel_map, (vm_offset_t *)&kdcopybuf, (vm_size_t)KDCOPYBUF_SIZE, VM_KERN_MEMORY_DIAG) != KERN_SUCCESS) {
822 error = ENOSPC;
823 goto out;
824 }
825 }
826 if (kmem_alloc(kernel_map, (vm_offset_t *)&kd_bufs, (vm_size_t)(n_storage_buffers * sizeof(struct kd_storage_buffers)), VM_KERN_MEMORY_DIAG) != KERN_SUCCESS) {
827 error = ENOSPC;
828 goto out;
829 }
830 bzero(kd_bufs, n_storage_buffers * sizeof(struct kd_storage_buffers));
831
832 for (i = 0; i < f_buffers; i++) {
833 if (kmem_alloc(kernel_map, (vm_offset_t *)&kd_bufs[i].kdsb_addr, (vm_size_t)f_buffer_size, VM_KERN_MEMORY_DIAG) != KERN_SUCCESS) {
834 error = ENOSPC;
835 goto out;
836 }
837 bzero(kd_bufs[i].kdsb_addr, f_buffer_size);
838
839 kd_bufs[i].kdsb_size = f_buffer_size;
840 }
841 if (p_buffer_size) {
842 if (kmem_alloc(kernel_map, (vm_offset_t *)&kd_bufs[i].kdsb_addr, (vm_size_t)p_buffer_size, VM_KERN_MEMORY_DIAG) != KERN_SUCCESS) {
843 error = ENOSPC;
844 goto out;
845 }
846 bzero(kd_bufs[i].kdsb_addr, p_buffer_size);
847
848 kd_bufs[i].kdsb_size = p_buffer_size;
849 }
850 n_storage_units = 0;
851
852 for (i = 0; i < n_storage_buffers; i++) {
853 struct kd_storage *kds;
854 uint16_t n_elements;
855 static_assert(N_STORAGE_UNITS_PER_BUFFER <= UINT16_MAX);
856 assert(kd_bufs[i].kdsb_size <= N_STORAGE_UNITS_PER_BUFFER *
857 sizeof(struct kd_storage));
858
859 n_elements = kd_bufs[i].kdsb_size / sizeof(struct kd_storage);
860 kds = kd_bufs[i].kdsb_addr;
861
862 for (uint16_t n = 0; n < n_elements; n++) {
863 kds[n].kds_next.buffer_index = kd_ctrl_page.kds_free_list.buffer_index;
864 kds[n].kds_next.offset = kd_ctrl_page.kds_free_list.offset;
865
866 kd_ctrl_page.kds_free_list.buffer_index = i;
867 kd_ctrl_page.kds_free_list.offset = n;
868 }
869 n_storage_units += n_elements;
870 }
871
872 bzero((char *)kdbip, sizeof(struct kd_bufinfo) * kd_ctrl_page.kdebug_cpus);
873
874 for (i = 0; i < kd_ctrl_page.kdebug_cpus; i++) {
875 kdbip[i].kd_list_head.raw = KDS_PTR_NULL;
876 kdbip[i].kd_list_tail.raw = KDS_PTR_NULL;
877 kdbip[i].kd_lostevents = false;
878 kdbip[i].num_bufs = 0;
879 }
880
881 kd_ctrl_page.kdebug_flags |= KDBG_BUFINIT;
882
883 kd_ctrl_page.kds_inuse_count = 0;
884 n_storage_threshold = n_storage_units / 2;
885 out:
886 if (error) {
887 delete_buffers();
888 }
889
890 return error;
891 }
892
893 static void
894 delete_buffers(void)
895 {
896 unsigned int i;
897
898 if (kd_bufs) {
899 for (i = 0; i < n_storage_buffers; i++) {
900 if (kd_bufs[i].kdsb_addr) {
901 kmem_free(kernel_map, (vm_offset_t)kd_bufs[i].kdsb_addr, (vm_size_t)kd_bufs[i].kdsb_size);
902 }
903 }
904 kmem_free(kernel_map, (vm_offset_t)kd_bufs, (vm_size_t)(n_storage_buffers * sizeof(struct kd_storage_buffers)));
905
906 kd_bufs = NULL;
907 n_storage_buffers = 0;
908 }
909 if (kdcopybuf) {
910 kmem_free(kernel_map, (vm_offset_t)kdcopybuf, KDCOPYBUF_SIZE);
911
912 kdcopybuf = NULL;
913 }
914 kd_ctrl_page.kds_free_list.raw = KDS_PTR_NULL;
915
916 if (kdbip) {
917 kmem_free(kernel_map, (vm_offset_t)kdbip, sizeof(struct kd_bufinfo) * kd_ctrl_page.kdebug_cpus);
918
919 kdbip = NULL;
920 }
921 kd_ctrl_page.kdebug_iops = NULL;
922 kd_ctrl_page.kdebug_cpus = 0;
923 kd_ctrl_page.kdebug_flags &= ~KDBG_BUFINIT;
924 }
925
926 void
927 release_storage_unit(int cpu, uint32_t kdsp_raw)
928 {
929 int s = 0;
930 struct kd_storage *kdsp_actual;
931 struct kd_bufinfo *kdbp;
932 union kds_ptr kdsp;
933
934 kdsp.raw = kdsp_raw;
935
936 s = ml_set_interrupts_enabled(false);
937 lck_spin_lock_grp(&kds_spin_lock, &kdebug_lck_grp);
938
939 kdbp = &kdbip[cpu];
940
941 if (kdsp.raw == kdbp->kd_list_head.raw) {
942 /*
943 * it's possible for the storage unit pointed to
944 * by kdsp to have already been stolen... so
945 * check to see if it's still the head of the list
946 * now that we're behind the lock that protects
947 * adding and removing from the queue...
948 * since we only ever release and steal units from
949 * that position, if it's no longer the head
950 * we having nothing to do in this context
951 */
952 kdsp_actual = POINTER_FROM_KDS_PTR(kdsp);
953 kdbp->kd_list_head = kdsp_actual->kds_next;
954
955 kdsp_actual->kds_next = kd_ctrl_page.kds_free_list;
956 kd_ctrl_page.kds_free_list = kdsp;
957
958 kd_ctrl_page.kds_inuse_count--;
959 }
960 lck_spin_unlock(&kds_spin_lock);
961 ml_set_interrupts_enabled(s);
962 }
963
964 bool
965 allocate_storage_unit(int cpu)
966 {
967 union kds_ptr kdsp;
968 struct kd_storage *kdsp_actual, *kdsp_next_actual;
969 struct kd_bufinfo *kdbp, *kdbp_vict, *kdbp_try;
970 uint64_t oldest_ts, ts;
971 bool retval = true;
972 int s = 0;
973
974 s = ml_set_interrupts_enabled(false);
975 lck_spin_lock_grp(&kds_spin_lock, &kdebug_lck_grp);
976
977 kdbp = &kdbip[cpu];
978
979 /* If someone beat us to the allocate, return success */
980 if (kdbp->kd_list_tail.raw != KDS_PTR_NULL) {
981 kdsp_actual = POINTER_FROM_KDS_PTR(kdbp->kd_list_tail);
982
983 if (kdsp_actual->kds_bufindx < EVENTS_PER_STORAGE_UNIT) {
984 goto out;
985 }
986 }
987
988 if ((kdsp = kd_ctrl_page.kds_free_list).raw != KDS_PTR_NULL) {
989 /*
990 * If there's a free page, grab it from the free list.
991 */
992 kdsp_actual = POINTER_FROM_KDS_PTR(kdsp);
993 kd_ctrl_page.kds_free_list = kdsp_actual->kds_next;
994
995 kd_ctrl_page.kds_inuse_count++;
996 } else {
997 /*
998 * Otherwise, we're going to lose events and repurpose the oldest
999 * storage unit we can find.
1000 */
1001 if (kd_ctrl_page.kdebug_flags & KDBG_NOWRAP) {
1002 kd_ctrl_page.kdebug_slowcheck |= SLOW_NOLOG;
1003 kdbp->kd_lostevents = true;
1004 retval = false;
1005 goto out;
1006 }
1007 kdbp_vict = NULL;
1008 oldest_ts = UINT64_MAX;
1009
1010 for (kdbp_try = &kdbip[0]; kdbp_try < &kdbip[kd_ctrl_page.kdebug_cpus]; kdbp_try++) {
1011 if (kdbp_try->kd_list_head.raw == KDS_PTR_NULL) {
1012 /*
1013 * no storage unit to steal
1014 */
1015 continue;
1016 }
1017
1018 kdsp_actual = POINTER_FROM_KDS_PTR(kdbp_try->kd_list_head);
1019
1020 if (kdsp_actual->kds_bufcnt < EVENTS_PER_STORAGE_UNIT) {
1021 /*
1022 * make sure we don't steal the storage unit
1023 * being actively recorded to... need to
1024 * move on because we don't want an out-of-order
1025 * set of events showing up later
1026 */
1027 continue;
1028 }
1029
1030 /*
1031 * When wrapping, steal the storage unit with the
1032 * earliest timestamp on its last event, instead of the
1033 * earliest timestamp on the first event. This allows a
1034 * storage unit with more recent events to be preserved,
1035 * even if the storage unit contains events that are
1036 * older than those found in other CPUs.
1037 */
1038 ts = kdbg_get_timestamp(&kdsp_actual->kds_records[EVENTS_PER_STORAGE_UNIT - 1]);
1039 if (ts < oldest_ts) {
1040 oldest_ts = ts;
1041 kdbp_vict = kdbp_try;
1042 }
1043 }
1044 if (kdbp_vict == NULL) {
1045 kdebug_enable = 0;
1046 kd_ctrl_page.enabled = 0;
1047 commpage_update_kdebug_state();
1048 retval = false;
1049 goto out;
1050 }
1051 kdsp = kdbp_vict->kd_list_head;
1052 kdsp_actual = POINTER_FROM_KDS_PTR(kdsp);
1053 kdbp_vict->kd_list_head = kdsp_actual->kds_next;
1054
1055 if (kdbp_vict->kd_list_head.raw != KDS_PTR_NULL) {
1056 kdsp_next_actual = POINTER_FROM_KDS_PTR(kdbp_vict->kd_list_head);
1057 kdsp_next_actual->kds_lostevents = true;
1058 } else {
1059 kdbp_vict->kd_lostevents = true;
1060 }
1061
1062 if (kd_ctrl_page.oldest_time < oldest_ts) {
1063 kd_ctrl_page.oldest_time = oldest_ts;
1064 }
1065 kd_ctrl_page.kdebug_flags |= KDBG_WRAPPED;
1066 }
1067 kdsp_actual->kds_timestamp = kdbg_timestamp();
1068 kdsp_actual->kds_next.raw = KDS_PTR_NULL;
1069 kdsp_actual->kds_bufcnt = 0;
1070 kdsp_actual->kds_readlast = 0;
1071
1072 kdsp_actual->kds_lostevents = kdbp->kd_lostevents;
1073 kdbp->kd_lostevents = false;
1074 kdsp_actual->kds_bufindx = 0;
1075
1076 if (kdbp->kd_list_head.raw == KDS_PTR_NULL) {
1077 kdbp->kd_list_head = kdsp;
1078 } else {
1079 POINTER_FROM_KDS_PTR(kdbp->kd_list_tail)->kds_next = kdsp;
1080 }
1081 kdbp->kd_list_tail = kdsp;
1082 out:
1083 lck_spin_unlock(&kds_spin_lock);
1084 ml_set_interrupts_enabled(s);
1085
1086 return retval;
1087 }
1088
1089 int
1090 kernel_debug_register_callback(kd_callback_t callback)
1091 {
1092 kd_iop_t* iop;
1093 if (kmem_alloc(kernel_map, (vm_offset_t *)&iop, sizeof(kd_iop_t), VM_KERN_MEMORY_DIAG) == KERN_SUCCESS) {
1094 memcpy(&iop->callback, &callback, sizeof(kd_callback_t));
1095
1096 /*
1097 * <rdar://problem/13351477> Some IOP clients are not providing a name.
1098 *
1099 * Remove when fixed.
1100 */
1101 {
1102 bool is_valid_name = false;
1103 for (uint32_t length = 0; length < sizeof(callback.iop_name); ++length) {
1104 /* This is roughly isprintable(c) */
1105 if (callback.iop_name[length] > 0x20 && callback.iop_name[length] < 0x7F) {
1106 continue;
1107 }
1108 if (callback.iop_name[length] == 0) {
1109 if (length) {
1110 is_valid_name = true;
1111 }
1112 break;
1113 }
1114 }
1115
1116 if (!is_valid_name) {
1117 strlcpy(iop->callback.iop_name, "IOP-???", sizeof(iop->callback.iop_name));
1118 }
1119 }
1120
1121 iop->last_timestamp = 0;
1122
1123 do {
1124 /*
1125 * We use two pieces of state, the old list head
1126 * pointer, and the value of old_list_head->cpu_id.
1127 * If we read kd_iops more than once, it can change
1128 * between reads.
1129 *
1130 * TLDR; Must not read kd_iops more than once per loop.
1131 */
1132 iop->next = kd_iops;
1133 iop->cpu_id = iop->next ? (iop->next->cpu_id + 1) : kdbg_cpu_count(false);
1134
1135 /*
1136 * Header says OSCompareAndSwapPtr has a memory barrier
1137 */
1138 } while (!OSCompareAndSwapPtr(iop->next, iop, (void* volatile*)&kd_iops));
1139
1140 return iop->cpu_id;
1141 }
1142
1143 return 0;
1144 }
1145
1146 void
1147 kernel_debug_enter(
1148 uint32_t coreid,
1149 uint32_t debugid,
1150 uint64_t timestamp,
1151 uintptr_t arg1,
1152 uintptr_t arg2,
1153 uintptr_t arg3,
1154 uintptr_t arg4,
1155 uintptr_t threadid
1156 )
1157 {
1158 uint32_t bindx;
1159 kd_buf *kd;
1160 struct kd_bufinfo *kdbp;
1161 struct kd_storage *kdsp_actual;
1162 union kds_ptr kds_raw;
1163
1164 if (kd_ctrl_page.kdebug_slowcheck) {
1165 if ((kd_ctrl_page.kdebug_slowcheck & SLOW_NOLOG) || !(kdebug_enable & (KDEBUG_ENABLE_TRACE | KDEBUG_ENABLE_PPT))) {
1166 goto out1;
1167 }
1168
1169 if (kd_ctrl_page.kdebug_flags & KDBG_TYPEFILTER_CHECK) {
1170 if (typefilter_is_debugid_allowed(kdbg_typefilter, debugid)) {
1171 goto record_event;
1172 }
1173 goto out1;
1174 } else if (kd_ctrl_page.kdebug_flags & KDBG_RANGECHECK) {
1175 if (debugid >= kdlog_beg && debugid <= kdlog_end) {
1176 goto record_event;
1177 }
1178 goto out1;
1179 } else if (kd_ctrl_page.kdebug_flags & KDBG_VALCHECK) {
1180 if ((debugid & KDBG_EVENTID_MASK) != kdlog_value1 &&
1181 (debugid & KDBG_EVENTID_MASK) != kdlog_value2 &&
1182 (debugid & KDBG_EVENTID_MASK) != kdlog_value3 &&
1183 (debugid & KDBG_EVENTID_MASK) != kdlog_value4) {
1184 goto out1;
1185 }
1186 }
1187 }
1188
1189 record_event:
1190 if (timestamp < kd_ctrl_page.oldest_time) {
1191 goto out1;
1192 }
1193
1194 disable_preemption();
1195
1196 if (kd_ctrl_page.enabled == 0) {
1197 goto out;
1198 }
1199
1200 kdbp = &kdbip[coreid];
1201 timestamp &= KDBG_TIMESTAMP_MASK;
1202
1203 retry_q:
1204 kds_raw = kdbp->kd_list_tail;
1205
1206 if (kds_raw.raw != KDS_PTR_NULL) {
1207 kdsp_actual = POINTER_FROM_KDS_PTR(kds_raw);
1208 bindx = kdsp_actual->kds_bufindx;
1209 } else {
1210 kdsp_actual = NULL;
1211 bindx = EVENTS_PER_STORAGE_UNIT;
1212 }
1213
1214 if (kdsp_actual == NULL || bindx >= EVENTS_PER_STORAGE_UNIT) {
1215 if (allocate_storage_unit(coreid) == false) {
1216 /*
1217 * this can only happen if wrapping
1218 * has been disabled
1219 */
1220 goto out;
1221 }
1222 goto retry_q;
1223 }
1224 if (!OSCompareAndSwap(bindx, bindx + 1, &kdsp_actual->kds_bufindx)) {
1225 goto retry_q;
1226 }
1227
1228 // IOP entries can be allocated before xnu allocates and inits the buffer
1229 if (timestamp < kdsp_actual->kds_timestamp) {
1230 kdsp_actual->kds_timestamp = timestamp;
1231 }
1232
1233 kd = &kdsp_actual->kds_records[bindx];
1234
1235 kd->debugid = debugid;
1236 kd->arg1 = arg1;
1237 kd->arg2 = arg2;
1238 kd->arg3 = arg3;
1239 kd->arg4 = arg4;
1240 kd->arg5 = threadid;
1241
1242 kdbg_set_timestamp_and_cpu(kd, timestamp, coreid);
1243
1244 OSAddAtomic(1, &kdsp_actual->kds_bufcnt);
1245 out:
1246 enable_preemption();
1247 out1:
1248 if ((kds_waiter && kd_ctrl_page.kds_inuse_count >= n_storage_threshold)) {
1249 kdbg_wakeup();
1250 }
1251 }
1252
1253 /*
1254 * Check if the given debug ID is allowed to be traced on the current process.
1255 *
1256 * Returns true if allowed and false otherwise.
1257 */
1258 static inline bool
1259 kdebug_debugid_procfilt_allowed(uint32_t debugid)
1260 {
1261 uint32_t procfilt_flags = kd_ctrl_page.kdebug_flags &
1262 (KDBG_PIDCHECK | KDBG_PIDEXCLUDE);
1263
1264 if (!procfilt_flags) {
1265 return true;
1266 }
1267
1268 /*
1269 * DBG_TRACE and MACH_SCHED tracepoints ignore the process filter.
1270 */
1271 if ((debugid & 0xffff0000) == MACHDBG_CODE(DBG_MACH_SCHED, 0) ||
1272 (debugid >> 24 == DBG_TRACE)) {
1273 return true;
1274 }
1275
1276 struct proc *curproc = current_proc();
1277 /*
1278 * If the process is missing (early in boot), allow it.
1279 */
1280 if (!curproc) {
1281 return true;
1282 }
1283
1284 if (procfilt_flags & KDBG_PIDCHECK) {
1285 /*
1286 * Allow only processes marked with the kdebug bit.
1287 */
1288 return curproc->p_kdebug;
1289 } else if (procfilt_flags & KDBG_PIDEXCLUDE) {
1290 /*
1291 * Exclude any process marked with the kdebug bit.
1292 */
1293 return !curproc->p_kdebug;
1294 } else {
1295 panic("kdebug: invalid procfilt flags %x", kd_ctrl_page.kdebug_flags);
1296 __builtin_unreachable();
1297 }
1298 }
1299
1300 static void
1301 kernel_debug_internal(
1302 uint32_t debugid,
1303 uintptr_t arg1,
1304 uintptr_t arg2,
1305 uintptr_t arg3,
1306 uintptr_t arg4,
1307 uintptr_t arg5,
1308 uint64_t flags)
1309 {
1310 uint64_t now;
1311 uint32_t bindx;
1312 kd_buf *kd;
1313 int cpu;
1314 struct kd_bufinfo *kdbp;
1315 struct kd_storage *kdsp_actual;
1316 union kds_ptr kds_raw;
1317 bool only_filter = flags & KDBG_FLAG_FILTERED;
1318 bool observe_procfilt = !(flags & KDBG_FLAG_NOPROCFILT);
1319
1320 if (kd_ctrl_page.kdebug_slowcheck) {
1321 if ((kd_ctrl_page.kdebug_slowcheck & SLOW_NOLOG) ||
1322 !(kdebug_enable & (KDEBUG_ENABLE_TRACE | KDEBUG_ENABLE_PPT))) {
1323 goto out1;
1324 }
1325
1326 if (!ml_at_interrupt_context() && observe_procfilt &&
1327 !kdebug_debugid_procfilt_allowed(debugid)) {
1328 goto out1;
1329 }
1330
1331 if (kd_ctrl_page.kdebug_flags & KDBG_TYPEFILTER_CHECK) {
1332 if (typefilter_is_debugid_allowed(kdbg_typefilter, debugid)) {
1333 goto record_event;
1334 }
1335
1336 goto out1;
1337 } else if (only_filter) {
1338 goto out1;
1339 } else if (kd_ctrl_page.kdebug_flags & KDBG_RANGECHECK) {
1340 /* Always record trace system info */
1341 if (KDBG_EXTRACT_CLASS(debugid) == DBG_TRACE) {
1342 goto record_event;
1343 }
1344
1345 if (debugid < kdlog_beg || debugid > kdlog_end) {
1346 goto out1;
1347 }
1348 } else if (kd_ctrl_page.kdebug_flags & KDBG_VALCHECK) {
1349 /* Always record trace system info */
1350 if (KDBG_EXTRACT_CLASS(debugid) == DBG_TRACE) {
1351 goto record_event;
1352 }
1353
1354 if ((debugid & KDBG_EVENTID_MASK) != kdlog_value1 &&
1355 (debugid & KDBG_EVENTID_MASK) != kdlog_value2 &&
1356 (debugid & KDBG_EVENTID_MASK) != kdlog_value3 &&
1357 (debugid & KDBG_EVENTID_MASK) != kdlog_value4) {
1358 goto out1;
1359 }
1360 }
1361 } else if (only_filter) {
1362 goto out1;
1363 }
1364
1365 record_event:
1366 disable_preemption();
1367
1368 if (kd_ctrl_page.enabled == 0) {
1369 goto out;
1370 }
1371
1372 cpu = cpu_number();
1373 kdbp = &kdbip[cpu];
1374
1375 retry_q:
1376 kds_raw = kdbp->kd_list_tail;
1377
1378 if (kds_raw.raw != KDS_PTR_NULL) {
1379 kdsp_actual = POINTER_FROM_KDS_PTR(kds_raw);
1380 bindx = kdsp_actual->kds_bufindx;
1381 } else {
1382 kdsp_actual = NULL;
1383 bindx = EVENTS_PER_STORAGE_UNIT;
1384 }
1385
1386 if (kdsp_actual == NULL || bindx >= EVENTS_PER_STORAGE_UNIT) {
1387 if (allocate_storage_unit(cpu) == false) {
1388 /*
1389 * this can only happen if wrapping
1390 * has been disabled
1391 */
1392 goto out;
1393 }
1394 goto retry_q;
1395 }
1396
1397 now = kdbg_timestamp() & KDBG_TIMESTAMP_MASK;
1398
1399 if (!OSCompareAndSwap(bindx, bindx + 1, &kdsp_actual->kds_bufindx)) {
1400 goto retry_q;
1401 }
1402
1403 kd = &kdsp_actual->kds_records[bindx];
1404
1405 kd->debugid = debugid;
1406 kd->arg1 = arg1;
1407 kd->arg2 = arg2;
1408 kd->arg3 = arg3;
1409 kd->arg4 = arg4;
1410 kd->arg5 = arg5;
1411
1412 kdbg_set_timestamp_and_cpu(kd, now, cpu);
1413
1414 OSAddAtomic(1, &kdsp_actual->kds_bufcnt);
1415
1416 #if KPERF
1417 kperf_kdebug_callback(debugid, __builtin_frame_address(0));
1418 #endif
1419 out:
1420 enable_preemption();
1421 out1:
1422 if (kds_waiter && kd_ctrl_page.kds_inuse_count >= n_storage_threshold) {
1423 uint32_t etype;
1424 uint32_t stype;
1425
1426 etype = debugid & KDBG_EVENTID_MASK;
1427 stype = debugid & KDBG_CSC_MASK;
1428
1429 if (etype == INTERRUPT || etype == MACH_vmfault ||
1430 stype == BSC_SysCall || stype == MACH_SysCall) {
1431 kdbg_wakeup();
1432 }
1433 }
1434 }
1435
1436 __attribute__((noinline))
1437 void
1438 kernel_debug(
1439 uint32_t debugid,
1440 uintptr_t arg1,
1441 uintptr_t arg2,
1442 uintptr_t arg3,
1443 uintptr_t arg4,
1444 __unused uintptr_t arg5)
1445 {
1446 kernel_debug_internal(debugid, arg1, arg2, arg3, arg4,
1447 (uintptr_t)thread_tid(current_thread()), 0);
1448 }
1449
1450 __attribute__((noinline))
1451 void
1452 kernel_debug1(
1453 uint32_t debugid,
1454 uintptr_t arg1,
1455 uintptr_t arg2,
1456 uintptr_t arg3,
1457 uintptr_t arg4,
1458 uintptr_t arg5)
1459 {
1460 kernel_debug_internal(debugid, arg1, arg2, arg3, arg4, arg5, 0);
1461 }
1462
1463 __attribute__((noinline))
1464 void
1465 kernel_debug_flags(
1466 uint32_t debugid,
1467 uintptr_t arg1,
1468 uintptr_t arg2,
1469 uintptr_t arg3,
1470 uintptr_t arg4,
1471 uint64_t flags)
1472 {
1473 kernel_debug_internal(debugid, arg1, arg2, arg3, arg4,
1474 (uintptr_t)thread_tid(current_thread()), flags);
1475 }
1476
1477 __attribute__((noinline))
1478 void
1479 kernel_debug_filtered(
1480 uint32_t debugid,
1481 uintptr_t arg1,
1482 uintptr_t arg2,
1483 uintptr_t arg3,
1484 uintptr_t arg4)
1485 {
1486 kernel_debug_flags(debugid, arg1, arg2, arg3, arg4, KDBG_FLAG_FILTERED);
1487 }
1488
1489 void
1490 kernel_debug_string_early(const char *message)
1491 {
1492 uintptr_t arg[4] = {0, 0, 0, 0};
1493
1494 /* Stuff the message string in the args and log it. */
1495 strncpy((char *)arg, message, MIN(sizeof(arg), strlen(message)));
1496 KERNEL_DEBUG_EARLY(
1497 TRACE_INFO_STRING,
1498 arg[0], arg[1], arg[2], arg[3]);
1499 }
1500
1501 #define SIMPLE_STR_LEN (64)
1502 static_assert(SIMPLE_STR_LEN % sizeof(uintptr_t) == 0);
1503
1504 void
1505 kernel_debug_string_simple(uint32_t eventid, const char *str)
1506 {
1507 if (!kdebug_enable) {
1508 return;
1509 }
1510
1511 /* array of uintptr_ts simplifies emitting the string as arguments */
1512 uintptr_t str_buf[(SIMPLE_STR_LEN / sizeof(uintptr_t)) + 1] = { 0 };
1513 size_t len = strlcpy((char *)str_buf, str, SIMPLE_STR_LEN + 1);
1514
1515 uintptr_t thread_id = (uintptr_t)thread_tid(current_thread());
1516 uint32_t debugid = eventid | DBG_FUNC_START;
1517
1518 /* string can fit in a single tracepoint */
1519 if (len <= (4 * sizeof(uintptr_t))) {
1520 debugid |= DBG_FUNC_END;
1521 }
1522
1523 kernel_debug_internal(debugid, str_buf[0],
1524 str_buf[1],
1525 str_buf[2],
1526 str_buf[3], thread_id, 0);
1527
1528 debugid &= KDBG_EVENTID_MASK;
1529 int i = 4;
1530 size_t written = 4 * sizeof(uintptr_t);
1531
1532 for (; written < len; i += 4, written += 4 * sizeof(uintptr_t)) {
1533 /* if this is the last tracepoint to be emitted */
1534 if ((written + (4 * sizeof(uintptr_t))) >= len) {
1535 debugid |= DBG_FUNC_END;
1536 }
1537 kernel_debug_internal(debugid, str_buf[i],
1538 str_buf[i + 1],
1539 str_buf[i + 2],
1540 str_buf[i + 3], thread_id, 0);
1541 }
1542 }
1543
1544 extern int master_cpu; /* MACH_KERNEL_PRIVATE */
1545 /*
1546 * Used prior to start_kern_tracing() being called.
1547 * Log temporarily into a static buffer.
1548 */
1549 void
1550 kernel_debug_early(
1551 uint32_t debugid,
1552 uintptr_t arg1,
1553 uintptr_t arg2,
1554 uintptr_t arg3,
1555 uintptr_t arg4)
1556 {
1557 #if defined(__x86_64__)
1558 extern int early_boot;
1559 /*
1560 * Note that "early" isn't early enough in some cases where
1561 * we're invoked before gsbase is set on x86, hence the
1562 * check of "early_boot".
1563 */
1564 if (early_boot) {
1565 return;
1566 }
1567 #endif
1568
1569 /* If early tracing is over, use the normal path. */
1570 if (kd_early_done) {
1571 KDBG_RELEASE(debugid, arg1, arg2, arg3, arg4);
1572 return;
1573 }
1574
1575 /* Do nothing if the buffer is full or we're not on the boot cpu. */
1576 kd_early_overflow = kd_early_index >= KD_EARLY_BUFFER_NBUFS;
1577 if (kd_early_overflow || cpu_number() != master_cpu) {
1578 return;
1579 }
1580
1581 kd_early_buffer[kd_early_index].debugid = debugid;
1582 kd_early_buffer[kd_early_index].timestamp = mach_absolute_time();
1583 kd_early_buffer[kd_early_index].arg1 = arg1;
1584 kd_early_buffer[kd_early_index].arg2 = arg2;
1585 kd_early_buffer[kd_early_index].arg3 = arg3;
1586 kd_early_buffer[kd_early_index].arg4 = arg4;
1587 kd_early_buffer[kd_early_index].arg5 = 0;
1588 kd_early_index++;
1589 }
1590
1591 /*
1592 * Transfer the contents of the temporary buffer into the trace buffers.
1593 * Precede that by logging the rebase time (offset) - the TSC-based time (in ns)
1594 * when mach_absolute_time is set to 0.
1595 */
1596 static void
1597 kernel_debug_early_end(void)
1598 {
1599 if (cpu_number() != master_cpu) {
1600 panic("kernel_debug_early_end() not call on boot processor");
1601 }
1602
1603 /* reset the current oldest time to allow early events */
1604 kd_ctrl_page.oldest_time = 0;
1605
1606 #if defined(__x86_64__)
1607 /* Fake sentinel marking the start of kernel time relative to TSC */
1608 kernel_debug_enter(0, TRACE_TIMESTAMPS, 0,
1609 (uint32_t)(tsc_rebase_abs_time >> 32), (uint32_t)tsc_rebase_abs_time,
1610 tsc_at_boot, 0, 0);
1611 #endif /* defined(__x86_64__) */
1612 for (unsigned int i = 0; i < kd_early_index; i++) {
1613 kernel_debug_enter(0,
1614 kd_early_buffer[i].debugid,
1615 kd_early_buffer[i].timestamp,
1616 kd_early_buffer[i].arg1,
1617 kd_early_buffer[i].arg2,
1618 kd_early_buffer[i].arg3,
1619 kd_early_buffer[i].arg4,
1620 0);
1621 }
1622
1623 /* Cut events-lost event on overflow */
1624 if (kd_early_overflow) {
1625 KDBG_RELEASE(TRACE_LOST_EVENTS, 1);
1626 }
1627
1628 kd_early_done = true;
1629
1630 /* This trace marks the start of kernel tracing */
1631 kernel_debug_string_early("early trace done");
1632 }
1633
1634 void
1635 kernel_debug_disable(void)
1636 {
1637 if (kdebug_enable) {
1638 kdbg_set_tracing_enabled(false, 0);
1639 }
1640 }
1641
1642 /*
1643 * Returns non-zero if debugid is in a reserved class.
1644 */
1645 static int
1646 kdebug_validate_debugid(uint32_t debugid)
1647 {
1648 uint8_t debugid_class;
1649
1650 debugid_class = KDBG_EXTRACT_CLASS(debugid);
1651 switch (debugid_class) {
1652 case DBG_TRACE:
1653 return EPERM;
1654 }
1655
1656 return 0;
1657 }
1658
1659 /*
1660 * Support syscall SYS_kdebug_typefilter.
1661 */
1662 int
1663 kdebug_typefilter(__unused struct proc* p,
1664 struct kdebug_typefilter_args* uap,
1665 __unused int *retval)
1666 {
1667 int ret = KERN_SUCCESS;
1668
1669 if (uap->addr == USER_ADDR_NULL ||
1670 uap->size == USER_ADDR_NULL) {
1671 return EINVAL;
1672 }
1673
1674 /*
1675 * The atomic load is to close a race window with setting the typefilter
1676 * and memory entry values. A description follows:
1677 *
1678 * Thread 1 (writer)
1679 *
1680 * Allocate Typefilter
1681 * Allocate MemoryEntry
1682 * Write Global MemoryEntry Ptr
1683 * Atomic Store (Release) Global Typefilter Ptr
1684 *
1685 * Thread 2 (reader, AKA us)
1686 *
1687 * if ((Atomic Load (Acquire) Global Typefilter Ptr) == NULL)
1688 * return;
1689 *
1690 * Without the atomic store, it isn't guaranteed that the write of
1691 * Global MemoryEntry Ptr is visible before we can see the write of
1692 * Global Typefilter Ptr.
1693 *
1694 * Without the atomic load, it isn't guaranteed that the loads of
1695 * Global MemoryEntry Ptr aren't speculated.
1696 *
1697 * The global pointers transition from NULL -> valid once and only once,
1698 * and never change after becoming valid. This means that having passed
1699 * the first atomic load test of Global Typefilter Ptr, this function
1700 * can then safely use the remaining global state without atomic checks.
1701 */
1702 if (!os_atomic_load(&kdbg_typefilter, acquire)) {
1703 return EINVAL;
1704 }
1705
1706 assert(kdbg_typefilter_memory_entry);
1707
1708 mach_vm_offset_t user_addr = 0;
1709 vm_map_t user_map = current_map();
1710
1711 ret = mach_to_bsd_errno(
1712 mach_vm_map_kernel(user_map, // target map
1713 &user_addr, // [in, out] target address
1714 TYPEFILTER_ALLOC_SIZE, // initial size
1715 0, // mask (alignment?)
1716 VM_FLAGS_ANYWHERE, // flags
1717 VM_MAP_KERNEL_FLAGS_NONE,
1718 VM_KERN_MEMORY_NONE,
1719 kdbg_typefilter_memory_entry, // port (memory entry!)
1720 0, // offset (in memory entry)
1721 false, // should copy
1722 VM_PROT_READ, // cur_prot
1723 VM_PROT_READ, // max_prot
1724 VM_INHERIT_SHARE)); // inherit behavior on fork
1725
1726 if (ret == KERN_SUCCESS) {
1727 vm_size_t user_ptr_size = vm_map_is_64bit(user_map) ? 8 : 4;
1728 ret = copyout(CAST_DOWN(void *, &user_addr), uap->addr, user_ptr_size );
1729
1730 if (ret != KERN_SUCCESS) {
1731 mach_vm_deallocate(user_map, user_addr, TYPEFILTER_ALLOC_SIZE);
1732 }
1733 }
1734
1735 return ret;
1736 }
1737
1738 /*
1739 * Support syscall SYS_kdebug_trace. U64->K32 args may get truncated in kdebug_trace64
1740 */
1741 int
1742 kdebug_trace(struct proc *p, struct kdebug_trace_args *uap, int32_t *retval)
1743 {
1744 struct kdebug_trace64_args uap64;
1745
1746 uap64.code = uap->code;
1747 uap64.arg1 = uap->arg1;
1748 uap64.arg2 = uap->arg2;
1749 uap64.arg3 = uap->arg3;
1750 uap64.arg4 = uap->arg4;
1751
1752 return kdebug_trace64(p, &uap64, retval);
1753 }
1754
1755 /*
1756 * Support syscall SYS_kdebug_trace64. 64-bit args on K32 will get truncated
1757 * to fit in 32-bit record format.
1758 *
1759 * It is intentional that error conditions are not checked until kdebug is
1760 * enabled. This is to match the userspace wrapper behavior, which is optimizing
1761 * for non-error case performance.
1762 */
1763 int
1764 kdebug_trace64(__unused struct proc *p, struct kdebug_trace64_args *uap, __unused int32_t *retval)
1765 {
1766 int err;
1767
1768 if (__probable(kdebug_enable == 0)) {
1769 return 0;
1770 }
1771
1772 if ((err = kdebug_validate_debugid(uap->code)) != 0) {
1773 return err;
1774 }
1775
1776 kernel_debug_internal(uap->code, (uintptr_t)uap->arg1,
1777 (uintptr_t)uap->arg2, (uintptr_t)uap->arg3, (uintptr_t)uap->arg4,
1778 (uintptr_t)thread_tid(current_thread()), 0);
1779
1780 return 0;
1781 }
1782
1783 /*
1784 * Adding enough padding to contain a full tracepoint for the last
1785 * portion of the string greatly simplifies the logic of splitting the
1786 * string between tracepoints. Full tracepoints can be generated using
1787 * the buffer itself, without having to manually add zeros to pad the
1788 * arguments.
1789 */
1790
1791 /* 2 string args in first tracepoint and 9 string data tracepoints */
1792 #define STR_BUF_ARGS (2 + (9 * 4))
1793 /* times the size of each arg on K64 */
1794 #define MAX_STR_LEN (STR_BUF_ARGS * sizeof(uint64_t))
1795 /* on K32, ending straddles a tracepoint, so reserve blanks */
1796 #define STR_BUF_SIZE (MAX_STR_LEN + (2 * sizeof(uint32_t)))
1797
1798 /*
1799 * This function does no error checking and assumes that it is called with
1800 * the correct arguments, including that the buffer pointed to by str is at
1801 * least STR_BUF_SIZE bytes. However, str must be aligned to word-size and
1802 * be NUL-terminated. In cases where a string can fit evenly into a final
1803 * tracepoint without its NUL-terminator, this function will not end those
1804 * strings with a NUL in trace. It's up to clients to look at the function
1805 * qualifier for DBG_FUNC_END in this case, to end the string.
1806 */
1807 static uint64_t
1808 kernel_debug_string_internal(uint32_t debugid, uint64_t str_id, void *vstr,
1809 size_t str_len)
1810 {
1811 /* str must be word-aligned */
1812 uintptr_t *str = vstr;
1813 size_t written = 0;
1814 uintptr_t thread_id;
1815 int i;
1816 uint32_t trace_debugid = TRACEDBG_CODE(DBG_TRACE_STRING,
1817 TRACE_STRING_GLOBAL);
1818
1819 thread_id = (uintptr_t)thread_tid(current_thread());
1820
1821 /* if the ID is being invalidated, just emit that */
1822 if (str_id != 0 && str_len == 0) {
1823 kernel_debug_internal(trace_debugid | DBG_FUNC_START | DBG_FUNC_END,
1824 (uintptr_t)debugid, (uintptr_t)str_id, 0, 0, thread_id, 0);
1825 return str_id;
1826 }
1827
1828 /* generate an ID, if necessary */
1829 if (str_id == 0) {
1830 str_id = OSIncrementAtomic64((SInt64 *)&g_curr_str_id);
1831 str_id = (str_id & STR_ID_MASK) | g_str_id_signature;
1832 }
1833
1834 trace_debugid |= DBG_FUNC_START;
1835 /* string can fit in a single tracepoint */
1836 if (str_len <= (2 * sizeof(uintptr_t))) {
1837 trace_debugid |= DBG_FUNC_END;
1838 }
1839
1840 kernel_debug_internal(trace_debugid, (uintptr_t)debugid, (uintptr_t)str_id,
1841 str[0], str[1], thread_id, 0);
1842
1843 trace_debugid &= KDBG_EVENTID_MASK;
1844 i = 2;
1845 written += 2 * sizeof(uintptr_t);
1846
1847 for (; written < str_len; i += 4, written += 4 * sizeof(uintptr_t)) {
1848 if ((written + (4 * sizeof(uintptr_t))) >= str_len) {
1849 trace_debugid |= DBG_FUNC_END;
1850 }
1851 kernel_debug_internal(trace_debugid, str[i],
1852 str[i + 1],
1853 str[i + 2],
1854 str[i + 3], thread_id, 0);
1855 }
1856
1857 return str_id;
1858 }
1859
1860 /*
1861 * Returns true if the current process can emit events, and false otherwise.
1862 * Trace system and scheduling events circumvent this check, as do events
1863 * emitted in interrupt context.
1864 */
1865 static bool
1866 kdebug_current_proc_enabled(uint32_t debugid)
1867 {
1868 /* can't determine current process in interrupt context */
1869 if (ml_at_interrupt_context()) {
1870 return true;
1871 }
1872
1873 /* always emit trace system and scheduling events */
1874 if ((KDBG_EXTRACT_CLASS(debugid) == DBG_TRACE ||
1875 (debugid & KDBG_CSC_MASK) == MACHDBG_CODE(DBG_MACH_SCHED, 0))) {
1876 return true;
1877 }
1878
1879 if (kd_ctrl_page.kdebug_flags & KDBG_PIDCHECK) {
1880 proc_t cur_proc = current_proc();
1881
1882 /* only the process with the kdebug bit set is allowed */
1883 if (cur_proc && !(cur_proc->p_kdebug)) {
1884 return false;
1885 }
1886 } else if (kd_ctrl_page.kdebug_flags & KDBG_PIDEXCLUDE) {
1887 proc_t cur_proc = current_proc();
1888
1889 /* every process except the one with the kdebug bit set is allowed */
1890 if (cur_proc && cur_proc->p_kdebug) {
1891 return false;
1892 }
1893 }
1894
1895 return true;
1896 }
1897
1898 bool
1899 kdebug_debugid_enabled(uint32_t debugid)
1900 {
1901 /* if no filtering is enabled */
1902 if (!kd_ctrl_page.kdebug_slowcheck) {
1903 return true;
1904 }
1905
1906 return kdebug_debugid_explicitly_enabled(debugid);
1907 }
1908
1909 bool
1910 kdebug_debugid_explicitly_enabled(uint32_t debugid)
1911 {
1912 if (kd_ctrl_page.kdebug_flags & KDBG_TYPEFILTER_CHECK) {
1913 return typefilter_is_debugid_allowed(kdbg_typefilter, debugid);
1914 } else if (KDBG_EXTRACT_CLASS(debugid) == DBG_TRACE) {
1915 return true;
1916 } else if (kd_ctrl_page.kdebug_flags & KDBG_RANGECHECK) {
1917 if (debugid < kdlog_beg || debugid > kdlog_end) {
1918 return false;
1919 }
1920 } else if (kd_ctrl_page.kdebug_flags & KDBG_VALCHECK) {
1921 if ((debugid & KDBG_EVENTID_MASK) != kdlog_value1 &&
1922 (debugid & KDBG_EVENTID_MASK) != kdlog_value2 &&
1923 (debugid & KDBG_EVENTID_MASK) != kdlog_value3 &&
1924 (debugid & KDBG_EVENTID_MASK) != kdlog_value4) {
1925 return false;
1926 }
1927 }
1928
1929 return true;
1930 }
1931
1932 bool
1933 kdebug_using_continuous_time(void)
1934 {
1935 return kdebug_enable & KDEBUG_ENABLE_CONT_TIME;
1936 }
1937
1938 /*
1939 * Returns 0 if a string can be traced with these arguments. Returns errno
1940 * value if error occurred.
1941 */
1942 static errno_t
1943 kdebug_check_trace_string(uint32_t debugid, uint64_t str_id)
1944 {
1945 /* if there are function qualifiers on the debugid */
1946 if (debugid & ~KDBG_EVENTID_MASK) {
1947 return EINVAL;
1948 }
1949
1950 if (kdebug_validate_debugid(debugid)) {
1951 return EPERM;
1952 }
1953
1954 if (str_id != 0 && (str_id & STR_ID_SIG_MASK) != g_str_id_signature) {
1955 return EINVAL;
1956 }
1957
1958 return 0;
1959 }
1960
1961 /*
1962 * Implementation of KPI kernel_debug_string.
1963 */
1964 int
1965 kernel_debug_string(uint32_t debugid, uint64_t *str_id, const char *str)
1966 {
1967 /* arguments to tracepoints must be word-aligned */
1968 __attribute__((aligned(sizeof(uintptr_t)))) char str_buf[STR_BUF_SIZE];
1969 static_assert(sizeof(str_buf) > MAX_STR_LEN);
1970 vm_size_t len_copied;
1971 int err;
1972
1973 assert(str_id);
1974
1975 if (__probable(kdebug_enable == 0)) {
1976 return 0;
1977 }
1978
1979 if (!kdebug_current_proc_enabled(debugid)) {
1980 return 0;
1981 }
1982
1983 if (!kdebug_debugid_enabled(debugid)) {
1984 return 0;
1985 }
1986
1987 if ((err = kdebug_check_trace_string(debugid, *str_id)) != 0) {
1988 return err;
1989 }
1990
1991 if (str == NULL) {
1992 if (str_id == 0) {
1993 return EINVAL;
1994 }
1995
1996 *str_id = kernel_debug_string_internal(debugid, *str_id, NULL, 0);
1997 return 0;
1998 }
1999
2000 memset(str_buf, 0, sizeof(str_buf));
2001 len_copied = strlcpy(str_buf, str, MAX_STR_LEN + 1);
2002 *str_id = kernel_debug_string_internal(debugid, *str_id, str_buf,
2003 len_copied);
2004 return 0;
2005 }
2006
2007 /*
2008 * Support syscall kdebug_trace_string.
2009 */
2010 int
2011 kdebug_trace_string(__unused struct proc *p,
2012 struct kdebug_trace_string_args *uap,
2013 uint64_t *retval)
2014 {
2015 __attribute__((aligned(sizeof(uintptr_t)))) char str_buf[STR_BUF_SIZE];
2016 static_assert(sizeof(str_buf) > MAX_STR_LEN);
2017 size_t len_copied;
2018 int err;
2019
2020 if (__probable(kdebug_enable == 0)) {
2021 return 0;
2022 }
2023
2024 if (!kdebug_current_proc_enabled(uap->debugid)) {
2025 return 0;
2026 }
2027
2028 if (!kdebug_debugid_enabled(uap->debugid)) {
2029 return 0;
2030 }
2031
2032 if ((err = kdebug_check_trace_string(uap->debugid, uap->str_id)) != 0) {
2033 return err;
2034 }
2035
2036 if (uap->str == USER_ADDR_NULL) {
2037 if (uap->str_id == 0) {
2038 return EINVAL;
2039 }
2040
2041 *retval = kernel_debug_string_internal(uap->debugid, uap->str_id,
2042 NULL, 0);
2043 return 0;
2044 }
2045
2046 memset(str_buf, 0, sizeof(str_buf));
2047 err = copyinstr(uap->str, str_buf, MAX_STR_LEN + 1, &len_copied);
2048
2049 /* it's alright to truncate the string, so allow ENAMETOOLONG */
2050 if (err == ENAMETOOLONG) {
2051 str_buf[MAX_STR_LEN] = '\0';
2052 } else if (err) {
2053 return err;
2054 }
2055
2056 if (len_copied <= 1) {
2057 return EINVAL;
2058 }
2059
2060 /* convert back to a length */
2061 len_copied--;
2062
2063 *retval = kernel_debug_string_internal(uap->debugid, uap->str_id, str_buf,
2064 len_copied);
2065 return 0;
2066 }
2067
2068 int
2069 kdbg_bootstrap(bool early_trace)
2070 {
2071 kd_ctrl_page.kdebug_flags &= ~KDBG_WRAPPED;
2072
2073 return create_buffers(early_trace);
2074 }
2075
2076 int
2077 kdbg_reinit(bool early_trace)
2078 {
2079 int ret = 0;
2080
2081 /*
2082 * Disable trace collecting
2083 * First make sure we're not in
2084 * the middle of cutting a trace
2085 */
2086 kernel_debug_disable();
2087
2088 /*
2089 * make sure the SLOW_NOLOG is seen
2090 * by everyone that might be trying
2091 * to cut a trace..
2092 */
2093 IOSleep(100);
2094
2095 delete_buffers();
2096
2097 kdbg_clear_thread_map();
2098 ret = kdbg_bootstrap(early_trace);
2099
2100 RAW_file_offset = 0;
2101 RAW_file_written = 0;
2102
2103 return ret;
2104 }
2105
2106 void
2107 kdbg_trace_data(struct proc *proc, long *arg_pid, long *arg_uniqueid)
2108 {
2109 if (!proc) {
2110 *arg_pid = 0;
2111 *arg_uniqueid = 0;
2112 } else {
2113 *arg_pid = proc->p_pid;
2114 /* Fit in a trace point */
2115 *arg_uniqueid = (long)proc->p_uniqueid;
2116 if ((uint64_t) *arg_uniqueid != proc->p_uniqueid) {
2117 *arg_uniqueid = 0;
2118 }
2119 }
2120 }
2121
2122
2123 void
2124 kdbg_trace_string(struct proc *proc, long *arg1, long *arg2, long *arg3,
2125 long *arg4)
2126 {
2127 if (!proc) {
2128 *arg1 = 0;
2129 *arg2 = 0;
2130 *arg3 = 0;
2131 *arg4 = 0;
2132 return;
2133 }
2134
2135 const char *procname = proc_best_name(proc);
2136 size_t namelen = strlen(procname);
2137
2138 long args[4] = { 0 };
2139
2140 if (namelen > sizeof(args)) {
2141 namelen = sizeof(args);
2142 }
2143
2144 strncpy((char *)args, procname, namelen);
2145
2146 *arg1 = args[0];
2147 *arg2 = args[1];
2148 *arg3 = args[2];
2149 *arg4 = args[3];
2150 }
2151
2152 /*
2153 *
2154 * Writes a cpumap for the given iops_list/cpu_count to the provided buffer.
2155 *
2156 * You may provide a buffer and size, or if you set the buffer to NULL, a
2157 * buffer of sufficient size will be allocated.
2158 *
2159 * If you provide a buffer and it is too small, sets cpumap_size to the number
2160 * of bytes required and returns EINVAL.
2161 *
2162 * On success, if you provided a buffer, cpumap_size is set to the number of
2163 * bytes written. If you did not provide a buffer, cpumap is set to the newly
2164 * allocated buffer and cpumap_size is set to the number of bytes allocated.
2165 *
2166 * NOTE: It may seem redundant to pass both iops and a cpu_count.
2167 *
2168 * We may be reporting data from "now", or from the "past".
2169 *
2170 * The "past" data would be for kdbg_readcpumap().
2171 *
2172 * If we do not pass both iops and cpu_count, and iops is NULL, this function
2173 * will need to read "now" state to get the number of cpus, which would be in
2174 * error if we were reporting "past" state.
2175 */
2176
2177 int
2178 kdbg_cpumap_init_internal(kd_iop_t* iops, uint32_t cpu_count, uint8_t** cpumap, uint32_t* cpumap_size)
2179 {
2180 assert(cpumap);
2181 assert(cpumap_size);
2182 assert(cpu_count);
2183 assert(!iops || iops->cpu_id + 1 == cpu_count);
2184
2185 uint32_t bytes_needed = sizeof(kd_cpumap_header) + cpu_count * sizeof(kd_cpumap);
2186 uint32_t bytes_available = *cpumap_size;
2187 *cpumap_size = bytes_needed;
2188
2189 if (*cpumap == NULL) {
2190 if (kmem_alloc(kernel_map, (vm_offset_t*)cpumap, (vm_size_t)*cpumap_size, VM_KERN_MEMORY_DIAG) != KERN_SUCCESS) {
2191 return ENOMEM;
2192 }
2193 bzero(*cpumap, *cpumap_size);
2194 } else if (bytes_available < bytes_needed) {
2195 return EINVAL;
2196 }
2197
2198 kd_cpumap_header* header = (kd_cpumap_header*)(uintptr_t)*cpumap;
2199
2200 header->version_no = RAW_VERSION1;
2201 header->cpu_count = cpu_count;
2202
2203 kd_cpumap* cpus = (kd_cpumap*)&header[1];
2204
2205 int32_t index = cpu_count - 1;
2206 while (iops) {
2207 cpus[index].cpu_id = iops->cpu_id;
2208 cpus[index].flags = KDBG_CPUMAP_IS_IOP;
2209 strlcpy(cpus[index].name, iops->callback.iop_name, sizeof(cpus->name));
2210
2211 iops = iops->next;
2212 index--;
2213 }
2214
2215 while (index >= 0) {
2216 cpus[index].cpu_id = index;
2217 cpus[index].flags = 0;
2218 strlcpy(cpus[index].name, "AP", sizeof(cpus->name));
2219
2220 index--;
2221 }
2222
2223 return KERN_SUCCESS;
2224 }
2225
2226 void
2227 kdbg_thrmap_init(void)
2228 {
2229 ktrace_assert_lock_held();
2230
2231 if (kd_ctrl_page.kdebug_flags & KDBG_MAPINIT) {
2232 return;
2233 }
2234
2235 kd_mapptr = kdbg_thrmap_init_internal(0, &kd_mapsize, &kd_mapcount);
2236
2237 if (kd_mapptr) {
2238 kd_ctrl_page.kdebug_flags |= KDBG_MAPINIT;
2239 }
2240 }
2241
2242 static void
2243 kd_resolve_map(thread_t thread, void *opaque)
2244 {
2245 struct kd_resolver *resolve = opaque;
2246
2247 if (resolve->krs_count < resolve->krs_maxcount) {
2248 kd_threadmap *map = &resolve->krs_map[resolve->krs_count];
2249 struct kd_task_name *task_name = resolve->krs_task;
2250 map->thread = (uintptr_t)thread_tid(thread);
2251
2252 (void)strlcpy(map->command, task_name->ktn_name, sizeof(map->command));
2253 /*
2254 * Kernel threads should still be marked with non-zero valid bit.
2255 */
2256 pid_t pid = resolve->krs_task->ktn_pid;
2257 map->valid = pid == 0 ? 1 : pid;
2258 resolve->krs_count++;
2259 }
2260 }
2261
2262 static vm_size_t
2263 kd_resolve_tasks(struct kd_task_name *task_names, vm_size_t ntasks)
2264 {
2265 vm_size_t i = 0;
2266 proc_t p = PROC_NULL;
2267
2268 proc_list_lock();
2269 ALLPROC_FOREACH(p) {
2270 if (i >= ntasks) {
2271 break;
2272 }
2273 /*
2274 * Only record processes that can be referenced and are not exiting.
2275 */
2276 if (p->task && (p->p_lflag & P_LEXIT) == 0) {
2277 task_reference(p->task);
2278 task_names[i].ktn_task = p->task;
2279 task_names[i].ktn_pid = p->p_pid;
2280 (void)strlcpy(task_names[i].ktn_name, proc_best_name(p),
2281 sizeof(task_names[i].ktn_name));
2282 i++;
2283 }
2284 }
2285 proc_list_unlock();
2286
2287 return i;
2288 }
2289
2290 static vm_size_t
2291 kd_resolve_threads(kd_threadmap *map, struct kd_task_name *task_names,
2292 vm_size_t ntasks, vm_size_t nthreads)
2293 {
2294 struct kd_resolver resolver = {
2295 .krs_map = map, .krs_count = 0, .krs_maxcount = nthreads,
2296 };
2297
2298 for (int i = 0; i < ntasks; i++) {
2299 struct kd_task_name *cur_task = &task_names[i];
2300 resolver.krs_task = cur_task;
2301 task_act_iterate_wth_args(cur_task->ktn_task, kd_resolve_map,
2302 &resolver);
2303 task_deallocate(cur_task->ktn_task);
2304 }
2305
2306 return resolver.krs_count;
2307 }
2308
2309 static kd_threadmap *
2310 kdbg_thrmap_init_internal(size_t maxthreads, vm_size_t *mapsize,
2311 vm_size_t *mapcount)
2312 {
2313 kd_threadmap *thread_map = NULL;
2314 struct kd_task_name *task_names;
2315 vm_size_t names_size = 0;
2316
2317 assert(mapsize != NULL);
2318 assert(mapcount != NULL);
2319
2320 vm_size_t nthreads = threads_count;
2321 vm_size_t ntasks = tasks_count;
2322
2323 /*
2324 * Allow 25% more threads and tasks to be created between now and taking the
2325 * proc_list_lock.
2326 */
2327 if (os_add_overflow(nthreads, nthreads / 4, &nthreads) ||
2328 os_add_overflow(ntasks, ntasks / 4, &ntasks)) {
2329 return NULL;
2330 }
2331
2332 *mapcount = nthreads;
2333 if (os_mul_overflow(nthreads, sizeof(kd_threadmap), mapsize)) {
2334 return NULL;
2335 }
2336 if (os_mul_overflow(ntasks, sizeof(task_names[0]), &names_size)) {
2337 return NULL;
2338 }
2339
2340 /*
2341 * Wait until the out-parameters have been filled with the needed size to
2342 * do the bounds checking on the provided maximum.
2343 */
2344 if (maxthreads != 0 && maxthreads < nthreads) {
2345 return NULL;
2346 }
2347
2348 thread_map = kalloc_tag(*mapsize, VM_KERN_MEMORY_DIAG);
2349 bzero(thread_map, *mapsize);
2350 task_names = kheap_alloc(KHEAP_TEMP, names_size, Z_WAITOK | Z_ZERO);
2351 ntasks = kd_resolve_tasks(task_names, ntasks);
2352 *mapcount = kd_resolve_threads(thread_map, task_names, ntasks, nthreads);
2353 kheap_free(KHEAP_TEMP, task_names, names_size);
2354 return thread_map;
2355 }
2356
2357 static void
2358 kdbg_clear(void)
2359 {
2360 /*
2361 * Clean up the trace buffer
2362 * First make sure we're not in
2363 * the middle of cutting a trace
2364 */
2365 kernel_debug_disable();
2366 kdbg_disable_typefilter();
2367
2368 /*
2369 * make sure the SLOW_NOLOG is seen
2370 * by everyone that might be trying
2371 * to cut a trace..
2372 */
2373 IOSleep(100);
2374
2375 /* reset kdebug state for each process */
2376 if (kd_ctrl_page.kdebug_flags & (KDBG_PIDCHECK | KDBG_PIDEXCLUDE)) {
2377 proc_list_lock();
2378 proc_t p;
2379 ALLPROC_FOREACH(p) {
2380 p->p_kdebug = 0;
2381 }
2382 proc_list_unlock();
2383 }
2384
2385 kd_ctrl_page.kdebug_flags &= (unsigned int)~KDBG_CKTYPES;
2386 kd_ctrl_page.kdebug_flags &= ~(KDBG_NOWRAP | KDBG_RANGECHECK | KDBG_VALCHECK);
2387 kd_ctrl_page.kdebug_flags &= ~(KDBG_PIDCHECK | KDBG_PIDEXCLUDE);
2388
2389 kd_ctrl_page.oldest_time = 0;
2390
2391 delete_buffers();
2392 nkdbufs = 0;
2393
2394 /* Clean up the thread map buffer */
2395 kdbg_clear_thread_map();
2396
2397 RAW_file_offset = 0;
2398 RAW_file_written = 0;
2399 }
2400
2401 void
2402 kdebug_reset(void)
2403 {
2404 ktrace_assert_lock_held();
2405
2406 kdbg_clear();
2407 if (kdbg_typefilter) {
2408 typefilter_reject_all(kdbg_typefilter);
2409 typefilter_allow_class(kdbg_typefilter, DBG_TRACE);
2410 }
2411 }
2412
2413 void
2414 kdebug_free_early_buf(void)
2415 {
2416 #if defined(__x86_64__)
2417 /*
2418 * Make Intel aware that the early buffer is no longer being used. ARM
2419 * handles this as part of the BOOTDATA segment.
2420 */
2421 ml_static_mfree((vm_offset_t)&kd_early_buffer, sizeof(kd_early_buffer));
2422 #endif /* defined(__x86_64__) */
2423 }
2424
2425 int
2426 kdbg_setpid(kd_regtype *kdr)
2427 {
2428 pid_t pid;
2429 int flag, ret = 0;
2430 struct proc *p;
2431
2432 pid = (pid_t)kdr->value1;
2433 flag = (int)kdr->value2;
2434
2435 if (pid >= 0) {
2436 if ((p = proc_find(pid)) == NULL) {
2437 ret = ESRCH;
2438 } else {
2439 if (flag == 1) {
2440 /*
2441 * turn on pid check for this and all pids
2442 */
2443 kd_ctrl_page.kdebug_flags |= KDBG_PIDCHECK;
2444 kd_ctrl_page.kdebug_flags &= ~KDBG_PIDEXCLUDE;
2445 kdbg_set_flags(SLOW_CHECKS, 0, true);
2446
2447 p->p_kdebug = 1;
2448 } else {
2449 /*
2450 * turn off pid check for this pid value
2451 * Don't turn off all pid checking though
2452 *
2453 * kd_ctrl_page.kdebug_flags &= ~KDBG_PIDCHECK;
2454 */
2455 p->p_kdebug = 0;
2456 }
2457 proc_rele(p);
2458 }
2459 } else {
2460 ret = EINVAL;
2461 }
2462
2463 return ret;
2464 }
2465
2466 /* This is for pid exclusion in the trace buffer */
2467 int
2468 kdbg_setpidex(kd_regtype *kdr)
2469 {
2470 pid_t pid;
2471 int flag, ret = 0;
2472 struct proc *p;
2473
2474 pid = (pid_t)kdr->value1;
2475 flag = (int)kdr->value2;
2476
2477 if (pid >= 0) {
2478 if ((p = proc_find(pid)) == NULL) {
2479 ret = ESRCH;
2480 } else {
2481 if (flag == 1) {
2482 /*
2483 * turn on pid exclusion
2484 */
2485 kd_ctrl_page.kdebug_flags |= KDBG_PIDEXCLUDE;
2486 kd_ctrl_page.kdebug_flags &= ~KDBG_PIDCHECK;
2487 kdbg_set_flags(SLOW_CHECKS, 0, true);
2488
2489 p->p_kdebug = 1;
2490 } else {
2491 /*
2492 * turn off pid exclusion for this pid value
2493 * Don't turn off all pid exclusion though
2494 *
2495 * kd_ctrl_page.kdebug_flags &= ~KDBG_PIDEXCLUDE;
2496 */
2497 p->p_kdebug = 0;
2498 }
2499 proc_rele(p);
2500 }
2501 } else {
2502 ret = EINVAL;
2503 }
2504
2505 return ret;
2506 }
2507
2508 /*
2509 * The following functions all operate on the "global" typefilter singleton.
2510 */
2511
2512 /*
2513 * The tf param is optional, you may pass either a valid typefilter or NULL.
2514 * If you pass a valid typefilter, you release ownership of that typefilter.
2515 */
2516 static int
2517 kdbg_initialize_typefilter(typefilter_t tf)
2518 {
2519 ktrace_assert_lock_held();
2520 assert(!kdbg_typefilter);
2521 assert(!kdbg_typefilter_memory_entry);
2522 typefilter_t deallocate_tf = NULL;
2523
2524 if (!tf && ((tf = deallocate_tf = typefilter_create()) == NULL)) {
2525 return ENOMEM;
2526 }
2527
2528 if ((kdbg_typefilter_memory_entry = typefilter_create_memory_entry(tf)) == MACH_PORT_NULL) {
2529 if (deallocate_tf) {
2530 typefilter_deallocate(deallocate_tf);
2531 }
2532 return ENOMEM;
2533 }
2534
2535 /*
2536 * The atomic store closes a race window with
2537 * the kdebug_typefilter syscall, which assumes
2538 * that any non-null kdbg_typefilter means a
2539 * valid memory_entry is available.
2540 */
2541 os_atomic_store(&kdbg_typefilter, tf, release);
2542
2543 return KERN_SUCCESS;
2544 }
2545
2546 static int
2547 kdbg_copyin_typefilter(user_addr_t addr, size_t size)
2548 {
2549 int ret = ENOMEM;
2550 typefilter_t tf;
2551
2552 ktrace_assert_lock_held();
2553
2554 if (size != KDBG_TYPEFILTER_BITMAP_SIZE) {
2555 return EINVAL;
2556 }
2557
2558 if ((tf = typefilter_create())) {
2559 if ((ret = copyin(addr, tf, KDBG_TYPEFILTER_BITMAP_SIZE)) == 0) {
2560 /* The kernel typefilter must always allow DBG_TRACE */
2561 typefilter_allow_class(tf, DBG_TRACE);
2562
2563 /*
2564 * If this is the first typefilter; claim it.
2565 * Otherwise copy and deallocate.
2566 *
2567 * Allocating a typefilter for the copyin allows
2568 * the kernel to hold the invariant that DBG_TRACE
2569 * must always be allowed.
2570 */
2571 if (!kdbg_typefilter) {
2572 if ((ret = kdbg_initialize_typefilter(tf))) {
2573 return ret;
2574 }
2575 tf = NULL;
2576 } else {
2577 typefilter_copy(kdbg_typefilter, tf);
2578 }
2579
2580 kdbg_enable_typefilter();
2581 kdbg_iop_list_callback(kd_ctrl_page.kdebug_iops, KD_CALLBACK_TYPEFILTER_CHANGED, kdbg_typefilter);
2582 }
2583
2584 if (tf) {
2585 typefilter_deallocate(tf);
2586 }
2587 }
2588
2589 return ret;
2590 }
2591
2592 /*
2593 * Enable the flags in the control page for the typefilter. Assumes that
2594 * kdbg_typefilter has already been allocated, so events being written
2595 * don't see a bad typefilter.
2596 */
2597 static void
2598 kdbg_enable_typefilter(void)
2599 {
2600 assert(kdbg_typefilter);
2601 kd_ctrl_page.kdebug_flags &= ~(KDBG_RANGECHECK | KDBG_VALCHECK);
2602 kd_ctrl_page.kdebug_flags |= KDBG_TYPEFILTER_CHECK;
2603 kdbg_set_flags(SLOW_CHECKS, 0, true);
2604 commpage_update_kdebug_state();
2605 }
2606
2607 /*
2608 * Disable the flags in the control page for the typefilter. The typefilter
2609 * may be safely deallocated shortly after this function returns.
2610 */
2611 static void
2612 kdbg_disable_typefilter(void)
2613 {
2614 bool notify_iops = kd_ctrl_page.kdebug_flags & KDBG_TYPEFILTER_CHECK;
2615 kd_ctrl_page.kdebug_flags &= ~KDBG_TYPEFILTER_CHECK;
2616
2617 if ((kd_ctrl_page.kdebug_flags & (KDBG_PIDCHECK | KDBG_PIDEXCLUDE))) {
2618 kdbg_set_flags(SLOW_CHECKS, 0, true);
2619 } else {
2620 kdbg_set_flags(SLOW_CHECKS, 0, false);
2621 }
2622 commpage_update_kdebug_state();
2623
2624 if (notify_iops) {
2625 /*
2626 * Notify IOPs that the typefilter will now allow everything.
2627 * Otherwise, they won't know a typefilter is no longer in
2628 * effect.
2629 */
2630 typefilter_allow_all(kdbg_typefilter);
2631 kdbg_iop_list_callback(kd_ctrl_page.kdebug_iops,
2632 KD_CALLBACK_TYPEFILTER_CHANGED, kdbg_typefilter);
2633 }
2634 }
2635
2636 uint32_t
2637 kdebug_commpage_state(void)
2638 {
2639 if (kdebug_enable) {
2640 if (kd_ctrl_page.kdebug_flags & KDBG_TYPEFILTER_CHECK) {
2641 return KDEBUG_COMMPAGE_ENABLE_TYPEFILTER | KDEBUG_COMMPAGE_ENABLE_TRACE;
2642 }
2643
2644 return KDEBUG_COMMPAGE_ENABLE_TRACE;
2645 }
2646
2647 return 0;
2648 }
2649
2650 int
2651 kdbg_setreg(kd_regtype * kdr)
2652 {
2653 int ret = 0;
2654 unsigned int val_1, val_2, val;
2655 switch (kdr->type) {
2656 case KDBG_CLASSTYPE:
2657 val_1 = (kdr->value1 & 0xff);
2658 val_2 = (kdr->value2 & 0xff);
2659 kdlog_beg = (val_1 << 24);
2660 kdlog_end = (val_2 << 24);
2661 kd_ctrl_page.kdebug_flags &= (unsigned int)~KDBG_CKTYPES;
2662 kd_ctrl_page.kdebug_flags &= ~KDBG_VALCHECK; /* Turn off specific value check */
2663 kd_ctrl_page.kdebug_flags |= (KDBG_RANGECHECK | KDBG_CLASSTYPE);
2664 kdbg_set_flags(SLOW_CHECKS, 0, true);
2665 break;
2666 case KDBG_SUBCLSTYPE:
2667 val_1 = (kdr->value1 & 0xff);
2668 val_2 = (kdr->value2 & 0xff);
2669 val = val_2 + 1;
2670 kdlog_beg = ((val_1 << 24) | (val_2 << 16));
2671 kdlog_end = ((val_1 << 24) | (val << 16));
2672 kd_ctrl_page.kdebug_flags &= (unsigned int)~KDBG_CKTYPES;
2673 kd_ctrl_page.kdebug_flags &= ~KDBG_VALCHECK; /* Turn off specific value check */
2674 kd_ctrl_page.kdebug_flags |= (KDBG_RANGECHECK | KDBG_SUBCLSTYPE);
2675 kdbg_set_flags(SLOW_CHECKS, 0, true);
2676 break;
2677 case KDBG_RANGETYPE:
2678 kdlog_beg = (kdr->value1);
2679 kdlog_end = (kdr->value2);
2680 kd_ctrl_page.kdebug_flags &= (unsigned int)~KDBG_CKTYPES;
2681 kd_ctrl_page.kdebug_flags &= ~KDBG_VALCHECK; /* Turn off specific value check */
2682 kd_ctrl_page.kdebug_flags |= (KDBG_RANGECHECK | KDBG_RANGETYPE);
2683 kdbg_set_flags(SLOW_CHECKS, 0, true);
2684 break;
2685 case KDBG_VALCHECK:
2686 kdlog_value1 = (kdr->value1);
2687 kdlog_value2 = (kdr->value2);
2688 kdlog_value3 = (kdr->value3);
2689 kdlog_value4 = (kdr->value4);
2690 kd_ctrl_page.kdebug_flags &= (unsigned int)~KDBG_CKTYPES;
2691 kd_ctrl_page.kdebug_flags &= ~KDBG_RANGECHECK; /* Turn off range check */
2692 kd_ctrl_page.kdebug_flags |= KDBG_VALCHECK; /* Turn on specific value check */
2693 kdbg_set_flags(SLOW_CHECKS, 0, true);
2694 break;
2695 case KDBG_TYPENONE:
2696 kd_ctrl_page.kdebug_flags &= (unsigned int)~KDBG_CKTYPES;
2697
2698 if ((kd_ctrl_page.kdebug_flags & (KDBG_RANGECHECK | KDBG_VALCHECK |
2699 KDBG_PIDCHECK | KDBG_PIDEXCLUDE |
2700 KDBG_TYPEFILTER_CHECK))) {
2701 kdbg_set_flags(SLOW_CHECKS, 0, true);
2702 } else {
2703 kdbg_set_flags(SLOW_CHECKS, 0, false);
2704 }
2705
2706 kdlog_beg = 0;
2707 kdlog_end = 0;
2708 break;
2709 default:
2710 ret = EINVAL;
2711 break;
2712 }
2713 return ret;
2714 }
2715
2716 static int
2717 kdbg_write_to_vnode(caddr_t buffer, size_t size, vnode_t vp, vfs_context_t ctx, off_t file_offset)
2718 {
2719 assert(size < INT_MAX);
2720 return vn_rdwr(UIO_WRITE, vp, buffer, (int)size, file_offset, UIO_SYSSPACE, IO_NODELOCKED | IO_UNIT,
2721 vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
2722 }
2723
2724 int
2725 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)
2726 {
2727 int ret = KERN_SUCCESS;
2728 kd_chunk_header_v3 header = {
2729 .tag = tag,
2730 .sub_tag = sub_tag,
2731 .length = length,
2732 };
2733
2734 // Check that only one of them is valid
2735 assert(!buffer ^ !vp);
2736 assert((vp == NULL) || (ctx != NULL));
2737
2738 // Write the 8-byte future_chunk_timestamp field in the payload
2739 if (buffer || vp) {
2740 if (vp) {
2741 ret = kdbg_write_to_vnode((caddr_t)&header, sizeof(kd_chunk_header_v3), vp, ctx, RAW_file_offset);
2742 if (ret) {
2743 goto write_error;
2744 }
2745 RAW_file_offset += (sizeof(kd_chunk_header_v3));
2746 } else {
2747 ret = copyout(&header, buffer, sizeof(kd_chunk_header_v3));
2748 if (ret) {
2749 goto write_error;
2750 }
2751 }
2752 }
2753 write_error:
2754 return ret;
2755 }
2756
2757 static int
2758 kdbg_write_v3_chunk_to_fd(uint32_t tag, uint32_t sub_tag, uint64_t length, void *payload, uint64_t payload_size, int fd)
2759 {
2760 proc_t p;
2761 struct vfs_context context;
2762 struct fileproc *fp;
2763 vnode_t vp;
2764 p = current_proc();
2765
2766 if (fp_get_ftype(p, fd, DTYPE_VNODE, EBADF, &fp)) {
2767 return EBADF;
2768 }
2769
2770 vp = fp->fp_glob->fg_data;
2771 context.vc_thread = current_thread();
2772 context.vc_ucred = fp->fp_glob->fg_cred;
2773
2774 if ((vnode_getwithref(vp)) == 0) {
2775 RAW_file_offset = fp->fp_glob->fg_offset;
2776
2777 kd_chunk_header_v3 chunk_header = {
2778 .tag = tag,
2779 .sub_tag = sub_tag,
2780 .length = length,
2781 };
2782
2783 int ret = kdbg_write_to_vnode((caddr_t) &chunk_header, sizeof(kd_chunk_header_v3), vp, &context, RAW_file_offset);
2784 if (!ret) {
2785 RAW_file_offset += sizeof(kd_chunk_header_v3);
2786 }
2787
2788 ret = kdbg_write_to_vnode((caddr_t) payload, (size_t) payload_size, vp, &context, RAW_file_offset);
2789 if (!ret) {
2790 RAW_file_offset += payload_size;
2791 }
2792
2793 fp->fp_glob->fg_offset = RAW_file_offset;
2794 vnode_put(vp);
2795 }
2796
2797 fp_drop(p, fd, fp, 0);
2798 return KERN_SUCCESS;
2799 }
2800
2801 user_addr_t
2802 kdbg_write_v3_event_chunk_header(user_addr_t buffer, uint32_t tag, uint64_t length, vnode_t vp, vfs_context_t ctx)
2803 {
2804 uint64_t future_chunk_timestamp = 0;
2805 length += sizeof(uint64_t);
2806
2807 if (kdbg_write_v3_chunk_header(buffer, tag, V3_EVENT_DATA_VERSION, length, vp, ctx)) {
2808 return 0;
2809 }
2810 if (buffer) {
2811 buffer += sizeof(kd_chunk_header_v3);
2812 }
2813
2814 // Check that only one of them is valid
2815 assert(!buffer ^ !vp);
2816 assert((vp == NULL) || (ctx != NULL));
2817
2818 // Write the 8-byte future_chunk_timestamp field in the payload
2819 if (buffer || vp) {
2820 if (vp) {
2821 int ret = kdbg_write_to_vnode((caddr_t)&future_chunk_timestamp, sizeof(uint64_t), vp, ctx, RAW_file_offset);
2822 if (!ret) {
2823 RAW_file_offset += (sizeof(uint64_t));
2824 }
2825 } else {
2826 if (copyout(&future_chunk_timestamp, buffer, sizeof(uint64_t))) {
2827 return 0;
2828 }
2829 }
2830 }
2831
2832 return buffer + sizeof(uint64_t);
2833 }
2834
2835 int
2836 kdbg_write_v3_header(user_addr_t user_header, size_t *user_header_size, int fd)
2837 {
2838 int ret = KERN_SUCCESS;
2839
2840 uint8_t* cpumap = 0;
2841 uint32_t cpumap_size = 0;
2842 uint32_t thrmap_size = 0;
2843
2844 size_t bytes_needed = 0;
2845
2846 // Check that only one of them is valid
2847 assert(!user_header ^ !fd);
2848 assert(user_header_size);
2849
2850 if (!(kd_ctrl_page.kdebug_flags & KDBG_BUFINIT)) {
2851 ret = EINVAL;
2852 goto bail;
2853 }
2854
2855 if (!(user_header || fd)) {
2856 ret = EINVAL;
2857 goto bail;
2858 }
2859
2860 // Initialize the cpu map
2861 ret = kdbg_cpumap_init_internal(kd_ctrl_page.kdebug_iops, kd_ctrl_page.kdebug_cpus, &cpumap, &cpumap_size);
2862 if (ret != KERN_SUCCESS) {
2863 goto bail;
2864 }
2865
2866 // Check if a thread map is initialized
2867 if (!kd_mapptr) {
2868 ret = EINVAL;
2869 goto bail;
2870 }
2871 if (os_mul_overflow(kd_mapcount, sizeof(kd_threadmap), &thrmap_size)) {
2872 ret = ERANGE;
2873 goto bail;
2874 }
2875
2876 mach_timebase_info_data_t timebase = {0, 0};
2877 clock_timebase_info(&timebase);
2878
2879 // Setup the header.
2880 // See v3 header description in sys/kdebug.h for more inforamtion.
2881 kd_header_v3 header = {
2882 .tag = RAW_VERSION3,
2883 .sub_tag = V3_HEADER_VERSION,
2884 .length = (sizeof(kd_header_v3) + cpumap_size - sizeof(kd_cpumap_header)),
2885 .timebase_numer = timebase.numer,
2886 .timebase_denom = timebase.denom,
2887 .timestamp = 0, /* FIXME rdar://problem/22053009 */
2888 .walltime_secs = 0,
2889 .walltime_usecs = 0,
2890 .timezone_minuteswest = 0,
2891 .timezone_dst = 0,
2892 #if defined(__LP64__)
2893 .flags = 1,
2894 #else
2895 .flags = 0,
2896 #endif
2897 };
2898
2899 // If its a buffer, check if we have enough space to copy the header and the maps.
2900 if (user_header) {
2901 bytes_needed = (size_t)header.length + thrmap_size + (2 * sizeof(kd_chunk_header_v3));
2902 if (*user_header_size < bytes_needed) {
2903 ret = EINVAL;
2904 goto bail;
2905 }
2906 }
2907
2908 // Start writing the header
2909 if (fd) {
2910 void *hdr_ptr = (void *)(((uintptr_t) &header) + sizeof(kd_chunk_header_v3));
2911 size_t payload_size = (sizeof(kd_header_v3) - sizeof(kd_chunk_header_v3));
2912
2913 ret = kdbg_write_v3_chunk_to_fd(RAW_VERSION3, V3_HEADER_VERSION, header.length, hdr_ptr, payload_size, fd);
2914 if (ret) {
2915 goto bail;
2916 }
2917 } else {
2918 if (copyout(&header, user_header, sizeof(kd_header_v3))) {
2919 ret = EFAULT;
2920 goto bail;
2921 }
2922 // Update the user pointer
2923 user_header += sizeof(kd_header_v3);
2924 }
2925
2926 // Write a cpu map. This is a sub chunk of the header
2927 cpumap = (uint8_t*)((uintptr_t) cpumap + sizeof(kd_cpumap_header));
2928 size_t payload_size = (size_t)(cpumap_size - sizeof(kd_cpumap_header));
2929 if (fd) {
2930 ret = kdbg_write_v3_chunk_to_fd(V3_CPU_MAP, V3_CPUMAP_VERSION, payload_size, (void *)cpumap, payload_size, fd);
2931 if (ret) {
2932 goto bail;
2933 }
2934 } else {
2935 ret = kdbg_write_v3_chunk_header(user_header, V3_CPU_MAP, V3_CPUMAP_VERSION, payload_size, NULL, NULL);
2936 if (ret) {
2937 goto bail;
2938 }
2939 user_header += sizeof(kd_chunk_header_v3);
2940 if (copyout(cpumap, user_header, payload_size)) {
2941 ret = EFAULT;
2942 goto bail;
2943 }
2944 // Update the user pointer
2945 user_header += payload_size;
2946 }
2947
2948 // Write a thread map
2949 if (fd) {
2950 ret = kdbg_write_v3_chunk_to_fd(V3_THREAD_MAP, V3_THRMAP_VERSION, thrmap_size, (void *)kd_mapptr, thrmap_size, fd);
2951 if (ret) {
2952 goto bail;
2953 }
2954 } else {
2955 ret = kdbg_write_v3_chunk_header(user_header, V3_THREAD_MAP, V3_THRMAP_VERSION, thrmap_size, NULL, NULL);
2956 if (ret) {
2957 goto bail;
2958 }
2959 user_header += sizeof(kd_chunk_header_v3);
2960 if (copyout(kd_mapptr, user_header, thrmap_size)) {
2961 ret = EFAULT;
2962 goto bail;
2963 }
2964 user_header += thrmap_size;
2965 }
2966
2967 if (fd) {
2968 RAW_file_written += bytes_needed;
2969 }
2970
2971 *user_header_size = bytes_needed;
2972 bail:
2973 if (cpumap) {
2974 kmem_free(kernel_map, (vm_offset_t)cpumap, cpumap_size);
2975 }
2976 return ret;
2977 }
2978
2979 int
2980 kdbg_readcpumap(user_addr_t user_cpumap, size_t *user_cpumap_size)
2981 {
2982 uint8_t* cpumap = NULL;
2983 uint32_t cpumap_size = 0;
2984 int ret = KERN_SUCCESS;
2985
2986 if (kd_ctrl_page.kdebug_flags & KDBG_BUFINIT) {
2987 if (kdbg_cpumap_init_internal(kd_ctrl_page.kdebug_iops, kd_ctrl_page.kdebug_cpus, &cpumap, &cpumap_size) == KERN_SUCCESS) {
2988 if (user_cpumap) {
2989 size_t bytes_to_copy = (*user_cpumap_size >= cpumap_size) ? cpumap_size : *user_cpumap_size;
2990 if (copyout(cpumap, user_cpumap, (size_t)bytes_to_copy)) {
2991 ret = EFAULT;
2992 }
2993 }
2994 *user_cpumap_size = cpumap_size;
2995 kmem_free(kernel_map, (vm_offset_t)cpumap, cpumap_size);
2996 } else {
2997 ret = EINVAL;
2998 }
2999 } else {
3000 ret = EINVAL;
3001 }
3002
3003 return ret;
3004 }
3005
3006 int
3007 kdbg_readcurthrmap(user_addr_t buffer, size_t *bufsize)
3008 {
3009 kd_threadmap *mapptr;
3010 vm_size_t mapsize;
3011 vm_size_t mapcount;
3012 int ret = 0;
3013 size_t count = *bufsize / sizeof(kd_threadmap);
3014
3015 *bufsize = 0;
3016
3017 if ((mapptr = kdbg_thrmap_init_internal(count, &mapsize, &mapcount))) {
3018 if (copyout(mapptr, buffer, mapcount * sizeof(kd_threadmap))) {
3019 ret = EFAULT;
3020 } else {
3021 *bufsize = (mapcount * sizeof(kd_threadmap));
3022 }
3023
3024 kfree(mapptr, mapsize);
3025 } else {
3026 ret = EINVAL;
3027 }
3028
3029 return ret;
3030 }
3031
3032 static int
3033 kdbg_write_v1_header(bool write_thread_map, vnode_t vp, vfs_context_t ctx)
3034 {
3035 int ret = 0;
3036 RAW_header header;
3037 clock_sec_t secs;
3038 clock_usec_t usecs;
3039 char *pad_buf;
3040 uint32_t pad_size;
3041 uint32_t extra_thread_count = 0;
3042 uint32_t cpumap_size;
3043 size_t map_size = 0;
3044 uint32_t map_count = 0;
3045
3046 if (write_thread_map) {
3047 assert(kd_ctrl_page.kdebug_flags & KDBG_MAPINIT);
3048 if (kd_mapcount > UINT32_MAX) {
3049 return ERANGE;
3050 }
3051 map_count = (uint32_t)kd_mapcount;
3052 if (os_mul_overflow(map_count, sizeof(kd_threadmap), &map_size)) {
3053 return ERANGE;
3054 }
3055 if (map_size >= INT_MAX) {
3056 return ERANGE;
3057 }
3058 }
3059
3060 /*
3061 * Without the buffers initialized, we cannot construct a CPU map or a
3062 * thread map, and cannot write a header.
3063 */
3064 if (!(kd_ctrl_page.kdebug_flags & KDBG_BUFINIT)) {
3065 return EINVAL;
3066 }
3067
3068 /*
3069 * To write a RAW_VERSION1+ file, we must embed a cpumap in the
3070 * "padding" used to page align the events following the threadmap. If
3071 * the threadmap happens to not require enough padding, we artificially
3072 * increase its footprint until it needs enough padding.
3073 */
3074
3075 assert(vp);
3076 assert(ctx);
3077
3078 pad_size = PAGE_16KB - ((sizeof(RAW_header) + map_size) & PAGE_MASK);
3079 cpumap_size = sizeof(kd_cpumap_header) + kd_ctrl_page.kdebug_cpus * sizeof(kd_cpumap);
3080
3081 if (cpumap_size > pad_size) {
3082 /* If the cpu map doesn't fit in the current available pad_size,
3083 * we increase the pad_size by 16K. We do this so that the event
3084 * data is always available on a page aligned boundary for both
3085 * 4k and 16k systems. We enforce this alignment for the event
3086 * data so that we can take advantage of optimized file/disk writes.
3087 */
3088 pad_size += PAGE_16KB;
3089 }
3090
3091 /* The way we are silently embedding a cpumap in the "padding" is by artificially
3092 * increasing the number of thread entries. However, we'll also need to ensure that
3093 * the cpumap is embedded in the last 4K page before when the event data is expected.
3094 * This way the tools can read the data starting the next page boundary on both
3095 * 4K and 16K systems preserving compatibility with older versions of the tools
3096 */
3097 if (pad_size > PAGE_4KB) {
3098 pad_size -= PAGE_4KB;
3099 extra_thread_count = (pad_size / sizeof(kd_threadmap)) + 1;
3100 }
3101
3102 memset(&header, 0, sizeof(header));
3103 header.version_no = RAW_VERSION1;
3104 header.thread_count = map_count + extra_thread_count;
3105
3106 clock_get_calendar_microtime(&secs, &usecs);
3107 header.TOD_secs = secs;
3108 header.TOD_usecs = usecs;
3109
3110 ret = vn_rdwr(UIO_WRITE, vp, (caddr_t)&header, (int)sizeof(RAW_header), RAW_file_offset,
3111 UIO_SYSSPACE, IO_NODELOCKED | IO_UNIT, vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
3112 if (ret) {
3113 goto write_error;
3114 }
3115 RAW_file_offset += sizeof(RAW_header);
3116 RAW_file_written += sizeof(RAW_header);
3117
3118 if (write_thread_map) {
3119 assert(map_size < INT_MAX);
3120 ret = vn_rdwr(UIO_WRITE, vp, (caddr_t)kd_mapptr, (int)map_size, RAW_file_offset,
3121 UIO_SYSSPACE, IO_NODELOCKED | IO_UNIT, vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
3122 if (ret) {
3123 goto write_error;
3124 }
3125
3126 RAW_file_offset += map_size;
3127 RAW_file_written += map_size;
3128 }
3129
3130 if (extra_thread_count) {
3131 pad_size = extra_thread_count * sizeof(kd_threadmap);
3132 pad_buf = kheap_alloc(KHEAP_TEMP, pad_size, Z_WAITOK | Z_ZERO);
3133 if (!pad_buf) {
3134 ret = ENOMEM;
3135 goto write_error;
3136 }
3137
3138 assert(pad_size < INT_MAX);
3139 ret = vn_rdwr(UIO_WRITE, vp, (caddr_t)pad_buf, (int)pad_size, RAW_file_offset,
3140 UIO_SYSSPACE, IO_NODELOCKED | IO_UNIT, vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
3141 kheap_free(KHEAP_TEMP, pad_buf, pad_size);
3142 if (ret) {
3143 goto write_error;
3144 }
3145
3146 RAW_file_offset += pad_size;
3147 RAW_file_written += pad_size;
3148 }
3149
3150 pad_size = PAGE_SIZE - (RAW_file_offset & PAGE_MASK);
3151 if (pad_size) {
3152 pad_buf = (char *)kheap_alloc(KHEAP_TEMP, pad_size, Z_WAITOK | Z_ZERO);
3153 if (!pad_buf) {
3154 ret = ENOMEM;
3155 goto write_error;
3156 }
3157
3158 /*
3159 * embed a cpumap in the padding bytes.
3160 * older code will skip this.
3161 * newer code will know how to read it.
3162 */
3163 uint32_t temp = pad_size;
3164 if (kdbg_cpumap_init_internal(kd_ctrl_page.kdebug_iops, kd_ctrl_page.kdebug_cpus, (uint8_t**)&pad_buf, &temp) != KERN_SUCCESS) {
3165 memset(pad_buf, 0, pad_size);
3166 }
3167
3168 assert(pad_size < INT_MAX);
3169 ret = vn_rdwr(UIO_WRITE, vp, (caddr_t)pad_buf, (int)pad_size, RAW_file_offset,
3170 UIO_SYSSPACE, IO_NODELOCKED | IO_UNIT, vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
3171 kheap_free(KHEAP_TEMP, pad_buf, pad_size);
3172 if (ret) {
3173 goto write_error;
3174 }
3175
3176 RAW_file_offset += pad_size;
3177 RAW_file_written += pad_size;
3178 }
3179
3180 write_error:
3181 return ret;
3182 }
3183
3184 static void
3185 kdbg_clear_thread_map(void)
3186 {
3187 ktrace_assert_lock_held();
3188
3189 if (kd_ctrl_page.kdebug_flags & KDBG_MAPINIT) {
3190 assert(kd_mapptr != NULL);
3191 kfree(kd_mapptr, kd_mapsize);
3192 kd_mapptr = NULL;
3193 kd_mapsize = 0;
3194 kd_mapcount = 0;
3195 kd_ctrl_page.kdebug_flags &= ~KDBG_MAPINIT;
3196 }
3197 }
3198
3199 /*
3200 * Write out a version 1 header and the thread map, if it is initialized, to a
3201 * vnode. Used by KDWRITEMAP and kdbg_dump_trace_to_file.
3202 *
3203 * Returns write errors from vn_rdwr if a write fails. Returns ENODATA if the
3204 * thread map has not been initialized, but the header will still be written.
3205 * Returns ENOMEM if padding could not be allocated. Returns 0 otherwise.
3206 */
3207 static int
3208 kdbg_write_thread_map(vnode_t vp, vfs_context_t ctx)
3209 {
3210 int ret = 0;
3211 bool map_initialized;
3212
3213 ktrace_assert_lock_held();
3214 assert(ctx != NULL);
3215
3216 map_initialized = (kd_ctrl_page.kdebug_flags & KDBG_MAPINIT);
3217
3218 ret = kdbg_write_v1_header(map_initialized, vp, ctx);
3219 if (ret == 0) {
3220 if (map_initialized) {
3221 kdbg_clear_thread_map();
3222 } else {
3223 ret = ENODATA;
3224 }
3225 }
3226
3227 return ret;
3228 }
3229
3230 /*
3231 * Copy out the thread map to a user space buffer. Used by KDTHRMAP.
3232 *
3233 * Returns copyout errors if the copyout fails. Returns ENODATA if the thread
3234 * map has not been initialized. Returns EINVAL if the buffer provided is not
3235 * large enough for the entire thread map. Returns 0 otherwise.
3236 */
3237 static int
3238 kdbg_copyout_thread_map(user_addr_t buffer, size_t *buffer_size)
3239 {
3240 bool map_initialized;
3241 size_t map_size;
3242 int ret = 0;
3243
3244 ktrace_assert_lock_held();
3245 assert(buffer_size != NULL);
3246
3247 map_initialized = (kd_ctrl_page.kdebug_flags & KDBG_MAPINIT);
3248 if (!map_initialized) {
3249 return ENODATA;
3250 }
3251
3252 map_size = kd_mapcount * sizeof(kd_threadmap);
3253 if (*buffer_size < map_size) {
3254 return EINVAL;
3255 }
3256
3257 ret = copyout(kd_mapptr, buffer, map_size);
3258 if (ret == 0) {
3259 kdbg_clear_thread_map();
3260 }
3261
3262 return ret;
3263 }
3264
3265 int
3266 kdbg_readthrmap_v3(user_addr_t buffer, size_t buffer_size, int fd)
3267 {
3268 int ret = 0;
3269 bool map_initialized;
3270 size_t map_size;
3271
3272 ktrace_assert_lock_held();
3273
3274 if ((!fd && !buffer) || (fd && buffer)) {
3275 return EINVAL;
3276 }
3277
3278 map_initialized = (kd_ctrl_page.kdebug_flags & KDBG_MAPINIT);
3279 map_size = kd_mapcount * sizeof(kd_threadmap);
3280
3281 if (map_initialized && (buffer_size >= map_size)) {
3282 ret = kdbg_write_v3_header(buffer, &buffer_size, fd);
3283
3284 if (ret == 0) {
3285 kdbg_clear_thread_map();
3286 }
3287 } else {
3288 ret = EINVAL;
3289 }
3290
3291 return ret;
3292 }
3293
3294 static void
3295 kdbg_set_nkdbufs(unsigned int req_nkdbufs)
3296 {
3297 /*
3298 * Only allow allocation up to half the available memory (sane_size).
3299 */
3300 uint64_t max_nkdbufs = (sane_size / 2) / sizeof(kd_buf);
3301 nkdbufs = (req_nkdbufs > max_nkdbufs) ? (unsigned int)max_nkdbufs :
3302 req_nkdbufs;
3303 }
3304
3305 /*
3306 * Block until there are `n_storage_threshold` storage units filled with
3307 * events or `timeout_ms` milliseconds have passed. If `locked_wait` is true,
3308 * `ktrace_lock` is held while waiting. This is necessary while waiting to
3309 * write events out of the buffers.
3310 *
3311 * Returns true if the threshold was reached and false otherwise.
3312 *
3313 * Called with `ktrace_lock` locked and interrupts enabled.
3314 */
3315 static bool
3316 kdbg_wait(uint64_t timeout_ms, bool locked_wait)
3317 {
3318 int wait_result = THREAD_AWAKENED;
3319 uint64_t abstime = 0;
3320
3321 ktrace_assert_lock_held();
3322
3323 if (timeout_ms != 0) {
3324 uint64_t ns = timeout_ms * NSEC_PER_MSEC;
3325 nanoseconds_to_absolutetime(ns, &abstime);
3326 clock_absolutetime_interval_to_deadline(abstime, &abstime);
3327 }
3328
3329 bool s = ml_set_interrupts_enabled(false);
3330 if (!s) {
3331 panic("kdbg_wait() called with interrupts disabled");
3332 }
3333 lck_spin_lock_grp(&kdw_spin_lock, &kdebug_lck_grp);
3334
3335 if (!locked_wait) {
3336 /* drop the mutex to allow others to access trace */
3337 ktrace_unlock();
3338 }
3339
3340 while (wait_result == THREAD_AWAKENED &&
3341 kd_ctrl_page.kds_inuse_count < n_storage_threshold) {
3342 kds_waiter = 1;
3343
3344 if (abstime) {
3345 wait_result = lck_spin_sleep_deadline(&kdw_spin_lock, 0, &kds_waiter, THREAD_ABORTSAFE, abstime);
3346 } else {
3347 wait_result = lck_spin_sleep(&kdw_spin_lock, 0, &kds_waiter, THREAD_ABORTSAFE);
3348 }
3349
3350 kds_waiter = 0;
3351 }
3352
3353 /* check the count under the spinlock */
3354 bool threshold_exceeded = (kd_ctrl_page.kds_inuse_count >= n_storage_threshold);
3355
3356 lck_spin_unlock(&kdw_spin_lock);
3357 ml_set_interrupts_enabled(s);
3358
3359 if (!locked_wait) {
3360 /* pick the mutex back up again */
3361 ktrace_lock();
3362 }
3363
3364 /* write out whether we've exceeded the threshold */
3365 return threshold_exceeded;
3366 }
3367
3368 /*
3369 * Wakeup a thread waiting using `kdbg_wait` if there are at least
3370 * `n_storage_threshold` storage units in use.
3371 */
3372 static void
3373 kdbg_wakeup(void)
3374 {
3375 bool need_kds_wakeup = false;
3376
3377 /*
3378 * Try to take the lock here to synchronize with the waiter entering
3379 * the blocked state. Use the try mode to prevent deadlocks caused by
3380 * re-entering this routine due to various trace points triggered in the
3381 * lck_spin_sleep_xxxx routines used to actually enter one of our 2 wait
3382 * conditions. No problem if we fail, there will be lots of additional
3383 * events coming in that will eventually succeed in grabbing this lock.
3384 */
3385 bool s = ml_set_interrupts_enabled(false);
3386
3387 if (lck_spin_try_lock(&kdw_spin_lock)) {
3388 if (kds_waiter &&
3389 (kd_ctrl_page.kds_inuse_count >= n_storage_threshold)) {
3390 kds_waiter = 0;
3391 need_kds_wakeup = true;
3392 }
3393 lck_spin_unlock(&kdw_spin_lock);
3394 }
3395
3396 ml_set_interrupts_enabled(s);
3397
3398 if (need_kds_wakeup == true) {
3399 wakeup(&kds_waiter);
3400 }
3401 }
3402
3403 int
3404 kdbg_control(int *name, u_int namelen, user_addr_t where, size_t *sizep)
3405 {
3406 int ret = 0;
3407 size_t size = *sizep;
3408 unsigned int value = 0;
3409 kd_regtype kd_Reg;
3410 kbufinfo_t kd_bufinfo;
3411 proc_t p;
3412
3413 if (name[0] == KERN_KDWRITETR ||
3414 name[0] == KERN_KDWRITETR_V3 ||
3415 name[0] == KERN_KDWRITEMAP ||
3416 name[0] == KERN_KDWRITEMAP_V3 ||
3417 name[0] == KERN_KDEFLAGS ||
3418 name[0] == KERN_KDDFLAGS ||
3419 name[0] == KERN_KDENABLE ||
3420 name[0] == KERN_KDSETBUF) {
3421 if (namelen < 2) {
3422 return EINVAL;
3423 }
3424 value = name[1];
3425 }
3426
3427 ktrace_lock();
3428
3429 /*
3430 * Some requests only require "read" access to kdebug trace. Regardless,
3431 * tell ktrace that a configuration or read is occurring (and see if it's
3432 * allowed).
3433 */
3434 if (name[0] != KERN_KDGETBUF &&
3435 name[0] != KERN_KDGETREG &&
3436 name[0] != KERN_KDREADCURTHRMAP) {
3437 if ((ret = ktrace_configure(KTRACE_KDEBUG))) {
3438 goto out;
3439 }
3440 } else {
3441 if ((ret = ktrace_read_check())) {
3442 goto out;
3443 }
3444 }
3445
3446 switch (name[0]) {
3447 case KERN_KDGETBUF:
3448 if (size < sizeof(kd_bufinfo.nkdbufs)) {
3449 /*
3450 * There is not enough room to return even
3451 * the first element of the info structure.
3452 */
3453 ret = EINVAL;
3454 break;
3455 }
3456
3457 memset(&kd_bufinfo, 0, sizeof(kd_bufinfo));
3458
3459 kd_bufinfo.nkdbufs = nkdbufs;
3460 kd_bufinfo.nkdthreads = kd_mapcount < INT_MAX ? (int)kd_mapcount :
3461 INT_MAX;
3462 if ((kd_ctrl_page.kdebug_slowcheck & SLOW_NOLOG)) {
3463 kd_bufinfo.nolog = 1;
3464 } else {
3465 kd_bufinfo.nolog = 0;
3466 }
3467
3468 kd_bufinfo.flags = kd_ctrl_page.kdebug_flags;
3469 #if defined(__LP64__)
3470 kd_bufinfo.flags |= KDBG_LP64;
3471 #endif
3472 {
3473 int pid = ktrace_get_owning_pid();
3474 kd_bufinfo.bufid = (pid == 0 ? -1 : pid);
3475 }
3476
3477 if (size >= sizeof(kd_bufinfo)) {
3478 /*
3479 * Provide all the info we have
3480 */
3481 if (copyout(&kd_bufinfo, where, sizeof(kd_bufinfo))) {
3482 ret = EINVAL;
3483 }
3484 } else {
3485 /*
3486 * For backwards compatibility, only provide
3487 * as much info as there is room for.
3488 */
3489 if (copyout(&kd_bufinfo, where, size)) {
3490 ret = EINVAL;
3491 }
3492 }
3493 break;
3494
3495 case KERN_KDREADCURTHRMAP:
3496 ret = kdbg_readcurthrmap(where, sizep);
3497 break;
3498
3499 case KERN_KDEFLAGS:
3500 value &= KDBG_USERFLAGS;
3501 kd_ctrl_page.kdebug_flags |= value;
3502 break;
3503
3504 case KERN_KDDFLAGS:
3505 value &= KDBG_USERFLAGS;
3506 kd_ctrl_page.kdebug_flags &= ~value;
3507 break;
3508
3509 case KERN_KDENABLE:
3510 /*
3511 * Enable tracing mechanism. Two types:
3512 * KDEBUG_TRACE is the standard one,
3513 * and KDEBUG_PPT which is a carefully
3514 * chosen subset to avoid performance impact.
3515 */
3516 if (value) {
3517 /*
3518 * enable only if buffer is initialized
3519 */
3520 if (!(kd_ctrl_page.kdebug_flags & KDBG_BUFINIT) ||
3521 !(value == KDEBUG_ENABLE_TRACE || value == KDEBUG_ENABLE_PPT)) {
3522 ret = EINVAL;
3523 break;
3524 }
3525 kdbg_thrmap_init();
3526
3527 kdbg_set_tracing_enabled(true, value);
3528 } else {
3529 if (!kdebug_enable) {
3530 break;
3531 }
3532
3533 kernel_debug_disable();
3534 }
3535 break;
3536
3537 case KERN_KDSETBUF:
3538 kdbg_set_nkdbufs(value);
3539 break;
3540
3541 case KERN_KDSETUP:
3542 ret = kdbg_reinit(false);
3543 break;
3544
3545 case KERN_KDREMOVE:
3546 ktrace_reset(KTRACE_KDEBUG);
3547 break;
3548
3549 case KERN_KDSETREG:
3550 if (size < sizeof(kd_regtype)) {
3551 ret = EINVAL;
3552 break;
3553 }
3554 if (copyin(where, &kd_Reg, sizeof(kd_regtype))) {
3555 ret = EINVAL;
3556 break;
3557 }
3558
3559 ret = kdbg_setreg(&kd_Reg);
3560 break;
3561
3562 case KERN_KDGETREG:
3563 ret = EINVAL;
3564 break;
3565
3566 case KERN_KDREADTR:
3567 ret = kdbg_read(where, sizep, NULL, NULL, RAW_VERSION1);
3568 break;
3569
3570 case KERN_KDWRITETR:
3571 case KERN_KDWRITETR_V3:
3572 case KERN_KDWRITEMAP:
3573 case KERN_KDWRITEMAP_V3:
3574 {
3575 struct vfs_context context;
3576 struct fileproc *fp;
3577 size_t number;
3578 vnode_t vp;
3579 int fd;
3580
3581 if (name[0] == KERN_KDWRITETR || name[0] == KERN_KDWRITETR_V3) {
3582 (void)kdbg_wait(size, true);
3583 }
3584 p = current_proc();
3585 fd = value;
3586
3587
3588 if (fp_get_ftype(p, fd, DTYPE_VNODE, EBADF, &fp)) {
3589 ret = EBADF;
3590 break;
3591 }
3592
3593 vp = fp->fp_glob->fg_data;
3594 context.vc_thread = current_thread();
3595 context.vc_ucred = fp->fp_glob->fg_cred;
3596
3597 if ((ret = vnode_getwithref(vp)) == 0) {
3598 RAW_file_offset = fp->fp_glob->fg_offset;
3599 if (name[0] == KERN_KDWRITETR || name[0] == KERN_KDWRITETR_V3) {
3600 number = nkdbufs * sizeof(kd_buf);
3601
3602 KDBG_RELEASE(TRACE_WRITING_EVENTS | DBG_FUNC_START);
3603 if (name[0] == KERN_KDWRITETR_V3) {
3604 ret = kdbg_read(0, &number, vp, &context, RAW_VERSION3);
3605 } else {
3606 ret = kdbg_read(0, &number, vp, &context, RAW_VERSION1);
3607 }
3608 KDBG_RELEASE(TRACE_WRITING_EVENTS | DBG_FUNC_END, number);
3609
3610 *sizep = number;
3611 } else {
3612 number = kd_mapcount * sizeof(kd_threadmap);
3613 if (name[0] == KERN_KDWRITEMAP_V3) {
3614 ret = kdbg_readthrmap_v3(0, number, fd);
3615 } else {
3616 ret = kdbg_write_thread_map(vp, &context);
3617 }
3618 }
3619 fp->fp_glob->fg_offset = RAW_file_offset;
3620 vnode_put(vp);
3621 }
3622 fp_drop(p, fd, fp, 0);
3623
3624 break;
3625 }
3626 case KERN_KDBUFWAIT:
3627 *sizep = kdbg_wait(size, false);
3628 break;
3629
3630 case KERN_KDPIDTR:
3631 if (size < sizeof(kd_regtype)) {
3632 ret = EINVAL;
3633 break;
3634 }
3635 if (copyin(where, &kd_Reg, sizeof(kd_regtype))) {
3636 ret = EINVAL;
3637 break;
3638 }
3639
3640 ret = kdbg_setpid(&kd_Reg);
3641 break;
3642
3643 case KERN_KDPIDEX:
3644 if (size < sizeof(kd_regtype)) {
3645 ret = EINVAL;
3646 break;
3647 }
3648 if (copyin(where, &kd_Reg, sizeof(kd_regtype))) {
3649 ret = EINVAL;
3650 break;
3651 }
3652
3653 ret = kdbg_setpidex(&kd_Reg);
3654 break;
3655
3656 case KERN_KDCPUMAP:
3657 ret = kdbg_readcpumap(where, sizep);
3658 break;
3659
3660 case KERN_KDTHRMAP:
3661 ret = kdbg_copyout_thread_map(where, sizep);
3662 break;
3663
3664 case KERN_KDSET_TYPEFILTER: {
3665 ret = kdbg_copyin_typefilter(where, size);
3666 break;
3667 }
3668
3669 case KERN_KDTEST:
3670 ret = kdbg_test(size);
3671 break;
3672
3673 default:
3674 ret = EINVAL;
3675 break;
3676 }
3677 out:
3678 ktrace_unlock();
3679
3680 return ret;
3681 }
3682
3683
3684 /*
3685 * This code can run for the most part concurrently with kernel_debug_internal()...
3686 * 'release_storage_unit' will take the kds_spin_lock which may cause us to briefly
3687 * synchronize with the recording side of this puzzle... otherwise, we are able to
3688 * move through the lists w/o use of any locks
3689 */
3690 int
3691 kdbg_read(user_addr_t buffer, size_t *number, vnode_t vp, vfs_context_t ctx, uint32_t file_version)
3692 {
3693 size_t count;
3694 unsigned int cpu, min_cpu;
3695 uint64_t barrier_min = 0, barrier_max = 0, t, earliest_time;
3696 int error = 0;
3697 kd_buf *tempbuf;
3698 uint32_t rcursor;
3699 kd_buf lostevent;
3700 union kds_ptr kdsp;
3701 bool traced_retrograde = false;
3702 struct kd_storage *kdsp_actual;
3703 struct kd_bufinfo *kdbp;
3704 struct kd_bufinfo *min_kdbp;
3705 size_t tempbuf_count;
3706 uint32_t tempbuf_number;
3707 uint32_t old_kdebug_flags;
3708 uint32_t old_kdebug_slowcheck;
3709 bool out_of_events = false;
3710 bool wrapped = false;
3711
3712 assert(number != NULL);
3713 count = *number / sizeof(kd_buf);
3714 *number = 0;
3715
3716 ktrace_assert_lock_held();
3717
3718 if (count == 0 || !(kd_ctrl_page.kdebug_flags & KDBG_BUFINIT) || kdcopybuf == 0) {
3719 return EINVAL;
3720 }
3721
3722 thread_set_eager_preempt(current_thread());
3723
3724 memset(&lostevent, 0, sizeof(lostevent));
3725 lostevent.debugid = TRACE_LOST_EVENTS;
3726
3727 /*
3728 * Request each IOP to provide us with up to date entries before merging
3729 * buffers together.
3730 */
3731 kdbg_iop_list_callback(kd_ctrl_page.kdebug_iops, KD_CALLBACK_SYNC_FLUSH, NULL);
3732
3733 /*
3734 * Capture the current time. Only sort events that have occured
3735 * before now. Since the IOPs are being flushed here, it is possible
3736 * that events occur on the AP while running live tracing.
3737 */
3738 barrier_max = kdbg_timestamp() & KDBG_TIMESTAMP_MASK;
3739
3740 /*
3741 * Disable wrap so storage units cannot be stolen out from underneath us
3742 * while merging events.
3743 *
3744 * Because we hold ktrace_lock, no other control threads can be playing
3745 * with kdebug_flags. The code that emits new events could be running,
3746 * but it grabs kds_spin_lock if it needs to acquire a new storage
3747 * chunk, which is where it examines kdebug_flags. If it is adding to
3748 * the same chunk we're reading from, check for that below.
3749 */
3750 wrapped = disable_wrap(&old_kdebug_slowcheck, &old_kdebug_flags);
3751
3752 if (count > nkdbufs) {
3753 count = nkdbufs;
3754 }
3755
3756 if ((tempbuf_count = count) > KDCOPYBUF_COUNT) {
3757 tempbuf_count = KDCOPYBUF_COUNT;
3758 }
3759
3760 /*
3761 * If the buffers have wrapped, do not emit additional lost events for the
3762 * oldest storage units.
3763 */
3764 if (wrapped) {
3765 kd_ctrl_page.kdebug_flags &= ~KDBG_WRAPPED;
3766
3767 for (cpu = 0, kdbp = &kdbip[0]; cpu < kd_ctrl_page.kdebug_cpus; cpu++, kdbp++) {
3768 if ((kdsp = kdbp->kd_list_head).raw == KDS_PTR_NULL) {
3769 continue;
3770 }
3771 kdsp_actual = POINTER_FROM_KDS_PTR(kdsp);
3772 kdsp_actual->kds_lostevents = false;
3773 }
3774 }
3775 /*
3776 * Capture the earliest time where there are events for all CPUs and don't
3777 * emit events with timestamps prior.
3778 */
3779 barrier_min = kd_ctrl_page.oldest_time;
3780
3781 while (count) {
3782 tempbuf = kdcopybuf;
3783 tempbuf_number = 0;
3784
3785 if (wrapped) {
3786 /*
3787 * Emit a lost events tracepoint to indicate that previous events
3788 * were lost -- the thread map cannot be trusted. A new one must
3789 * be taken so tools can analyze the trace in a backwards-facing
3790 * fashion.
3791 */
3792 kdbg_set_timestamp_and_cpu(&lostevent, barrier_min, 0);
3793 *tempbuf = lostevent;
3794 wrapped = false;
3795 goto nextevent;
3796 }
3797
3798 /* While space left in merged events scratch buffer. */
3799 while (tempbuf_count) {
3800 bool lostevents = false;
3801 int lostcpu = 0;
3802 earliest_time = UINT64_MAX;
3803 min_kdbp = NULL;
3804 min_cpu = 0;
3805
3806 /* Check each CPU's buffers for the earliest event. */
3807 for (cpu = 0, kdbp = &kdbip[0]; cpu < kd_ctrl_page.kdebug_cpus; cpu++, kdbp++) {
3808 /* Skip CPUs without data in their oldest storage unit. */
3809 if ((kdsp = kdbp->kd_list_head).raw == KDS_PTR_NULL) {
3810 next_cpu:
3811 continue;
3812 }
3813 /* From CPU data to buffer header to buffer. */
3814 kdsp_actual = POINTER_FROM_KDS_PTR(kdsp);
3815
3816 next_event:
3817 /* The next event to be read from this buffer. */
3818 rcursor = kdsp_actual->kds_readlast;
3819
3820 /* Skip this buffer if there are no events left. */
3821 if (rcursor == kdsp_actual->kds_bufindx) {
3822 continue;
3823 }
3824
3825 /*
3826 * Check that this storage unit wasn't stolen and events were
3827 * lost. This must have happened while wrapping was disabled
3828 * in this function.
3829 */
3830 if (kdsp_actual->kds_lostevents) {
3831 lostevents = true;
3832 kdsp_actual->kds_lostevents = false;
3833
3834 /*
3835 * The earliest event we can trust is the first one in this
3836 * stolen storage unit.
3837 */
3838 uint64_t lost_time =
3839 kdbg_get_timestamp(&kdsp_actual->kds_records[0]);
3840 if (kd_ctrl_page.oldest_time < lost_time) {
3841 /*
3842 * If this is the first time we've seen lost events for
3843 * this gap, record its timestamp as the oldest
3844 * timestamp we're willing to merge for the lost events
3845 * tracepoint.
3846 */
3847 kd_ctrl_page.oldest_time = barrier_min = lost_time;
3848 lostcpu = cpu;
3849 }
3850 }
3851
3852 t = kdbg_get_timestamp(&kdsp_actual->kds_records[rcursor]);
3853
3854 if (t > barrier_max) {
3855 if (kdbg_debug) {
3856 printf("kdebug: FUTURE EVENT: debugid %#8x: "
3857 "time %lld from CPU %u "
3858 "(barrier at time %lld, read %lu events)\n",
3859 kdsp_actual->kds_records[rcursor].debugid,
3860 t, cpu, barrier_max, *number + tempbuf_number);
3861 }
3862 goto next_cpu;
3863 }
3864 if (t < kdsp_actual->kds_timestamp) {
3865 /*
3866 * This indicates the event emitter hasn't completed
3867 * filling in the event (becuase we're looking at the
3868 * buffer that the record head is using). The max barrier
3869 * timestamp should have saved us from seeing these kinds
3870 * of things, but other CPUs might be slow on the up-take.
3871 *
3872 * Bail out so we don't get out-of-order events by
3873 * continuing to read events from other CPUs' events.
3874 */
3875 out_of_events = true;
3876 break;
3877 }
3878
3879 /*
3880 * Ignore events that have aged out due to wrapping or storage
3881 * unit exhaustion while merging events.
3882 */
3883 if (t < barrier_min) {
3884 kdsp_actual->kds_readlast++;
3885 if (kdbg_debug) {
3886 printf("kdebug: PAST EVENT: debugid %#8x: "
3887 "time %lld from CPU %u "
3888 "(barrier at time %lld)\n",
3889 kdsp_actual->kds_records[rcursor].debugid,
3890 t, cpu, barrier_min);
3891 }
3892
3893 if (kdsp_actual->kds_readlast >= EVENTS_PER_STORAGE_UNIT) {
3894 release_storage_unit(cpu, kdsp.raw);
3895
3896 if ((kdsp = kdbp->kd_list_head).raw == KDS_PTR_NULL) {
3897 goto next_cpu;
3898 }
3899 kdsp_actual = POINTER_FROM_KDS_PTR(kdsp);
3900 }
3901
3902 goto next_event;
3903 }
3904
3905 /*
3906 * Don't worry about merging any events -- just walk through
3907 * the CPUs and find the latest timestamp of lost events.
3908 */
3909 if (lostevents) {
3910 continue;
3911 }
3912
3913 if (t < earliest_time) {
3914 earliest_time = t;
3915 min_kdbp = kdbp;
3916 min_cpu = cpu;
3917 }
3918 }
3919 if (lostevents) {
3920 /*
3921 * If any lost events were hit in the buffers, emit an event
3922 * with the latest timestamp.
3923 */
3924 kdbg_set_timestamp_and_cpu(&lostevent, barrier_min, lostcpu);
3925 *tempbuf = lostevent;
3926 tempbuf->arg1 = 1;
3927 goto nextevent;
3928 }
3929 if (min_kdbp == NULL) {
3930 /* All buffers ran empty. */
3931 out_of_events = true;
3932 }
3933 if (out_of_events) {
3934 break;
3935 }
3936
3937 kdsp = min_kdbp->kd_list_head;
3938 kdsp_actual = POINTER_FROM_KDS_PTR(kdsp);
3939
3940 /* Copy earliest event into merged events scratch buffer. */
3941 *tempbuf = kdsp_actual->kds_records[kdsp_actual->kds_readlast++];
3942
3943 if (kdsp_actual->kds_readlast == EVENTS_PER_STORAGE_UNIT) {
3944 release_storage_unit(min_cpu, kdsp.raw);
3945 }
3946
3947 /*
3948 * Watch for out of order timestamps (from IOPs).
3949 */
3950 if (earliest_time < min_kdbp->kd_prev_timebase) {
3951 /*
3952 * If we haven't already, emit a retrograde events event.
3953 * Otherwise, ignore this event.
3954 */
3955 if (traced_retrograde) {
3956 continue;
3957 }
3958 if (kdbg_debug) {
3959 printf("kdebug: RETRO EVENT: debugid %#8x: "
3960 "time %lld from CPU %u "
3961 "(barrier at time %lld)\n",
3962 kdsp_actual->kds_records[rcursor].debugid,
3963 t, cpu, barrier_min);
3964 }
3965
3966 kdbg_set_timestamp_and_cpu(tempbuf, min_kdbp->kd_prev_timebase, kdbg_get_cpu(tempbuf));
3967 tempbuf->arg1 = tempbuf->debugid;
3968 tempbuf->arg2 = (kd_buf_argtype)earliest_time;
3969 tempbuf->arg3 = 0;
3970 tempbuf->arg4 = 0;
3971 tempbuf->debugid = TRACE_RETROGRADE_EVENTS;
3972 traced_retrograde = true;
3973 } else {
3974 min_kdbp->kd_prev_timebase = earliest_time;
3975 }
3976 nextevent:
3977 tempbuf_count--;
3978 tempbuf_number++;
3979 tempbuf++;
3980
3981 if ((RAW_file_written += sizeof(kd_buf)) >= RAW_FLUSH_SIZE) {
3982 break;
3983 }
3984 }
3985 if (tempbuf_number) {
3986 /*
3987 * Remember the latest timestamp of events that we've merged so we
3988 * don't think we've lost events later.
3989 */
3990 uint64_t latest_time = kdbg_get_timestamp(tempbuf - 1);
3991 if (kd_ctrl_page.oldest_time < latest_time) {
3992 kd_ctrl_page.oldest_time = latest_time;
3993 }
3994 if (file_version == RAW_VERSION3) {
3995 if (!(kdbg_write_v3_event_chunk_header(buffer, V3_RAW_EVENTS, (tempbuf_number * sizeof(kd_buf)), vp, ctx))) {
3996 error = EFAULT;
3997 goto check_error;
3998 }
3999 if (buffer) {
4000 buffer += (sizeof(kd_chunk_header_v3) + sizeof(uint64_t));
4001 }
4002
4003 assert(count >= (sizeof(kd_chunk_header_v3) + sizeof(uint64_t)));
4004 count -= (sizeof(kd_chunk_header_v3) + sizeof(uint64_t));
4005 *number += (sizeof(kd_chunk_header_v3) + sizeof(uint64_t));
4006 }
4007 if (vp) {
4008 size_t write_size = tempbuf_number * sizeof(kd_buf);
4009 error = kdbg_write_to_vnode((caddr_t)kdcopybuf, write_size, vp, ctx, RAW_file_offset);
4010 if (!error) {
4011 RAW_file_offset += write_size;
4012 }
4013
4014 if (RAW_file_written >= RAW_FLUSH_SIZE) {
4015 error = VNOP_FSYNC(vp, MNT_NOWAIT, ctx);
4016
4017 RAW_file_written = 0;
4018 }
4019 } else {
4020 error = copyout(kdcopybuf, buffer, tempbuf_number * sizeof(kd_buf));
4021 buffer += (tempbuf_number * sizeof(kd_buf));
4022 }
4023 check_error:
4024 if (error) {
4025 *number = 0;
4026 error = EINVAL;
4027 break;
4028 }
4029 count -= tempbuf_number;
4030 *number += tempbuf_number;
4031 }
4032 if (out_of_events == true) {
4033 /*
4034 * all trace buffers are empty
4035 */
4036 break;
4037 }
4038
4039 if ((tempbuf_count = count) > KDCOPYBUF_COUNT) {
4040 tempbuf_count = KDCOPYBUF_COUNT;
4041 }
4042 }
4043 if (!(old_kdebug_flags & KDBG_NOWRAP)) {
4044 enable_wrap(old_kdebug_slowcheck);
4045 }
4046 thread_clear_eager_preempt(current_thread());
4047 return error;
4048 }
4049
4050 #define KDEBUG_TEST_CODE(code) BSDDBG_CODE(DBG_BSD_KDEBUG_TEST, (code))
4051
4052 /*
4053 * A test IOP for the SYNC_FLUSH callback.
4054 */
4055
4056 static int sync_flush_iop = 0;
4057
4058 static void
4059 sync_flush_callback(void * __unused context, kd_callback_type reason,
4060 void * __unused arg)
4061 {
4062 assert(sync_flush_iop > 0);
4063
4064 if (reason == KD_CALLBACK_SYNC_FLUSH) {
4065 kernel_debug_enter(sync_flush_iop, KDEBUG_TEST_CODE(0xff),
4066 kdbg_timestamp(), 0, 0, 0, 0, 0);
4067 }
4068 }
4069
4070 static struct kd_callback sync_flush_kdcb = {
4071 .func = sync_flush_callback,
4072 .iop_name = "test_sf",
4073 };
4074
4075 static int
4076 kdbg_test(size_t flavor)
4077 {
4078 int code = 0;
4079 int dummy_iop = 0;
4080
4081 switch (flavor) {
4082 case 1:
4083 /* try each macro */
4084 KDBG(KDEBUG_TEST_CODE(code)); code++;
4085 KDBG(KDEBUG_TEST_CODE(code), 1); code++;
4086 KDBG(KDEBUG_TEST_CODE(code), 1, 2); code++;
4087 KDBG(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
4088 KDBG(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
4089
4090 KDBG_RELEASE(KDEBUG_TEST_CODE(code)); code++;
4091 KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1); code++;
4092 KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1, 2); code++;
4093 KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
4094 KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
4095
4096 KDBG_FILTERED(KDEBUG_TEST_CODE(code)); code++;
4097 KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1); code++;
4098 KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1, 2); code++;
4099 KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
4100 KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
4101
4102 KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code)); code++;
4103 KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code), 1); code++;
4104 KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code), 1, 2); code++;
4105 KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
4106 KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
4107
4108 KDBG_DEBUG(KDEBUG_TEST_CODE(code)); code++;
4109 KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1); code++;
4110 KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1, 2); code++;
4111 KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
4112 KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
4113 break;
4114
4115 case 2:
4116 if (kd_ctrl_page.kdebug_iops) {
4117 /* avoid the assertion in kernel_debug_enter for a valid IOP */
4118 dummy_iop = kd_ctrl_page.kdebug_iops[0].cpu_id;
4119 }
4120
4121 /* ensure old timestamps are not emitted from kernel_debug_enter */
4122 kernel_debug_enter(dummy_iop, KDEBUG_TEST_CODE(code),
4123 100 /* very old timestamp */, 0, 0, 0, 0, 0);
4124 code++;
4125 kernel_debug_enter(dummy_iop, KDEBUG_TEST_CODE(code),
4126 kdbg_timestamp(), 0, 0, 0, 0, 0);
4127 code++;
4128 break;
4129
4130 case 3:
4131 if (kd_ctrl_page.kdebug_iops) {
4132 dummy_iop = kd_ctrl_page.kdebug_iops[0].cpu_id;
4133 }
4134 kernel_debug_enter(dummy_iop, KDEBUG_TEST_CODE(code),
4135 kdbg_timestamp() * 2 /* !!! */, 0, 0, 0, 0, 0);
4136 break;
4137
4138 case 4:
4139 if (!sync_flush_iop) {
4140 sync_flush_iop = kernel_debug_register_callback(
4141 sync_flush_kdcb);
4142 assert(sync_flush_iop > 0);
4143 }
4144 break;
4145
4146 default:
4147 return ENOTSUP;
4148 }
4149
4150 return 0;
4151 }
4152
4153 #undef KDEBUG_TEST_CODE
4154
4155 void
4156 kdebug_init(unsigned int n_events, char *filter_desc, enum kdebug_opts opts)
4157 {
4158 assert(filter_desc != NULL);
4159
4160 if (log_leaks && n_events == 0) {
4161 n_events = 200000;
4162 }
4163
4164 kdebug_trace_start(n_events, filter_desc, opts);
4165 }
4166
4167 static void
4168 kdbg_set_typefilter_string(const char *filter_desc)
4169 {
4170 char *end = NULL;
4171
4172 ktrace_assert_lock_held();
4173
4174 assert(filter_desc != NULL);
4175
4176 typefilter_reject_all(kdbg_typefilter);
4177 typefilter_allow_class(kdbg_typefilter, DBG_TRACE);
4178
4179 /* if the filter description starts with a number, assume it's a csc */
4180 if (filter_desc[0] >= '0' && filter_desc[0] <= '9') {
4181 unsigned long csc = strtoul(filter_desc, NULL, 0);
4182 if (filter_desc != end && csc <= KDBG_CSC_MAX) {
4183 typefilter_allow_csc(kdbg_typefilter, (uint16_t)csc);
4184 }
4185 return;
4186 }
4187
4188 while (filter_desc[0] != '\0') {
4189 unsigned long allow_value;
4190
4191 char filter_type = filter_desc[0];
4192 if (filter_type != 'C' && filter_type != 'S') {
4193 printf("kdebug: unexpected filter type `%c'\n", filter_type);
4194 return;
4195 }
4196 filter_desc++;
4197
4198 allow_value = strtoul(filter_desc, &end, 0);
4199 if (filter_desc == end) {
4200 printf("kdebug: cannot parse `%s' as integer\n", filter_desc);
4201 return;
4202 }
4203
4204 switch (filter_type) {
4205 case 'C':
4206 if (allow_value > KDBG_CLASS_MAX) {
4207 printf("kdebug: class 0x%lx is invalid\n", allow_value);
4208 return;
4209 }
4210 printf("kdebug: C 0x%lx\n", allow_value);
4211 typefilter_allow_class(kdbg_typefilter, (uint8_t)allow_value);
4212 break;
4213 case 'S':
4214 if (allow_value > KDBG_CSC_MAX) {
4215 printf("kdebug: class-subclass 0x%lx is invalid\n", allow_value);
4216 return;
4217 }
4218 printf("kdebug: S 0x%lx\n", allow_value);
4219 typefilter_allow_csc(kdbg_typefilter, (uint16_t)allow_value);
4220 break;
4221 default:
4222 __builtin_unreachable();
4223 }
4224
4225 /* advance to next filter entry */
4226 filter_desc = end;
4227 if (filter_desc[0] == ',') {
4228 filter_desc++;
4229 }
4230 }
4231 }
4232
4233 uint64_t
4234 kdebug_wake(void)
4235 {
4236 if (!wake_nkdbufs) {
4237 return 0;
4238 }
4239 uint64_t start = mach_absolute_time();
4240 kdebug_trace_start(wake_nkdbufs, NULL, trace_wrap ? KDOPT_WRAPPING : 0);
4241 return mach_absolute_time() - start;
4242 }
4243
4244 /*
4245 * This function is meant to be called from the bootstrap thread or kdebug_wake.
4246 */
4247 void
4248 kdebug_trace_start(unsigned int n_events, const char *filter_desc,
4249 enum kdebug_opts opts)
4250 {
4251 if (!n_events) {
4252 kd_early_done = true;
4253 return;
4254 }
4255
4256 ktrace_start_single_threaded();
4257
4258 ktrace_kernel_configure(KTRACE_KDEBUG);
4259
4260 kdbg_set_nkdbufs(n_events);
4261
4262 kernel_debug_string_early("start_kern_tracing");
4263
4264 if (kdbg_reinit((opts & KDOPT_ATBOOT))) {
4265 printf("error from kdbg_reinit, kernel tracing not started\n");
4266 goto out;
4267 }
4268
4269 /*
4270 * Wrapping is disabled because boot and wake tracing is interested in
4271 * the earliest events, at the expense of later ones.
4272 */
4273 if (!(opts & KDOPT_WRAPPING)) {
4274 uint32_t old1, old2;
4275 (void)disable_wrap(&old1, &old2);
4276 }
4277
4278 if (filter_desc && filter_desc[0] != '\0') {
4279 if (kdbg_initialize_typefilter(NULL) == KERN_SUCCESS) {
4280 kdbg_set_typefilter_string(filter_desc);
4281 kdbg_enable_typefilter();
4282 }
4283 }
4284
4285 /*
4286 * Hold off interrupts between getting a thread map and enabling trace
4287 * and until the early traces are recorded.
4288 */
4289 bool s = ml_set_interrupts_enabled(false);
4290
4291 if (!(opts & KDOPT_ATBOOT)) {
4292 kdbg_thrmap_init();
4293 }
4294
4295 kdbg_set_tracing_enabled(true, KDEBUG_ENABLE_TRACE);
4296
4297 if ((opts & KDOPT_ATBOOT)) {
4298 /*
4299 * Transfer all very early events from the static buffer into the real
4300 * buffers.
4301 */
4302 kernel_debug_early_end();
4303 }
4304
4305 ml_set_interrupts_enabled(s);
4306
4307 printf("kernel tracing started with %u events, filter = %s\n", n_events,
4308 filter_desc ?: "none");
4309
4310 out:
4311 ktrace_end_single_threaded();
4312 }
4313
4314 void
4315 kdbg_dump_trace_to_file(const char *filename)
4316 {
4317 vfs_context_t ctx;
4318 vnode_t vp;
4319 size_t write_size;
4320 int ret;
4321
4322 ktrace_lock();
4323
4324 if (!(kdebug_enable & KDEBUG_ENABLE_TRACE)) {
4325 goto out;
4326 }
4327
4328 if (ktrace_get_owning_pid() != 0) {
4329 /*
4330 * Another process owns ktrace and is still active, disable tracing to
4331 * prevent wrapping.
4332 */
4333 kdebug_enable = 0;
4334 kd_ctrl_page.enabled = 0;
4335 commpage_update_kdebug_state();
4336 goto out;
4337 }
4338
4339 KDBG_RELEASE(TRACE_WRITING_EVENTS | DBG_FUNC_START);
4340
4341 kdebug_enable = 0;
4342 kd_ctrl_page.enabled = 0;
4343 commpage_update_kdebug_state();
4344
4345 ctx = vfs_context_kernel();
4346
4347 if (vnode_open(filename, (O_CREAT | FWRITE | O_NOFOLLOW), 0600, 0, &vp, ctx)) {
4348 goto out;
4349 }
4350
4351 kdbg_write_thread_map(vp, ctx);
4352
4353 write_size = nkdbufs * sizeof(kd_buf);
4354 ret = kdbg_read(0, &write_size, vp, ctx, RAW_VERSION1);
4355 if (ret) {
4356 goto out_close;
4357 }
4358
4359 /*
4360 * Wait to synchronize the file to capture the I/O in the
4361 * TRACE_WRITING_EVENTS interval.
4362 */
4363 ret = VNOP_FSYNC(vp, MNT_WAIT, ctx);
4364
4365 /*
4366 * Balance the starting TRACE_WRITING_EVENTS tracepoint manually.
4367 */
4368 kd_buf end_event = {
4369 .debugid = TRACE_WRITING_EVENTS | DBG_FUNC_END,
4370 .arg1 = write_size,
4371 .arg2 = ret,
4372 .arg5 = (kd_buf_argtype)thread_tid(current_thread()),
4373 };
4374 kdbg_set_timestamp_and_cpu(&end_event, kdbg_timestamp(),
4375 cpu_number());
4376
4377 /* this is best effort -- ignore any errors */
4378 (void)kdbg_write_to_vnode((caddr_t)&end_event, sizeof(kd_buf), vp, ctx,
4379 RAW_file_offset);
4380
4381 out_close:
4382 vnode_close(vp, FWRITE, ctx);
4383 sync(current_proc(), (void *)NULL, (int *)NULL);
4384
4385 out:
4386 ktrace_unlock();
4387 }
4388
4389 static int
4390 kdbg_sysctl_continuous SYSCTL_HANDLER_ARGS
4391 {
4392 #pragma unused(oidp, arg1, arg2)
4393 int value = kdbg_continuous_time;
4394 int ret = sysctl_io_number(req, value, sizeof(value), &value, NULL);
4395
4396 if (ret || !req->newptr) {
4397 return ret;
4398 }
4399
4400 kdbg_continuous_time = value;
4401 return 0;
4402 }
4403
4404 SYSCTL_NODE(_kern, OID_AUTO, kdbg, CTLFLAG_RD | CTLFLAG_LOCKED, 0,
4405 "kdbg");
4406
4407 SYSCTL_PROC(_kern_kdbg, OID_AUTO, experimental_continuous,
4408 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, 0,
4409 sizeof(int), kdbg_sysctl_continuous, "I",
4410 "Set kdebug to use mach_continuous_time");
4411
4412 SYSCTL_INT(_kern_kdbg, OID_AUTO, debug,
4413 CTLFLAG_RW | CTLFLAG_LOCKED,
4414 &kdbg_debug, 0, "Set kdebug debug mode");
4415
4416 SYSCTL_QUAD(_kern_kdbg, OID_AUTO, oldest_time,
4417 CTLTYPE_QUAD | CTLFLAG_RD | CTLFLAG_LOCKED,
4418 &kd_ctrl_page.oldest_time,
4419 "Find the oldest timestamp still in trace");