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