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