2 * Copyright (c) 2000-2019 Apple Inc. All rights reserved.
4 * @Apple_LICENSE_HEADER_START@
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.
12 * This Original Code and all software distributed under the License are
13 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
17 * License for the specific language governing rights and limitations
20 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
23 #include <sys/errno.h>
24 #include <sys/param.h>
25 #include <sys/systm.h>
26 #include <sys/proc_internal.h>
28 #include <sys/sysctl.h>
29 #include <sys/kdebug.h>
30 #include <sys/kauth.h>
31 #include <sys/ktrace.h>
32 #include <sys/sysproto.h>
33 #include <sys/bsdtask_info.h>
34 #include <sys/random.h>
36 #include <mach/clock_types.h>
37 #include <mach/mach_types.h>
38 #include <mach/mach_time.h>
39 #include <mach/mach_vm.h>
40 #include <machine/atomic.h>
41 #include <machine/machine_routines.h>
43 #include <mach/machine.h>
44 #include <mach/vm_map.h>
46 #if defined(__i386__) || defined(__x86_64__)
47 #include <i386/rtclock_protos.h>
49 #include <i386/machine_routines.h>
53 #include <kern/clock.h>
55 #include <kern/thread.h>
56 #include <kern/task.h>
57 #include <kern/debug.h>
58 #include <kern/kalloc.h>
59 #include <kern/cpu_number.h>
60 #include <kern/cpu_data.h>
61 #include <kern/assert.h>
62 #include <kern/telemetry.h>
63 #include <kern/sched_prim.h>
64 #include <vm/vm_kern.h>
66 #include <kperf/kperf.h>
67 #include <pexpert/device_tree.h>
69 #include <sys/malloc.h>
70 #include <sys/mcache.h>
72 #include <sys/vnode.h>
73 #include <sys/vnode_internal.h>
74 #include <sys/fcntl.h>
75 #include <sys/file_internal.h>
77 #include <sys/param.h> /* for isset() */
79 #include <mach/mach_host.h> /* for host_info() */
80 #include <libkern/OSAtomic.h>
82 #include <machine/pal_routines.h>
83 #include <machine/atomic.h>
85 extern unsigned int wake_nkdbufs
;
86 extern unsigned int trace_wrap
;
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.
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.
98 * Once registered, an IOP is permanent, it cannot be unloaded/unregistered.
99 * The current implementation depends on this for thread safety.
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.
105 * You may safely walk the kd_iops list at any time, without holding locks.
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.
113 typedef struct kd_iop
{
114 kd_callback_t callback
;
116 uint64_t last_timestamp
; /* Prevent timer rollback */
120 static kd_iop_t
* kd_iops
= NULL
;
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.
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.
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.
139 typedef uint8_t* typefilter_t
;
141 static typefilter_t kdbg_typefilter
;
142 static mach_port_t kdbg_typefilter_memory_entry
;
145 * There are 3 combinations of page sizes:
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.
156 #define TYPEFILTER_ALLOC_SIZE MAX(round_page_32(KDBG_TYPEFILTER_BITMAP_SIZE), KDBG_TYPEFILTER_BITMAP_SIZE)
159 typefilter_create(void)
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
);
170 typefilter_deallocate(typefilter_t tf
)
173 assert(tf
!= kdbg_typefilter
);
174 kmem_free(kernel_map
, (vm_offset_t
)tf
, TYPEFILTER_ALLOC_SIZE
);
178 typefilter_copy(typefilter_t dst
, typefilter_t src
)
182 memcpy(dst
, src
, KDBG_TYPEFILTER_BITMAP_SIZE
);
186 typefilter_reject_all(typefilter_t tf
)
189 memset(tf
, 0, KDBG_TYPEFILTER_BITMAP_SIZE
);
193 typefilter_allow_all(typefilter_t tf
)
196 memset(tf
, ~0, KDBG_TYPEFILTER_BITMAP_SIZE
);
200 typefilter_allow_class(typefilter_t tf
, uint8_t class)
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
);
208 typefilter_allow_csc(typefilter_t tf
, uint16_t csc
)
215 typefilter_is_debugid_allowed(typefilter_t tf
, uint32_t id
)
218 return isset(tf
, KDBG_EXTRACT_CSC(id
));
222 typefilter_create_memory_entry(typefilter_t tf
)
226 mach_port_t memory_entry
= MACH_PORT_NULL
;
227 memory_object_size_t size
= TYPEFILTER_ALLOC_SIZE
;
229 mach_make_memory_entry_64(kernel_map
,
231 (memory_object_offset_t
)tf
,
239 static int kdbg_copyin_typefilter(user_addr_t addr
, size_t size
);
240 static void kdbg_enable_typefilter(void);
241 static void kdbg_disable_typefilter(void);
244 * External prototypes
247 void task_act_iterate_wth_args(task_t
, void (*)(thread_t
, void *), void *);
248 void commpage_update_kdebug_state(void); /* XXX sign */
250 extern int log_leaks
;
253 * This flag is for testing purposes only -- it's highly experimental and tools
254 * have not been updated to support it.
256 static bool kdbg_continuous_time
= false;
258 static inline uint64_t
261 if (kdbg_continuous_time
) {
262 return mach_continuous_time();
264 return mach_absolute_time();
268 static int kdbg_debug
= 0;
270 int kdbg_control(int *, u_int
, user_addr_t
, size_t *);
272 static int kdbg_read(user_addr_t
, size_t *, vnode_t
, vfs_context_t
, uint32_t);
273 static int kdbg_readcpumap(user_addr_t
, size_t *);
274 static int kdbg_readthrmap_v3(user_addr_t
, size_t, int);
275 static int kdbg_readcurthrmap(user_addr_t
, size_t *);
276 static int kdbg_setreg(kd_regtype
*);
277 static int kdbg_setpidex(kd_regtype
*);
278 static int kdbg_setpid(kd_regtype
*);
279 static void kdbg_thrmap_init(void);
280 static int kdbg_reinit(bool);
281 static int kdbg_bootstrap(bool);
282 static int kdbg_test(size_t flavor
);
284 static int kdbg_write_v1_header(bool write_thread_map
, vnode_t vp
, vfs_context_t ctx
);
285 static int kdbg_write_thread_map(vnode_t vp
, vfs_context_t ctx
);
286 static int kdbg_copyout_thread_map(user_addr_t buffer
, size_t *buffer_size
);
287 static void kdbg_clear_thread_map(void);
289 static bool kdbg_wait(uint64_t timeout_ms
, bool locked_wait
);
290 static void kdbg_wakeup(void);
292 int kdbg_cpumap_init_internal(kd_iop_t
* iops
, uint32_t cpu_count
,
293 uint8_t** cpumap
, uint32_t* cpumap_size
);
295 static kd_threadmap
*kdbg_thrmap_init_internal(size_t max_count
,
296 vm_size_t
*map_size
, vm_size_t
*map_count
);
298 static bool kdebug_current_proc_enabled(uint32_t debugid
);
299 static errno_t
kdebug_check_trace_string(uint32_t debugid
, uint64_t str_id
);
301 int kdbg_write_v3_header(user_addr_t
, size_t *, int);
302 int kdbg_write_v3_chunk_header(user_addr_t buffer
, uint32_t tag
,
303 uint32_t sub_tag
, uint64_t length
,
304 vnode_t vp
, vfs_context_t ctx
);
306 user_addr_t
kdbg_write_v3_event_chunk_header(user_addr_t buffer
, uint32_t tag
,
307 uint64_t length
, vnode_t vp
,
312 static int create_buffers(bool);
313 static void delete_buffers(void);
315 extern int tasks_count
;
316 extern int threads_count
;
317 extern void IOSleep(int);
319 /* trace enable status */
320 unsigned int kdebug_enable
= 0;
322 /* A static buffer to record events prior to the start of regular logging */
324 #define KD_EARLY_BUFFER_SIZE (16 * 1024)
325 #define KD_EARLY_BUFFER_NBUFS (KD_EARLY_BUFFER_SIZE / sizeof(kd_buf))
326 #if defined(__x86_64__)
327 __attribute__((aligned(KD_EARLY_BUFFER_SIZE
)))
328 static kd_buf kd_early_buffer
[KD_EARLY_BUFFER_NBUFS
];
329 #else /* defined(__x86_64__) */
331 * On ARM, the space for this is carved out by osfmk/arm/data.s -- clang
332 * has problems aligning to greater than 4K.
334 extern kd_buf kd_early_buffer
[KD_EARLY_BUFFER_NBUFS
];
335 #endif /* !defined(__x86_64__) */
337 static unsigned int kd_early_index
= 0;
338 static bool kd_early_overflow
= false;
339 static bool kd_early_done
= false;
341 #define SLOW_NOLOG 0x01
342 #define SLOW_CHECKS 0x02
344 #define EVENTS_PER_STORAGE_UNIT 2048
345 #define MIN_STORAGE_UNITS_PER_CPU 4
347 #define POINTER_FROM_KDS_PTR(x) (&kd_bufs[x.buffer_index].kdsb_addr[x.offset])
351 uint32_t buffer_index
:21;
358 union kds_ptr kds_next
;
359 uint32_t kds_bufindx
;
361 uint32_t kds_readlast
;
363 uint64_t kds_timestamp
;
365 kd_buf kds_records
[EVENTS_PER_STORAGE_UNIT
];
368 #define MAX_BUFFER_SIZE (1024 * 1024 * 128)
369 #define N_STORAGE_UNITS_PER_BUFFER (MAX_BUFFER_SIZE / sizeof(struct kd_storage))
370 static_assert(N_STORAGE_UNITS_PER_BUFFER
<= 0x7ff,
371 "shoudn't overflow kds_ptr.offset");
373 struct kd_storage_buffers
{
374 struct kd_storage
*kdsb_addr
;
378 #define KDS_PTR_NULL 0xffffffff
379 struct kd_storage_buffers
*kd_bufs
= NULL
;
380 int n_storage_units
= 0;
381 unsigned int n_storage_buffers
= 0;
382 int n_storage_threshold
= 0;
387 union kds_ptr kd_list_head
;
388 union kds_ptr kd_list_tail
;
391 uint64_t kd_prev_timebase
;
393 } __attribute__((aligned(MAX_CPU_CACHE_LINE_SIZE
)));
397 * In principle, this control block can be shared in DRAM with other
398 * coprocessors and runtimes, for configuring what tracing is enabled.
400 struct kd_ctrl_page_t
{
401 union kds_ptr kds_free_list
;
405 uint32_t kdebug_flags
;
406 uint32_t kdebug_slowcheck
;
407 uint64_t oldest_time
;
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.
415 kd_iop_t
* kdebug_iops
;
416 uint32_t kdebug_cpus
;
418 .kds_free_list
= {.raw
= KDS_PTR_NULL
},
419 .kdebug_slowcheck
= SLOW_NOLOG
,
425 struct kd_bufinfo
*kdbip
= NULL
;
427 #define KDCOPYBUF_COUNT 8192
428 #define KDCOPYBUF_SIZE (KDCOPYBUF_COUNT * sizeof(kd_buf))
430 #define PAGE_4KB 4096
431 #define PAGE_16KB 16384
433 kd_buf
*kdcopybuf
= NULL
;
435 unsigned int nkdbufs
= 0;
436 unsigned int kdlog_beg
= 0;
437 unsigned int kdlog_end
= 0;
438 unsigned int kdlog_value1
= 0;
439 unsigned int kdlog_value2
= 0;
440 unsigned int kdlog_value3
= 0;
441 unsigned int kdlog_value4
= 0;
443 static LCK_GRP_DECLARE(kdebug_lck_grp
, "kdebug");
444 static LCK_SPIN_DECLARE(kdw_spin_lock
, &kdebug_lck_grp
);
445 static LCK_SPIN_DECLARE(kds_spin_lock
, &kdebug_lck_grp
);
447 kd_threadmap
*kd_mapptr
= 0;
448 vm_size_t kd_mapsize
= 0;
449 vm_size_t kd_mapcount
= 0;
451 off_t RAW_file_offset
= 0;
452 int RAW_file_written
= 0;
454 #define RAW_FLUSH_SIZE (2 * 1024 * 1024)
457 * A globally increasing counter for identifying strings in trace. Starts at
458 * 1 because 0 is a reserved return value.
460 __attribute__((aligned(MAX_CPU_CACHE_LINE_SIZE
)))
461 static uint64_t g_curr_str_id
= 1;
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)
468 * A bit pattern for identifying string IDs generated by
469 * kdebug_trace_string(2).
471 static uint64_t g_str_id_signature
= (0x70acULL
<< STR_ID_SIG_OFFSET
);
473 #define INTERRUPT 0x01050000
474 #define MACH_vmfault 0x01300008
475 #define BSC_SysCall 0x040c0000
476 #define MACH_SysCall 0x010c0000
478 struct kd_task_name
{
485 kd_threadmap
*krs_map
;
487 vm_size_t krs_maxcount
;
488 struct kd_task_name
*krs_task
;
492 * TRACE file formats...
496 * uint32_t #threadmaps
502 * RAW_header, with version_no set to RAW_VERSION1
504 * Empty space to pad alignment to the nearest page boundary.
509 * RAW_header, with version_no set to RAW_VERSION1
511 * kd_cpumap_header, with version_no set to RAW_VERSION1
513 * Empty space to pad alignment to the nearest page boundary.
516 * V1+ implementation details...
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
524 * if (header.version_no != RAW_VERSION1) { // Assume V0 }
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.
530 * To differentiate between a V1 and V1+ file, read as V1 until you reach
531 * the padding bytes. Then:
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) {
543 #define RAW_VERSION3 0x00001000
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:
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 | ----------------------------------------------------------------------------
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.
578 uint32_t timebase_numer
;
579 uint32_t timebase_denom
;
581 uint64_t walltime_secs
;
582 uint32_t walltime_usecs
;
583 uint32_t timezone_minuteswest
;
584 uint32_t timezone_dst
;
586 } __attribute__((packed
)) kd_header_v3
;
592 } __attribute__((packed
)) kd_chunk_header_v3
;
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
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.
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
610 typedef struct krt krt_t
;
613 kdbg_cpu_count(bool early_trace
)
616 #if defined(__x86_64__)
618 #else /* defined(__x86_64__) */
619 return ml_get_cpu_count();
620 #endif /* !defined(__x86_64__) */
623 #if defined(__x86_64__)
624 host_basic_info_data_t hinfo
;
625 mach_msg_type_number_t count
= HOST_BASIC_INFO_COUNT
;
626 host_info((host_t
)1 /* BSD_HOST */, HOST_BASIC_INFO
, (host_info_t
)&hinfo
, &count
);
627 assert(hinfo
.logical_cpu_max
> 0);
628 return hinfo
.logical_cpu_max
;
629 #else /* defined(__x86_64__) */
630 return ml_get_topology_info()->max_cpu_id
+ 1;
631 #endif /* !defined(__x86_64__) */
637 kdbg_iop_list_is_valid(kd_iop_t
* iop
)
640 /* Is list sorted by cpu_id? */
641 kd_iop_t
* temp
= iop
;
643 assert(!temp
->next
|| temp
->next
->cpu_id
== temp
->cpu_id
- 1);
644 assert(temp
->next
|| (temp
->cpu_id
== kdbg_cpu_count(false) || temp
->cpu_id
== kdbg_cpu_count(true)));
645 } while ((temp
= temp
->next
));
647 /* Does each entry have a function and a name? */
650 assert(temp
->callback
.func
);
651 assert(strlen(temp
->callback
.iop_name
) < sizeof(temp
->callback
.iop_name
));
652 } while ((temp
= temp
->next
));
658 #endif /* MACH_ASSERT */
661 kdbg_iop_list_callback(kd_iop_t
* iop
, kd_callback_type type
, void* arg
)
664 iop
->callback
.func(iop
->callback
.context
, type
, arg
);
670 kdbg_set_tracing_enabled(bool enabled
, uint32_t trace_type
)
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.
677 kdbg_iop_list_callback(kd_ctrl_page
.kdebug_iops
, KD_CALLBACK_SYNC_FLUSH
,
680 int s
= ml_set_interrupts_enabled(false);
681 lck_spin_lock_grp(&kds_spin_lock
, &kdebug_lck_grp
);
685 * The oldest valid time is now; reject past events from IOPs.
687 kd_ctrl_page
.oldest_time
= kdbg_timestamp();
688 kdebug_enable
|= trace_type
;
689 kd_ctrl_page
.kdebug_slowcheck
&= ~SLOW_NOLOG
;
690 kd_ctrl_page
.enabled
= 1;
691 commpage_update_kdebug_state();
693 kdebug_enable
&= ~(KDEBUG_ENABLE_TRACE
| KDEBUG_ENABLE_PPT
);
694 kd_ctrl_page
.kdebug_slowcheck
|= SLOW_NOLOG
;
695 kd_ctrl_page
.enabled
= 0;
696 commpage_update_kdebug_state();
698 lck_spin_unlock(&kds_spin_lock
);
699 ml_set_interrupts_enabled(s
);
702 kdbg_iop_list_callback(kd_ctrl_page
.kdebug_iops
,
703 KD_CALLBACK_KDEBUG_ENABLED
, NULL
);
705 kdbg_iop_list_callback(kd_ctrl_page
.kdebug_iops
,
706 KD_CALLBACK_KDEBUG_DISABLED
, NULL
);
711 kdbg_set_flags(int slowflag
, int enableflag
, bool enabled
)
713 int s
= ml_set_interrupts_enabled(false);
714 lck_spin_lock_grp(&kds_spin_lock
, &kdebug_lck_grp
);
717 kd_ctrl_page
.kdebug_slowcheck
|= slowflag
;
718 kdebug_enable
|= enableflag
;
720 kd_ctrl_page
.kdebug_slowcheck
&= ~slowflag
;
721 kdebug_enable
&= ~enableflag
;
724 lck_spin_unlock(&kds_spin_lock
);
725 ml_set_interrupts_enabled(s
);
729 * Disable wrapping and return true if trace wrapped, false otherwise.
732 disable_wrap(uint32_t *old_slowcheck
, uint32_t *old_flags
)
735 int s
= ml_set_interrupts_enabled(false);
736 lck_spin_lock_grp(&kds_spin_lock
, &kdebug_lck_grp
);
738 *old_slowcheck
= kd_ctrl_page
.kdebug_slowcheck
;
739 *old_flags
= kd_ctrl_page
.kdebug_flags
;
741 wrapped
= kd_ctrl_page
.kdebug_flags
& KDBG_WRAPPED
;
742 kd_ctrl_page
.kdebug_flags
&= ~KDBG_WRAPPED
;
743 kd_ctrl_page
.kdebug_flags
|= KDBG_NOWRAP
;
745 lck_spin_unlock(&kds_spin_lock
);
746 ml_set_interrupts_enabled(s
);
752 enable_wrap(uint32_t old_slowcheck
)
754 int s
= ml_set_interrupts_enabled(false);
755 lck_spin_lock_grp(&kds_spin_lock
, &kdebug_lck_grp
);
757 kd_ctrl_page
.kdebug_flags
&= ~KDBG_NOWRAP
;
759 if (!(old_slowcheck
& SLOW_NOLOG
)) {
760 kd_ctrl_page
.kdebug_slowcheck
&= ~SLOW_NOLOG
;
763 lck_spin_unlock(&kds_spin_lock
);
764 ml_set_interrupts_enabled(s
);
768 create_buffers(bool early_trace
)
771 unsigned int p_buffer_size
;
772 unsigned int f_buffer_size
;
773 unsigned int f_buffers
;
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.
781 * TLDR; Must read kd_iops once and only once!
783 kd_ctrl_page
.kdebug_iops
= kd_iops
;
785 assert(kdbg_iop_list_is_valid(kd_ctrl_page
.kdebug_iops
));
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.
793 kd_ctrl_page
.kdebug_cpus
= kd_ctrl_page
.kdebug_iops
? kd_ctrl_page
.kdebug_iops
->cpu_id
+ 1 : kdbg_cpu_count(early_trace
);
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
) {
800 if (nkdbufs
< (kd_ctrl_page
.kdebug_cpus
* EVENTS_PER_STORAGE_UNIT
* MIN_STORAGE_UNITS_PER_CPU
)) {
801 n_storage_units
= kd_ctrl_page
.kdebug_cpus
* MIN_STORAGE_UNITS_PER_CPU
;
803 n_storage_units
= nkdbufs
/ EVENTS_PER_STORAGE_UNIT
;
806 nkdbufs
= n_storage_units
* EVENTS_PER_STORAGE_UNIT
;
808 f_buffers
= n_storage_units
/ N_STORAGE_UNITS_PER_BUFFER
;
809 n_storage_buffers
= f_buffers
;
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
);
820 if (kdcopybuf
== 0) {
821 if (kmem_alloc(kernel_map
, (vm_offset_t
*)&kdcopybuf
, (vm_size_t
)KDCOPYBUF_SIZE
, VM_KERN_MEMORY_DIAG
) != KERN_SUCCESS
) {
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
) {
830 bzero(kd_bufs
, n_storage_buffers
* sizeof(struct kd_storage_buffers
));
832 for (i
= 0; i
< f_buffers
; i
++) {
833 if (kmem_alloc(kernel_map
, (vm_offset_t
*)&kd_bufs
[i
].kdsb_addr
, (vm_size_t
)f_buffer_size
, VM_KERN_MEMORY_DIAG
) != KERN_SUCCESS
) {
837 bzero(kd_bufs
[i
].kdsb_addr
, f_buffer_size
);
839 kd_bufs
[i
].kdsb_size
= f_buffer_size
;
842 if (kmem_alloc(kernel_map
, (vm_offset_t
*)&kd_bufs
[i
].kdsb_addr
, (vm_size_t
)p_buffer_size
, VM_KERN_MEMORY_DIAG
) != KERN_SUCCESS
) {
846 bzero(kd_bufs
[i
].kdsb_addr
, p_buffer_size
);
848 kd_bufs
[i
].kdsb_size
= p_buffer_size
;
852 for (i
= 0; i
< n_storage_buffers
; i
++) {
853 struct kd_storage
*kds
;
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
));
859 n_elements
= kd_bufs
[i
].kdsb_size
/ sizeof(struct kd_storage
);
860 kds
= kd_bufs
[i
].kdsb_addr
;
862 for (uint16_t n
= 0; n
< n_elements
; n
++) {
863 kds
[n
].kds_next
.buffer_index
= kd_ctrl_page
.kds_free_list
.buffer_index
;
864 kds
[n
].kds_next
.offset
= kd_ctrl_page
.kds_free_list
.offset
;
866 kd_ctrl_page
.kds_free_list
.buffer_index
= i
;
867 kd_ctrl_page
.kds_free_list
.offset
= n
;
869 n_storage_units
+= n_elements
;
872 bzero((char *)kdbip
, sizeof(struct kd_bufinfo
) * kd_ctrl_page
.kdebug_cpus
);
874 for (i
= 0; i
< kd_ctrl_page
.kdebug_cpus
; i
++) {
875 kdbip
[i
].kd_list_head
.raw
= KDS_PTR_NULL
;
876 kdbip
[i
].kd_list_tail
.raw
= KDS_PTR_NULL
;
877 kdbip
[i
].kd_lostevents
= false;
878 kdbip
[i
].num_bufs
= 0;
881 kd_ctrl_page
.kdebug_flags
|= KDBG_BUFINIT
;
883 kd_ctrl_page
.kds_inuse_count
= 0;
884 n_storage_threshold
= n_storage_units
/ 2;
899 for (i
= 0; i
< n_storage_buffers
; i
++) {
900 if (kd_bufs
[i
].kdsb_addr
) {
901 kmem_free(kernel_map
, (vm_offset_t
)kd_bufs
[i
].kdsb_addr
, (vm_size_t
)kd_bufs
[i
].kdsb_size
);
904 kmem_free(kernel_map
, (vm_offset_t
)kd_bufs
, (vm_size_t
)(n_storage_buffers
* sizeof(struct kd_storage_buffers
)));
907 n_storage_buffers
= 0;
910 kmem_free(kernel_map
, (vm_offset_t
)kdcopybuf
, KDCOPYBUF_SIZE
);
914 kd_ctrl_page
.kds_free_list
.raw
= KDS_PTR_NULL
;
917 kmem_free(kernel_map
, (vm_offset_t
)kdbip
, sizeof(struct kd_bufinfo
) * kd_ctrl_page
.kdebug_cpus
);
921 kd_ctrl_page
.kdebug_iops
= NULL
;
922 kd_ctrl_page
.kdebug_cpus
= 0;
923 kd_ctrl_page
.kdebug_flags
&= ~KDBG_BUFINIT
;
927 release_storage_unit(int cpu
, uint32_t kdsp_raw
)
930 struct kd_storage
*kdsp_actual
;
931 struct kd_bufinfo
*kdbp
;
936 s
= ml_set_interrupts_enabled(false);
937 lck_spin_lock_grp(&kds_spin_lock
, &kdebug_lck_grp
);
941 if (kdsp
.raw
== kdbp
->kd_list_head
.raw
) {
943 * it's possible for the storage unit pointed to
944 * by kdsp to have already been stolen... so
945 * check to see if it's still the head of the list
946 * now that we're behind the lock that protects
947 * adding and removing from the queue...
948 * since we only ever release and steal units from
949 * that position, if it's no longer the head
950 * we having nothing to do in this context
952 kdsp_actual
= POINTER_FROM_KDS_PTR(kdsp
);
953 kdbp
->kd_list_head
= kdsp_actual
->kds_next
;
955 kdsp_actual
->kds_next
= kd_ctrl_page
.kds_free_list
;
956 kd_ctrl_page
.kds_free_list
= kdsp
;
958 kd_ctrl_page
.kds_inuse_count
--;
960 lck_spin_unlock(&kds_spin_lock
);
961 ml_set_interrupts_enabled(s
);
965 allocate_storage_unit(int cpu
)
968 struct kd_storage
*kdsp_actual
, *kdsp_next_actual
;
969 struct kd_bufinfo
*kdbp
, *kdbp_vict
, *kdbp_try
;
970 uint64_t oldest_ts
, ts
;
974 s
= ml_set_interrupts_enabled(false);
975 lck_spin_lock_grp(&kds_spin_lock
, &kdebug_lck_grp
);
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
);
983 if (kdsp_actual
->kds_bufindx
< EVENTS_PER_STORAGE_UNIT
) {
988 if ((kdsp
= kd_ctrl_page
.kds_free_list
).raw
!= KDS_PTR_NULL
) {
990 * If there's a free page, grab it from the free list.
992 kdsp_actual
= POINTER_FROM_KDS_PTR(kdsp
);
993 kd_ctrl_page
.kds_free_list
= kdsp_actual
->kds_next
;
995 kd_ctrl_page
.kds_inuse_count
++;
998 * Otherwise, we're going to lose events and repurpose the oldest
999 * storage unit we can find.
1001 if (kd_ctrl_page
.kdebug_flags
& KDBG_NOWRAP
) {
1002 kd_ctrl_page
.kdebug_slowcheck
|= SLOW_NOLOG
;
1003 kdbp
->kd_lostevents
= true;
1008 oldest_ts
= UINT64_MAX
;
1010 for (kdbp_try
= &kdbip
[0]; kdbp_try
< &kdbip
[kd_ctrl_page
.kdebug_cpus
]; kdbp_try
++) {
1011 if (kdbp_try
->kd_list_head
.raw
== KDS_PTR_NULL
) {
1013 * no storage unit to steal
1018 kdsp_actual
= POINTER_FROM_KDS_PTR(kdbp_try
->kd_list_head
);
1020 if (kdsp_actual
->kds_bufcnt
< EVENTS_PER_STORAGE_UNIT
) {
1022 * make sure we don't steal the storage unit
1023 * being actively recorded to... need to
1024 * move on because we don't want an out-of-order
1025 * set of events showing up later
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.
1038 ts
= kdbg_get_timestamp(&kdsp_actual
->kds_records
[EVENTS_PER_STORAGE_UNIT
- 1]);
1039 if (ts
< oldest_ts
) {
1041 kdbp_vict
= kdbp_try
;
1044 if (kdbp_vict
== NULL
) {
1046 kd_ctrl_page
.enabled
= 0;
1047 commpage_update_kdebug_state();
1051 kdsp
= kdbp_vict
->kd_list_head
;
1052 kdsp_actual
= POINTER_FROM_KDS_PTR(kdsp
);
1053 kdbp_vict
->kd_list_head
= kdsp_actual
->kds_next
;
1055 if (kdbp_vict
->kd_list_head
.raw
!= KDS_PTR_NULL
) {
1056 kdsp_next_actual
= POINTER_FROM_KDS_PTR(kdbp_vict
->kd_list_head
);
1057 kdsp_next_actual
->kds_lostevents
= true;
1059 kdbp_vict
->kd_lostevents
= true;
1062 if (kd_ctrl_page
.oldest_time
< oldest_ts
) {
1063 kd_ctrl_page
.oldest_time
= oldest_ts
;
1065 kd_ctrl_page
.kdebug_flags
|= KDBG_WRAPPED
;
1067 kdsp_actual
->kds_timestamp
= kdbg_timestamp();
1068 kdsp_actual
->kds_next
.raw
= KDS_PTR_NULL
;
1069 kdsp_actual
->kds_bufcnt
= 0;
1070 kdsp_actual
->kds_readlast
= 0;
1072 kdsp_actual
->kds_lostevents
= kdbp
->kd_lostevents
;
1073 kdbp
->kd_lostevents
= false;
1074 kdsp_actual
->kds_bufindx
= 0;
1076 if (kdbp
->kd_list_head
.raw
== KDS_PTR_NULL
) {
1077 kdbp
->kd_list_head
= kdsp
;
1079 POINTER_FROM_KDS_PTR(kdbp
->kd_list_tail
)->kds_next
= kdsp
;
1081 kdbp
->kd_list_tail
= kdsp
;
1083 lck_spin_unlock(&kds_spin_lock
);
1084 ml_set_interrupts_enabled(s
);
1090 kernel_debug_register_callback(kd_callback_t callback
)
1093 if (kmem_alloc(kernel_map
, (vm_offset_t
*)&iop
, sizeof(kd_iop_t
), VM_KERN_MEMORY_DIAG
) == KERN_SUCCESS
) {
1094 memcpy(&iop
->callback
, &callback
, sizeof(kd_callback_t
));
1097 * <rdar://problem/13351477> Some IOP clients are not providing a name.
1099 * Remove when fixed.
1102 bool is_valid_name
= false;
1103 for (uint32_t length
= 0; length
< sizeof(callback
.iop_name
); ++length
) {
1104 /* This is roughly isprintable(c) */
1105 if (callback
.iop_name
[length
] > 0x20 && callback
.iop_name
[length
] < 0x7F) {
1108 if (callback
.iop_name
[length
] == 0) {
1110 is_valid_name
= true;
1116 if (!is_valid_name
) {
1117 strlcpy(iop
->callback
.iop_name
, "IOP-???", sizeof(iop
->callback
.iop_name
));
1121 iop
->last_timestamp
= 0;
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
1130 * TLDR; Must not read kd_iops more than once per loop.
1132 iop
->next
= kd_iops
;
1133 iop
->cpu_id
= iop
->next
? (iop
->next
->cpu_id
+ 1) : kdbg_cpu_count(false);
1136 * Header says OSCompareAndSwapPtr has a memory barrier
1138 } while (!OSCompareAndSwapPtr(iop
->next
, iop
, (void* volatile*)&kd_iops
));
1160 struct kd_bufinfo
*kdbp
;
1161 struct kd_storage
*kdsp_actual
;
1162 union kds_ptr kds_raw
;
1164 if (kd_ctrl_page
.kdebug_slowcheck
) {
1165 if ((kd_ctrl_page
.kdebug_slowcheck
& SLOW_NOLOG
) || !(kdebug_enable
& (KDEBUG_ENABLE_TRACE
| KDEBUG_ENABLE_PPT
))) {
1169 if (kd_ctrl_page
.kdebug_flags
& KDBG_TYPEFILTER_CHECK
) {
1170 if (typefilter_is_debugid_allowed(kdbg_typefilter
, debugid
)) {
1174 } else if (kd_ctrl_page
.kdebug_flags
& KDBG_RANGECHECK
) {
1175 if (debugid
>= kdlog_beg
&& debugid
<= kdlog_end
) {
1179 } else if (kd_ctrl_page
.kdebug_flags
& KDBG_VALCHECK
) {
1180 if ((debugid
& KDBG_EVENTID_MASK
) != kdlog_value1
&&
1181 (debugid
& KDBG_EVENTID_MASK
) != kdlog_value2
&&
1182 (debugid
& KDBG_EVENTID_MASK
) != kdlog_value3
&&
1183 (debugid
& KDBG_EVENTID_MASK
) != kdlog_value4
) {
1190 if (timestamp
< kd_ctrl_page
.oldest_time
) {
1194 disable_preemption();
1196 if (kd_ctrl_page
.enabled
== 0) {
1200 kdbp
= &kdbip
[coreid
];
1201 timestamp
&= KDBG_TIMESTAMP_MASK
;
1204 kds_raw
= kdbp
->kd_list_tail
;
1206 if (kds_raw
.raw
!= KDS_PTR_NULL
) {
1207 kdsp_actual
= POINTER_FROM_KDS_PTR(kds_raw
);
1208 bindx
= kdsp_actual
->kds_bufindx
;
1211 bindx
= EVENTS_PER_STORAGE_UNIT
;
1214 if (kdsp_actual
== NULL
|| bindx
>= EVENTS_PER_STORAGE_UNIT
) {
1215 if (allocate_storage_unit(coreid
) == false) {
1217 * this can only happen if wrapping
1224 if (!OSCompareAndSwap(bindx
, bindx
+ 1, &kdsp_actual
->kds_bufindx
)) {
1228 // IOP entries can be allocated before xnu allocates and inits the buffer
1229 if (timestamp
< kdsp_actual
->kds_timestamp
) {
1230 kdsp_actual
->kds_timestamp
= timestamp
;
1233 kd
= &kdsp_actual
->kds_records
[bindx
];
1235 kd
->debugid
= debugid
;
1240 kd
->arg5
= threadid
;
1242 kdbg_set_timestamp_and_cpu(kd
, timestamp
, coreid
);
1244 OSAddAtomic(1, &kdsp_actual
->kds_bufcnt
);
1246 enable_preemption();
1248 if ((kds_waiter
&& kd_ctrl_page
.kds_inuse_count
>= n_storage_threshold
)) {
1254 * Check if the given debug ID is allowed to be traced on the current process.
1256 * Returns true if allowed and false otherwise.
1259 kdebug_debugid_procfilt_allowed(uint32_t debugid
)
1261 uint32_t procfilt_flags
= kd_ctrl_page
.kdebug_flags
&
1262 (KDBG_PIDCHECK
| KDBG_PIDEXCLUDE
);
1264 if (!procfilt_flags
) {
1269 * DBG_TRACE and MACH_SCHED tracepoints ignore the process filter.
1271 if ((debugid
& 0xffff0000) == MACHDBG_CODE(DBG_MACH_SCHED
, 0) ||
1272 (debugid
>> 24 == DBG_TRACE
)) {
1276 struct proc
*curproc
= current_proc();
1278 * If the process is missing (early in boot), allow it.
1284 if (procfilt_flags
& KDBG_PIDCHECK
) {
1286 * Allow only processes marked with the kdebug bit.
1288 return curproc
->p_kdebug
;
1289 } else if (procfilt_flags
& KDBG_PIDEXCLUDE
) {
1291 * Exclude any process marked with the kdebug bit.
1293 return !curproc
->p_kdebug
;
1295 panic("kdebug: invalid procfilt flags %x", kd_ctrl_page
.kdebug_flags
);
1296 __builtin_unreachable();
1301 kernel_debug_internal(
1314 struct kd_bufinfo
*kdbp
;
1315 struct kd_storage
*kdsp_actual
;
1316 union kds_ptr kds_raw
;
1317 bool only_filter
= flags
& KDBG_FLAG_FILTERED
;
1318 bool observe_procfilt
= !(flags
& KDBG_FLAG_NOPROCFILT
);
1320 if (kd_ctrl_page
.kdebug_slowcheck
) {
1321 if ((kd_ctrl_page
.kdebug_slowcheck
& SLOW_NOLOG
) ||
1322 !(kdebug_enable
& (KDEBUG_ENABLE_TRACE
| KDEBUG_ENABLE_PPT
))) {
1326 if (!ml_at_interrupt_context() && observe_procfilt
&&
1327 !kdebug_debugid_procfilt_allowed(debugid
)) {
1331 if (kd_ctrl_page
.kdebug_flags
& KDBG_TYPEFILTER_CHECK
) {
1332 if (typefilter_is_debugid_allowed(kdbg_typefilter
, debugid
)) {
1337 } else if (only_filter
) {
1339 } else if (kd_ctrl_page
.kdebug_flags
& KDBG_RANGECHECK
) {
1340 /* Always record trace system info */
1341 if (KDBG_EXTRACT_CLASS(debugid
) == DBG_TRACE
) {
1345 if (debugid
< kdlog_beg
|| debugid
> kdlog_end
) {
1348 } else if (kd_ctrl_page
.kdebug_flags
& KDBG_VALCHECK
) {
1349 /* Always record trace system info */
1350 if (KDBG_EXTRACT_CLASS(debugid
) == DBG_TRACE
) {
1354 if ((debugid
& KDBG_EVENTID_MASK
) != kdlog_value1
&&
1355 (debugid
& KDBG_EVENTID_MASK
) != kdlog_value2
&&
1356 (debugid
& KDBG_EVENTID_MASK
) != kdlog_value3
&&
1357 (debugid
& KDBG_EVENTID_MASK
) != kdlog_value4
) {
1361 } else if (only_filter
) {
1366 disable_preemption();
1368 if (kd_ctrl_page
.enabled
== 0) {
1376 kds_raw
= kdbp
->kd_list_tail
;
1378 if (kds_raw
.raw
!= KDS_PTR_NULL
) {
1379 kdsp_actual
= POINTER_FROM_KDS_PTR(kds_raw
);
1380 bindx
= kdsp_actual
->kds_bufindx
;
1383 bindx
= EVENTS_PER_STORAGE_UNIT
;
1386 if (kdsp_actual
== NULL
|| bindx
>= EVENTS_PER_STORAGE_UNIT
) {
1387 if (allocate_storage_unit(cpu
) == false) {
1389 * this can only happen if wrapping
1397 now
= kdbg_timestamp() & KDBG_TIMESTAMP_MASK
;
1399 if (!OSCompareAndSwap(bindx
, bindx
+ 1, &kdsp_actual
->kds_bufindx
)) {
1403 kd
= &kdsp_actual
->kds_records
[bindx
];
1405 kd
->debugid
= debugid
;
1412 kdbg_set_timestamp_and_cpu(kd
, now
, cpu
);
1414 OSAddAtomic(1, &kdsp_actual
->kds_bufcnt
);
1417 kperf_kdebug_callback(debugid
, __builtin_frame_address(0));
1420 enable_preemption();
1422 if (kds_waiter
&& kd_ctrl_page
.kds_inuse_count
>= n_storage_threshold
) {
1426 etype
= debugid
& KDBG_EVENTID_MASK
;
1427 stype
= debugid
& KDBG_CSC_MASK
;
1429 if (etype
== INTERRUPT
|| etype
== MACH_vmfault
||
1430 stype
== BSC_SysCall
|| stype
== MACH_SysCall
) {
1436 __attribute__((noinline
))
1444 __unused
uintptr_t arg5
)
1446 kernel_debug_internal(debugid
, arg1
, arg2
, arg3
, arg4
,
1447 (uintptr_t)thread_tid(current_thread()), 0);
1450 __attribute__((noinline
))
1460 kernel_debug_internal(debugid
, arg1
, arg2
, arg3
, arg4
, arg5
, 0);
1463 __attribute__((noinline
))
1473 kernel_debug_internal(debugid
, arg1
, arg2
, arg3
, arg4
,
1474 (uintptr_t)thread_tid(current_thread()), flags
);
1477 __attribute__((noinline
))
1479 kernel_debug_filtered(
1486 kernel_debug_flags(debugid
, arg1
, arg2
, arg3
, arg4
, KDBG_FLAG_FILTERED
);
1490 kernel_debug_string_early(const char *message
)
1492 uintptr_t arg
[4] = {0, 0, 0, 0};
1494 /* Stuff the message string in the args and log it. */
1495 strncpy((char *)arg
, message
, MIN(sizeof(arg
), strlen(message
)));
1498 arg
[0], arg
[1], arg
[2], arg
[3]);
1501 #define SIMPLE_STR_LEN (64)
1502 static_assert(SIMPLE_STR_LEN
% sizeof(uintptr_t) == 0);
1505 kernel_debug_string_simple(uint32_t eventid
, const char *str
)
1507 if (!kdebug_enable
) {
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);
1515 uintptr_t thread_id
= (uintptr_t)thread_tid(current_thread());
1516 uint32_t debugid
= eventid
| DBG_FUNC_START
;
1518 /* string can fit in a single tracepoint */
1519 if (len
<= (4 * sizeof(uintptr_t))) {
1520 debugid
|= DBG_FUNC_END
;
1523 kernel_debug_internal(debugid
, str_buf
[0],
1526 str_buf
[3], thread_id
, 0);
1528 debugid
&= KDBG_EVENTID_MASK
;
1530 size_t written
= 4 * sizeof(uintptr_t);
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
;
1537 kernel_debug_internal(debugid
, str_buf
[i
],
1540 str_buf
[i
+ 3], thread_id
, 0);
1544 extern int master_cpu
; /* MACH_KERNEL_PRIVATE */
1546 * Used prior to start_kern_tracing() being called.
1547 * Log temporarily into a static buffer.
1557 #if defined(__x86_64__)
1558 extern int early_boot
;
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".
1569 /* If early tracing is over, use the normal path. */
1570 if (kd_early_done
) {
1571 KDBG_RELEASE(debugid
, arg1
, arg2
, arg3
, arg4
);
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
) {
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;
1592 * Transfer the contents of the temporary buffer into the trace buffers.
1593 * Precede that by logging the rebase time (offset) - the TSC-based time (in ns)
1594 * when mach_absolute_time is set to 0.
1597 kernel_debug_early_end(void)
1599 if (cpu_number() != master_cpu
) {
1600 panic("kernel_debug_early_end() not call on boot processor");
1603 /* reset the current oldest time to allow early events */
1604 kd_ctrl_page
.oldest_time
= 0;
1606 #if defined(__x86_64__)
1607 /* Fake sentinel marking the start of kernel time relative to TSC */
1608 kernel_debug_enter(0, TRACE_TIMESTAMPS
, 0,
1609 (uint32_t)(tsc_rebase_abs_time
>> 32), (uint32_t)tsc_rebase_abs_time
,
1611 #endif /* defined(__x86_64__) */
1612 for (unsigned int i
= 0; i
< kd_early_index
; i
++) {
1613 kernel_debug_enter(0,
1614 kd_early_buffer
[i
].debugid
,
1615 kd_early_buffer
[i
].timestamp
,
1616 kd_early_buffer
[i
].arg1
,
1617 kd_early_buffer
[i
].arg2
,
1618 kd_early_buffer
[i
].arg3
,
1619 kd_early_buffer
[i
].arg4
,
1623 /* Cut events-lost event on overflow */
1624 if (kd_early_overflow
) {
1625 KDBG_RELEASE(TRACE_LOST_EVENTS
, 1);
1628 kd_early_done
= true;
1630 /* This trace marks the start of kernel tracing */
1631 kernel_debug_string_early("early trace done");
1635 kernel_debug_disable(void)
1637 if (kdebug_enable
) {
1638 kdbg_set_tracing_enabled(false, 0);
1643 * Returns non-zero if debugid is in a reserved class.
1646 kdebug_validate_debugid(uint32_t debugid
)
1648 uint8_t debugid_class
;
1650 debugid_class
= KDBG_EXTRACT_CLASS(debugid
);
1651 switch (debugid_class
) {
1660 * Support syscall SYS_kdebug_typefilter.
1663 kdebug_typefilter(__unused
struct proc
* p
,
1664 struct kdebug_typefilter_args
* uap
,
1665 __unused
int *retval
)
1667 int ret
= KERN_SUCCESS
;
1669 if (uap
->addr
== USER_ADDR_NULL
||
1670 uap
->size
== USER_ADDR_NULL
) {
1675 * The atomic load is to close a race window with setting the typefilter
1676 * and memory entry values. A description follows:
1680 * Allocate Typefilter
1681 * Allocate MemoryEntry
1682 * Write Global MemoryEntry Ptr
1683 * Atomic Store (Release) Global Typefilter Ptr
1685 * Thread 2 (reader, AKA us)
1687 * if ((Atomic Load (Acquire) Global Typefilter Ptr) == NULL)
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.
1694 * Without the atomic load, it isn't guaranteed that the loads of
1695 * Global MemoryEntry Ptr aren't speculated.
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.
1702 if (!os_atomic_load(&kdbg_typefilter
, acquire
)) {
1706 assert(kdbg_typefilter_memory_entry
);
1708 mach_vm_offset_t user_addr
= 0;
1709 vm_map_t user_map
= current_map();
1711 ret
= mach_to_bsd_errno(
1712 mach_vm_map_kernel(user_map
, // target map
1713 &user_addr
, // [in, out] target address
1714 TYPEFILTER_ALLOC_SIZE
, // initial size
1715 0, // mask (alignment?)
1716 VM_FLAGS_ANYWHERE
, // flags
1717 VM_MAP_KERNEL_FLAGS_NONE
,
1718 VM_KERN_MEMORY_NONE
,
1719 kdbg_typefilter_memory_entry
, // port (memory entry!)
1720 0, // offset (in memory entry)
1721 false, // should copy
1722 VM_PROT_READ
, // cur_prot
1723 VM_PROT_READ
, // max_prot
1724 VM_INHERIT_SHARE
)); // inherit behavior on fork
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
);
1730 if (ret
!= KERN_SUCCESS
) {
1731 mach_vm_deallocate(user_map
, user_addr
, TYPEFILTER_ALLOC_SIZE
);
1739 * Support syscall SYS_kdebug_trace. U64->K32 args may get truncated in kdebug_trace64
1742 kdebug_trace(struct proc
*p
, struct kdebug_trace_args
*uap
, int32_t *retval
)
1744 struct kdebug_trace64_args uap64
;
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
;
1752 return kdebug_trace64(p
, &uap64
, retval
);
1756 * Support syscall SYS_kdebug_trace64. 64-bit args on K32 will get truncated
1757 * to fit in 32-bit record format.
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.
1764 kdebug_trace64(__unused
struct proc
*p
, struct kdebug_trace64_args
*uap
, __unused
int32_t *retval
)
1768 if (__probable(kdebug_enable
== 0)) {
1772 if ((err
= kdebug_validate_debugid(uap
->code
)) != 0) {
1776 kernel_debug_internal(uap
->code
, (uintptr_t)uap
->arg1
,
1777 (uintptr_t)uap
->arg2
, (uintptr_t)uap
->arg3
, (uintptr_t)uap
->arg4
,
1778 (uintptr_t)thread_tid(current_thread()), 0);
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
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)))
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.
1808 kernel_debug_string_internal(uint32_t debugid
, uint64_t str_id
, void *vstr
,
1811 /* str must be word-aligned */
1812 uintptr_t *str
= vstr
;
1814 uintptr_t thread_id
;
1816 uint32_t trace_debugid
= TRACEDBG_CODE(DBG_TRACE_STRING
,
1817 TRACE_STRING_GLOBAL
);
1819 thread_id
= (uintptr_t)thread_tid(current_thread());
1821 /* if the ID is being invalidated, just emit that */
1822 if (str_id
!= 0 && str_len
== 0) {
1823 kernel_debug_internal(trace_debugid
| DBG_FUNC_START
| DBG_FUNC_END
,
1824 (uintptr_t)debugid
, (uintptr_t)str_id
, 0, 0, thread_id
, 0);
1828 /* generate an ID, if necessary */
1830 str_id
= OSIncrementAtomic64((SInt64
*)&g_curr_str_id
);
1831 str_id
= (str_id
& STR_ID_MASK
) | g_str_id_signature
;
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
;
1840 kernel_debug_internal(trace_debugid
, (uintptr_t)debugid
, (uintptr_t)str_id
,
1841 str
[0], str
[1], thread_id
, 0);
1843 trace_debugid
&= KDBG_EVENTID_MASK
;
1845 written
+= 2 * sizeof(uintptr_t);
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
;
1851 kernel_debug_internal(trace_debugid
, str
[i
],
1854 str
[i
+ 3], thread_id
, 0);
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.
1866 kdebug_current_proc_enabled(uint32_t debugid
)
1868 /* can't determine current process in interrupt context */
1869 if (ml_at_interrupt_context()) {
1873 /* always emit trace system and scheduling events */
1874 if ((KDBG_EXTRACT_CLASS(debugid
) == DBG_TRACE
||
1875 (debugid
& KDBG_CSC_MASK
) == MACHDBG_CODE(DBG_MACH_SCHED
, 0))) {
1879 if (kd_ctrl_page
.kdebug_flags
& KDBG_PIDCHECK
) {
1880 proc_t cur_proc
= current_proc();
1882 /* only the process with the kdebug bit set is allowed */
1883 if (cur_proc
&& !(cur_proc
->p_kdebug
)) {
1886 } else if (kd_ctrl_page
.kdebug_flags
& KDBG_PIDEXCLUDE
) {
1887 proc_t cur_proc
= current_proc();
1889 /* every process except the one with the kdebug bit set is allowed */
1890 if (cur_proc
&& cur_proc
->p_kdebug
) {
1899 kdebug_debugid_enabled(uint32_t debugid
)
1901 /* if no filtering is enabled */
1902 if (!kd_ctrl_page
.kdebug_slowcheck
) {
1906 return kdebug_debugid_explicitly_enabled(debugid
);
1910 kdebug_debugid_explicitly_enabled(uint32_t debugid
)
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
) {
1916 } else if (kd_ctrl_page
.kdebug_flags
& KDBG_RANGECHECK
) {
1917 if (debugid
< kdlog_beg
|| debugid
> kdlog_end
) {
1920 } else if (kd_ctrl_page
.kdebug_flags
& KDBG_VALCHECK
) {
1921 if ((debugid
& KDBG_EVENTID_MASK
) != kdlog_value1
&&
1922 (debugid
& KDBG_EVENTID_MASK
) != kdlog_value2
&&
1923 (debugid
& KDBG_EVENTID_MASK
) != kdlog_value3
&&
1924 (debugid
& KDBG_EVENTID_MASK
) != kdlog_value4
) {
1933 kdebug_using_continuous_time(void)
1935 return kdebug_enable
& KDEBUG_ENABLE_CONT_TIME
;
1939 * Returns 0 if a string can be traced with these arguments. Returns errno
1940 * value if error occurred.
1943 kdebug_check_trace_string(uint32_t debugid
, uint64_t str_id
)
1945 /* if there are function qualifiers on the debugid */
1946 if (debugid
& ~KDBG_EVENTID_MASK
) {
1950 if (kdebug_validate_debugid(debugid
)) {
1954 if (str_id
!= 0 && (str_id
& STR_ID_SIG_MASK
) != g_str_id_signature
) {
1962 * Implementation of KPI kernel_debug_string.
1965 kernel_debug_string(uint32_t debugid
, uint64_t *str_id
, const char *str
)
1967 /* arguments to tracepoints must be word-aligned */
1968 __attribute__((aligned(sizeof(uintptr_t)))) char str_buf
[STR_BUF_SIZE
];
1969 static_assert(sizeof(str_buf
) > MAX_STR_LEN
);
1970 vm_size_t len_copied
;
1975 if (__probable(kdebug_enable
== 0)) {
1979 if (!kdebug_current_proc_enabled(debugid
)) {
1983 if (!kdebug_debugid_enabled(debugid
)) {
1987 if ((err
= kdebug_check_trace_string(debugid
, *str_id
)) != 0) {
1996 *str_id
= kernel_debug_string_internal(debugid
, *str_id
, NULL
, 0);
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
,
2008 * Support syscall kdebug_trace_string.
2011 kdebug_trace_string(__unused
struct proc
*p
,
2012 struct kdebug_trace_string_args
*uap
,
2015 __attribute__((aligned(sizeof(uintptr_t)))) char str_buf
[STR_BUF_SIZE
];
2016 static_assert(sizeof(str_buf
) > MAX_STR_LEN
);
2020 if (__probable(kdebug_enable
== 0)) {
2024 if (!kdebug_current_proc_enabled(uap
->debugid
)) {
2028 if (!kdebug_debugid_enabled(uap
->debugid
)) {
2032 if ((err
= kdebug_check_trace_string(uap
->debugid
, uap
->str_id
)) != 0) {
2036 if (uap
->str
== USER_ADDR_NULL
) {
2037 if (uap
->str_id
== 0) {
2041 *retval
= kernel_debug_string_internal(uap
->debugid
, uap
->str_id
,
2046 memset(str_buf
, 0, sizeof(str_buf
));
2047 err
= copyinstr(uap
->str
, str_buf
, MAX_STR_LEN
+ 1, &len_copied
);
2049 /* it's alright to truncate the string, so allow ENAMETOOLONG */
2050 if (err
== ENAMETOOLONG
) {
2051 str_buf
[MAX_STR_LEN
] = '\0';
2056 if (len_copied
<= 1) {
2060 /* convert back to a length */
2063 *retval
= kernel_debug_string_internal(uap
->debugid
, uap
->str_id
, str_buf
,
2069 kdbg_bootstrap(bool early_trace
)
2071 kd_ctrl_page
.kdebug_flags
&= ~KDBG_WRAPPED
;
2073 return create_buffers(early_trace
);
2077 kdbg_reinit(bool early_trace
)
2082 * Disable trace collecting
2083 * First make sure we're not in
2084 * the middle of cutting a trace
2086 kernel_debug_disable();
2089 * make sure the SLOW_NOLOG is seen
2090 * by everyone that might be trying
2097 kdbg_clear_thread_map();
2098 ret
= kdbg_bootstrap(early_trace
);
2100 RAW_file_offset
= 0;
2101 RAW_file_written
= 0;
2107 kdbg_trace_data(struct proc
*proc
, long *arg_pid
, long *arg_uniqueid
)
2113 *arg_pid
= proc
->p_pid
;
2114 /* Fit in a trace point */
2115 *arg_uniqueid
= (long)proc
->p_uniqueid
;
2116 if ((uint64_t) *arg_uniqueid
!= proc
->p_uniqueid
) {
2124 kdbg_trace_string(struct proc
*proc
, long *arg1
, long *arg2
, long *arg3
,
2135 const char *procname
= proc_best_name(proc
);
2136 size_t namelen
= strlen(procname
);
2138 long args
[4] = { 0 };
2140 if (namelen
> sizeof(args
)) {
2141 namelen
= sizeof(args
);
2144 strncpy((char *)args
, procname
, namelen
);
2154 * Writes a cpumap for the given iops_list/cpu_count to the provided buffer.
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.
2159 * If you provide a buffer and it is too small, sets cpumap_size to the number
2160 * of bytes required and returns EINVAL.
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.
2166 * NOTE: It may seem redundant to pass both iops and a cpu_count.
2168 * We may be reporting data from "now", or from the "past".
2170 * The "past" data would be for kdbg_readcpumap().
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.
2178 kdbg_cpumap_init_internal(kd_iop_t
* iops
, uint32_t cpu_count
, uint8_t** cpumap
, uint32_t* cpumap_size
)
2181 assert(cpumap_size
);
2183 assert(!iops
|| iops
->cpu_id
+ 1 == cpu_count
);
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
;
2189 if (*cpumap
== NULL
) {
2190 if (kmem_alloc(kernel_map
, (vm_offset_t
*)cpumap
, (vm_size_t
)*cpumap_size
, VM_KERN_MEMORY_DIAG
) != KERN_SUCCESS
) {
2193 bzero(*cpumap
, *cpumap_size
);
2194 } else if (bytes_available
< bytes_needed
) {
2198 kd_cpumap_header
* header
= (kd_cpumap_header
*)(uintptr_t)*cpumap
;
2200 header
->version_no
= RAW_VERSION1
;
2201 header
->cpu_count
= cpu_count
;
2203 kd_cpumap
* cpus
= (kd_cpumap
*)&header
[1];
2205 int32_t index
= cpu_count
- 1;
2207 cpus
[index
].cpu_id
= iops
->cpu_id
;
2208 cpus
[index
].flags
= KDBG_CPUMAP_IS_IOP
;
2209 strlcpy(cpus
[index
].name
, iops
->callback
.iop_name
, sizeof(cpus
->name
));
2215 while (index
>= 0) {
2216 cpus
[index
].cpu_id
= index
;
2217 cpus
[index
].flags
= 0;
2218 strlcpy(cpus
[index
].name
, "AP", sizeof(cpus
->name
));
2223 return KERN_SUCCESS
;
2227 kdbg_thrmap_init(void)
2229 ktrace_assert_lock_held();
2231 if (kd_ctrl_page
.kdebug_flags
& KDBG_MAPINIT
) {
2235 kd_mapptr
= kdbg_thrmap_init_internal(0, &kd_mapsize
, &kd_mapcount
);
2238 kd_ctrl_page
.kdebug_flags
|= KDBG_MAPINIT
;
2243 kd_resolve_map(thread_t thread
, void *opaque
)
2245 struct kd_resolver
*resolve
= opaque
;
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
);
2252 (void)strlcpy(map
->command
, task_name
->ktn_name
, sizeof(map
->command
));
2254 * Kernel threads should still be marked with non-zero valid bit.
2256 pid_t pid
= resolve
->krs_task
->ktn_pid
;
2257 map
->valid
= pid
== 0 ? 1 : pid
;
2258 resolve
->krs_count
++;
2263 kd_resolve_tasks(struct kd_task_name
*task_names
, vm_size_t ntasks
)
2266 proc_t p
= PROC_NULL
;
2269 ALLPROC_FOREACH(p
) {
2274 * Only record processes that can be referenced and are not exiting.
2276 if (p
->task
&& (p
->p_lflag
& P_LEXIT
) == 0) {
2277 task_reference(p
->task
);
2278 task_names
[i
].ktn_task
= p
->task
;
2279 task_names
[i
].ktn_pid
= p
->p_pid
;
2280 (void)strlcpy(task_names
[i
].ktn_name
, proc_best_name(p
),
2281 sizeof(task_names
[i
].ktn_name
));
2291 kd_resolve_threads(kd_threadmap
*map
, struct kd_task_name
*task_names
,
2292 vm_size_t ntasks
, vm_size_t nthreads
)
2294 struct kd_resolver resolver
= {
2295 .krs_map
= map
, .krs_count
= 0, .krs_maxcount
= nthreads
,
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
,
2303 task_deallocate(cur_task
->ktn_task
);
2306 return resolver
.krs_count
;
2309 static kd_threadmap
*
2310 kdbg_thrmap_init_internal(size_t maxthreads
, vm_size_t
*mapsize
,
2311 vm_size_t
*mapcount
)
2313 kd_threadmap
*thread_map
= NULL
;
2314 struct kd_task_name
*task_names
;
2315 vm_size_t names_size
= 0;
2317 assert(mapsize
!= NULL
);
2318 assert(mapcount
!= NULL
);
2320 vm_size_t nthreads
= threads_count
;
2321 vm_size_t ntasks
= tasks_count
;
2324 * Allow 25% more threads and tasks to be created between now and taking the
2327 if (os_add_overflow(nthreads
, nthreads
/ 4, &nthreads
) ||
2328 os_add_overflow(ntasks
, ntasks
/ 4, &ntasks
)) {
2332 *mapcount
= nthreads
;
2333 if (os_mul_overflow(nthreads
, sizeof(kd_threadmap
), mapsize
)) {
2336 if (os_mul_overflow(ntasks
, sizeof(task_names
[0]), &names_size
)) {
2341 * Wait until the out-parameters have been filled with the needed size to
2342 * do the bounds checking on the provided maximum.
2344 if (maxthreads
!= 0 && maxthreads
< nthreads
) {
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
);
2361 * Clean up the trace buffer
2362 * First make sure we're not in
2363 * the middle of cutting a trace
2365 kernel_debug_disable();
2366 kdbg_disable_typefilter();
2369 * make sure the SLOW_NOLOG is seen
2370 * by everyone that might be trying
2375 /* reset kdebug state for each process */
2376 if (kd_ctrl_page
.kdebug_flags
& (KDBG_PIDCHECK
| KDBG_PIDEXCLUDE
)) {
2379 ALLPROC_FOREACH(p
) {
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
);
2389 kd_ctrl_page
.oldest_time
= 0;
2394 /* Clean up the thread map buffer */
2395 kdbg_clear_thread_map();
2397 RAW_file_offset
= 0;
2398 RAW_file_written
= 0;
2404 ktrace_assert_lock_held();
2407 if (kdbg_typefilter
) {
2408 typefilter_reject_all(kdbg_typefilter
);
2409 typefilter_allow_class(kdbg_typefilter
, DBG_TRACE
);
2414 kdebug_free_early_buf(void)
2416 #if defined(__x86_64__)
2418 * Make Intel aware that the early buffer is no longer being used. ARM
2419 * handles this as part of the BOOTDATA segment.
2421 ml_static_mfree((vm_offset_t
)&kd_early_buffer
, sizeof(kd_early_buffer
));
2422 #endif /* defined(__x86_64__) */
2426 kdbg_setpid(kd_regtype
*kdr
)
2432 pid
= (pid_t
)kdr
->value1
;
2433 flag
= (int)kdr
->value2
;
2436 if ((p
= proc_find(pid
)) == NULL
) {
2441 * turn on pid check for this and all pids
2443 kd_ctrl_page
.kdebug_flags
|= KDBG_PIDCHECK
;
2444 kd_ctrl_page
.kdebug_flags
&= ~KDBG_PIDEXCLUDE
;
2445 kdbg_set_flags(SLOW_CHECKS
, 0, true);
2450 * turn off pid check for this pid value
2451 * Don't turn off all pid checking though
2453 * kd_ctrl_page.kdebug_flags &= ~KDBG_PIDCHECK;
2466 /* This is for pid exclusion in the trace buffer */
2468 kdbg_setpidex(kd_regtype
*kdr
)
2474 pid
= (pid_t
)kdr
->value1
;
2475 flag
= (int)kdr
->value2
;
2478 if ((p
= proc_find(pid
)) == NULL
) {
2483 * turn on pid exclusion
2485 kd_ctrl_page
.kdebug_flags
|= KDBG_PIDEXCLUDE
;
2486 kd_ctrl_page
.kdebug_flags
&= ~KDBG_PIDCHECK
;
2487 kdbg_set_flags(SLOW_CHECKS
, 0, true);
2492 * turn off pid exclusion for this pid value
2493 * Don't turn off all pid exclusion though
2495 * kd_ctrl_page.kdebug_flags &= ~KDBG_PIDEXCLUDE;
2509 * The following functions all operate on the "global" typefilter singleton.
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.
2517 kdbg_initialize_typefilter(typefilter_t tf
)
2519 ktrace_assert_lock_held();
2520 assert(!kdbg_typefilter
);
2521 assert(!kdbg_typefilter_memory_entry
);
2522 typefilter_t deallocate_tf
= NULL
;
2524 if (!tf
&& ((tf
= deallocate_tf
= typefilter_create()) == NULL
)) {
2528 if ((kdbg_typefilter_memory_entry
= typefilter_create_memory_entry(tf
)) == MACH_PORT_NULL
) {
2529 if (deallocate_tf
) {
2530 typefilter_deallocate(deallocate_tf
);
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.
2541 os_atomic_store(&kdbg_typefilter
, tf
, release
);
2543 return KERN_SUCCESS
;
2547 kdbg_copyin_typefilter(user_addr_t addr
, size_t size
)
2552 ktrace_assert_lock_held();
2554 if (size
!= KDBG_TYPEFILTER_BITMAP_SIZE
) {
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
);
2564 * If this is the first typefilter; claim it.
2565 * Otherwise copy and deallocate.
2567 * Allocating a typefilter for the copyin allows
2568 * the kernel to hold the invariant that DBG_TRACE
2569 * must always be allowed.
2571 if (!kdbg_typefilter
) {
2572 if ((ret
= kdbg_initialize_typefilter(tf
))) {
2577 typefilter_copy(kdbg_typefilter
, tf
);
2580 kdbg_enable_typefilter();
2581 kdbg_iop_list_callback(kd_ctrl_page
.kdebug_iops
, KD_CALLBACK_TYPEFILTER_CHANGED
, kdbg_typefilter
);
2585 typefilter_deallocate(tf
);
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.
2598 kdbg_enable_typefilter(void)
2600 assert(kdbg_typefilter
);
2601 kd_ctrl_page
.kdebug_flags
&= ~(KDBG_RANGECHECK
| KDBG_VALCHECK
);
2602 kd_ctrl_page
.kdebug_flags
|= KDBG_TYPEFILTER_CHECK
;
2603 kdbg_set_flags(SLOW_CHECKS
, 0, true);
2604 commpage_update_kdebug_state();
2608 * Disable the flags in the control page for the typefilter. The typefilter
2609 * may be safely deallocated shortly after this function returns.
2612 kdbg_disable_typefilter(void)
2614 bool notify_iops
= kd_ctrl_page
.kdebug_flags
& KDBG_TYPEFILTER_CHECK
;
2615 kd_ctrl_page
.kdebug_flags
&= ~KDBG_TYPEFILTER_CHECK
;
2617 if ((kd_ctrl_page
.kdebug_flags
& (KDBG_PIDCHECK
| KDBG_PIDEXCLUDE
))) {
2618 kdbg_set_flags(SLOW_CHECKS
, 0, true);
2620 kdbg_set_flags(SLOW_CHECKS
, 0, false);
2622 commpage_update_kdebug_state();
2626 * Notify IOPs that the typefilter will now allow everything.
2627 * Otherwise, they won't know a typefilter is no longer in
2630 typefilter_allow_all(kdbg_typefilter
);
2631 kdbg_iop_list_callback(kd_ctrl_page
.kdebug_iops
,
2632 KD_CALLBACK_TYPEFILTER_CHANGED
, kdbg_typefilter
);
2637 kdebug_commpage_state(void)
2639 if (kdebug_enable
) {
2640 if (kd_ctrl_page
.kdebug_flags
& KDBG_TYPEFILTER_CHECK
) {
2641 return KDEBUG_COMMPAGE_ENABLE_TYPEFILTER
| KDEBUG_COMMPAGE_ENABLE_TRACE
;
2644 return KDEBUG_COMMPAGE_ENABLE_TRACE
;
2651 kdbg_setreg(kd_regtype
* kdr
)
2654 unsigned int val_1
, val_2
, val
;
2655 switch (kdr
->type
) {
2656 case KDBG_CLASSTYPE
:
2657 val_1
= (kdr
->value1
& 0xff);
2658 val_2
= (kdr
->value2
& 0xff);
2659 kdlog_beg
= (val_1
<< 24);
2660 kdlog_end
= (val_2
<< 24);
2661 kd_ctrl_page
.kdebug_flags
&= (unsigned int)~KDBG_CKTYPES
;
2662 kd_ctrl_page
.kdebug_flags
&= ~KDBG_VALCHECK
; /* Turn off specific value check */
2663 kd_ctrl_page
.kdebug_flags
|= (KDBG_RANGECHECK
| KDBG_CLASSTYPE
);
2664 kdbg_set_flags(SLOW_CHECKS
, 0, true);
2666 case KDBG_SUBCLSTYPE
:
2667 val_1
= (kdr
->value1
& 0xff);
2668 val_2
= (kdr
->value2
& 0xff);
2670 kdlog_beg
= ((val_1
<< 24) | (val_2
<< 16));
2671 kdlog_end
= ((val_1
<< 24) | (val
<< 16));
2672 kd_ctrl_page
.kdebug_flags
&= (unsigned int)~KDBG_CKTYPES
;
2673 kd_ctrl_page
.kdebug_flags
&= ~KDBG_VALCHECK
; /* Turn off specific value check */
2674 kd_ctrl_page
.kdebug_flags
|= (KDBG_RANGECHECK
| KDBG_SUBCLSTYPE
);
2675 kdbg_set_flags(SLOW_CHECKS
, 0, true);
2677 case KDBG_RANGETYPE
:
2678 kdlog_beg
= (kdr
->value1
);
2679 kdlog_end
= (kdr
->value2
);
2680 kd_ctrl_page
.kdebug_flags
&= (unsigned int)~KDBG_CKTYPES
;
2681 kd_ctrl_page
.kdebug_flags
&= ~KDBG_VALCHECK
; /* Turn off specific value check */
2682 kd_ctrl_page
.kdebug_flags
|= (KDBG_RANGECHECK
| KDBG_RANGETYPE
);
2683 kdbg_set_flags(SLOW_CHECKS
, 0, true);
2686 kdlog_value1
= (kdr
->value1
);
2687 kdlog_value2
= (kdr
->value2
);
2688 kdlog_value3
= (kdr
->value3
);
2689 kdlog_value4
= (kdr
->value4
);
2690 kd_ctrl_page
.kdebug_flags
&= (unsigned int)~KDBG_CKTYPES
;
2691 kd_ctrl_page
.kdebug_flags
&= ~KDBG_RANGECHECK
; /* Turn off range check */
2692 kd_ctrl_page
.kdebug_flags
|= KDBG_VALCHECK
; /* Turn on specific value check */
2693 kdbg_set_flags(SLOW_CHECKS
, 0, true);
2696 kd_ctrl_page
.kdebug_flags
&= (unsigned int)~KDBG_CKTYPES
;
2698 if ((kd_ctrl_page
.kdebug_flags
& (KDBG_RANGECHECK
| KDBG_VALCHECK
|
2699 KDBG_PIDCHECK
| KDBG_PIDEXCLUDE
|
2700 KDBG_TYPEFILTER_CHECK
))) {
2701 kdbg_set_flags(SLOW_CHECKS
, 0, true);
2703 kdbg_set_flags(SLOW_CHECKS
, 0, false);
2717 kdbg_write_to_vnode(caddr_t buffer
, size_t size
, vnode_t vp
, vfs_context_t ctx
, off_t file_offset
)
2719 assert(size
< INT_MAX
);
2720 return vn_rdwr(UIO_WRITE
, vp
, buffer
, (int)size
, file_offset
, UIO_SYSSPACE
, IO_NODELOCKED
| IO_UNIT
,
2721 vfs_context_ucred(ctx
), (int *) 0, vfs_context_proc(ctx
));
2725 kdbg_write_v3_chunk_header(user_addr_t buffer
, uint32_t tag
, uint32_t sub_tag
, uint64_t length
, vnode_t vp
, vfs_context_t ctx
)
2727 int ret
= KERN_SUCCESS
;
2728 kd_chunk_header_v3 header
= {
2734 // Check that only one of them is valid
2735 assert(!buffer
^ !vp
);
2736 assert((vp
== NULL
) || (ctx
!= NULL
));
2738 // Write the 8-byte future_chunk_timestamp field in the payload
2741 ret
= kdbg_write_to_vnode((caddr_t
)&header
, sizeof(kd_chunk_header_v3
), vp
, ctx
, RAW_file_offset
);
2745 RAW_file_offset
+= (sizeof(kd_chunk_header_v3
));
2747 ret
= copyout(&header
, buffer
, sizeof(kd_chunk_header_v3
));
2758 kdbg_write_v3_chunk_to_fd(uint32_t tag
, uint32_t sub_tag
, uint64_t length
, void *payload
, uint64_t payload_size
, int fd
)
2761 struct vfs_context context
;
2762 struct fileproc
*fp
;
2766 if (fp_get_ftype(p
, fd
, DTYPE_VNODE
, EBADF
, &fp
)) {
2770 vp
= fp
->fp_glob
->fg_data
;
2771 context
.vc_thread
= current_thread();
2772 context
.vc_ucred
= fp
->fp_glob
->fg_cred
;
2774 if ((vnode_getwithref(vp
)) == 0) {
2775 RAW_file_offset
= fp
->fp_glob
->fg_offset
;
2777 kd_chunk_header_v3 chunk_header
= {
2783 int ret
= kdbg_write_to_vnode((caddr_t
) &chunk_header
, sizeof(kd_chunk_header_v3
), vp
, &context
, RAW_file_offset
);
2785 RAW_file_offset
+= sizeof(kd_chunk_header_v3
);
2788 ret
= kdbg_write_to_vnode((caddr_t
) payload
, (size_t) payload_size
, vp
, &context
, RAW_file_offset
);
2790 RAW_file_offset
+= payload_size
;
2793 fp
->fp_glob
->fg_offset
= RAW_file_offset
;
2797 fp_drop(p
, fd
, fp
, 0);
2798 return KERN_SUCCESS
;
2802 kdbg_write_v3_event_chunk_header(user_addr_t buffer
, uint32_t tag
, uint64_t length
, vnode_t vp
, vfs_context_t ctx
)
2804 uint64_t future_chunk_timestamp
= 0;
2805 length
+= sizeof(uint64_t);
2807 if (kdbg_write_v3_chunk_header(buffer
, tag
, V3_EVENT_DATA_VERSION
, length
, vp
, ctx
)) {
2811 buffer
+= sizeof(kd_chunk_header_v3
);
2814 // Check that only one of them is valid
2815 assert(!buffer
^ !vp
);
2816 assert((vp
== NULL
) || (ctx
!= NULL
));
2818 // Write the 8-byte future_chunk_timestamp field in the payload
2821 int ret
= kdbg_write_to_vnode((caddr_t
)&future_chunk_timestamp
, sizeof(uint64_t), vp
, ctx
, RAW_file_offset
);
2823 RAW_file_offset
+= (sizeof(uint64_t));
2826 if (copyout(&future_chunk_timestamp
, buffer
, sizeof(uint64_t))) {
2832 return buffer
+ sizeof(uint64_t);
2836 kdbg_write_v3_header(user_addr_t user_header
, size_t *user_header_size
, int fd
)
2838 int ret
= KERN_SUCCESS
;
2840 uint8_t* cpumap
= 0;
2841 uint32_t cpumap_size
= 0;
2842 uint32_t thrmap_size
= 0;
2844 size_t bytes_needed
= 0;
2846 // Check that only one of them is valid
2847 assert(!user_header
^ !fd
);
2848 assert(user_header_size
);
2850 if (!(kd_ctrl_page
.kdebug_flags
& KDBG_BUFINIT
)) {
2855 if (!(user_header
|| fd
)) {
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
) {
2866 // Check if a thread map is initialized
2871 if (os_mul_overflow(kd_mapcount
, sizeof(kd_threadmap
), &thrmap_size
)) {
2876 mach_timebase_info_data_t timebase
= {0, 0};
2877 clock_timebase_info(&timebase
);
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 */
2889 .walltime_usecs
= 0,
2890 .timezone_minuteswest
= 0,
2892 #if defined(__LP64__)
2899 // If its a buffer, check if we have enough space to copy the header and the maps.
2901 bytes_needed
= (size_t)header
.length
+ thrmap_size
+ (2 * sizeof(kd_chunk_header_v3
));
2902 if (*user_header_size
< bytes_needed
) {
2908 // Start writing the header
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
));
2913 ret
= kdbg_write_v3_chunk_to_fd(RAW_VERSION3
, V3_HEADER_VERSION
, header
.length
, hdr_ptr
, payload_size
, fd
);
2918 if (copyout(&header
, user_header
, sizeof(kd_header_v3
))) {
2922 // Update the user pointer
2923 user_header
+= sizeof(kd_header_v3
);
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
));
2930 ret
= kdbg_write_v3_chunk_to_fd(V3_CPU_MAP
, V3_CPUMAP_VERSION
, payload_size
, (void *)cpumap
, payload_size
, fd
);
2935 ret
= kdbg_write_v3_chunk_header(user_header
, V3_CPU_MAP
, V3_CPUMAP_VERSION
, payload_size
, NULL
, NULL
);
2939 user_header
+= sizeof(kd_chunk_header_v3
);
2940 if (copyout(cpumap
, user_header
, payload_size
)) {
2944 // Update the user pointer
2945 user_header
+= payload_size
;
2948 // Write a thread map
2950 ret
= kdbg_write_v3_chunk_to_fd(V3_THREAD_MAP
, V3_THRMAP_VERSION
, thrmap_size
, (void *)kd_mapptr
, thrmap_size
, fd
);
2955 ret
= kdbg_write_v3_chunk_header(user_header
, V3_THREAD_MAP
, V3_THRMAP_VERSION
, thrmap_size
, NULL
, NULL
);
2959 user_header
+= sizeof(kd_chunk_header_v3
);
2960 if (copyout(kd_mapptr
, user_header
, thrmap_size
)) {
2964 user_header
+= thrmap_size
;
2968 RAW_file_written
+= bytes_needed
;
2971 *user_header_size
= bytes_needed
;
2974 kmem_free(kernel_map
, (vm_offset_t
)cpumap
, cpumap_size
);
2980 kdbg_readcpumap(user_addr_t user_cpumap
, size_t *user_cpumap_size
)
2982 uint8_t* cpumap
= NULL
;
2983 uint32_t cpumap_size
= 0;
2984 int ret
= KERN_SUCCESS
;
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
) {
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
)) {
2994 *user_cpumap_size
= cpumap_size
;
2995 kmem_free(kernel_map
, (vm_offset_t
)cpumap
, cpumap_size
);
3007 kdbg_readcurthrmap(user_addr_t buffer
, size_t *bufsize
)
3009 kd_threadmap
*mapptr
;
3013 size_t count
= *bufsize
/ sizeof(kd_threadmap
);
3017 if ((mapptr
= kdbg_thrmap_init_internal(count
, &mapsize
, &mapcount
))) {
3018 if (copyout(mapptr
, buffer
, mapcount
* sizeof(kd_threadmap
))) {
3021 *bufsize
= (mapcount
* sizeof(kd_threadmap
));
3024 kfree(mapptr
, mapsize
);
3033 kdbg_write_v1_header(bool write_thread_map
, vnode_t vp
, vfs_context_t ctx
)
3041 uint32_t extra_thread_count
= 0;
3042 uint32_t cpumap_size
;
3043 size_t map_size
= 0;
3044 uint32_t map_count
= 0;
3046 if (write_thread_map
) {
3047 assert(kd_ctrl_page
.kdebug_flags
& KDBG_MAPINIT
);
3048 if (kd_mapcount
> UINT32_MAX
) {
3051 map_count
= (uint32_t)kd_mapcount
;
3052 if (os_mul_overflow(map_count
, sizeof(kd_threadmap
), &map_size
)) {
3055 if (map_size
>= INT_MAX
) {
3061 * Without the buffers initialized, we cannot construct a CPU map or a
3062 * thread map, and cannot write a header.
3064 if (!(kd_ctrl_page
.kdebug_flags
& KDBG_BUFINIT
)) {
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.
3078 pad_size
= PAGE_16KB
- ((sizeof(RAW_header
) + map_size
) & PAGE_MASK
);
3079 cpumap_size
= sizeof(kd_cpumap_header
) + kd_ctrl_page
.kdebug_cpus
* sizeof(kd_cpumap
);
3081 if (cpumap_size
> pad_size
) {
3082 /* If the cpu map doesn't fit in the current available pad_size,
3083 * we increase the pad_size by 16K. We do this so that the event
3084 * data is always available on a page aligned boundary for both
3085 * 4k and 16k systems. We enforce this alignment for the event
3086 * data so that we can take advantage of optimized file/disk writes.
3088 pad_size
+= PAGE_16KB
;
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
3097 if (pad_size
> PAGE_4KB
) {
3098 pad_size
-= PAGE_4KB
;
3099 extra_thread_count
= (pad_size
/ sizeof(kd_threadmap
)) + 1;
3102 memset(&header
, 0, sizeof(header
));
3103 header
.version_no
= RAW_VERSION1
;
3104 header
.thread_count
= map_count
+ extra_thread_count
;
3106 clock_get_calendar_microtime(&secs
, &usecs
);
3107 header
.TOD_secs
= secs
;
3108 header
.TOD_usecs
= usecs
;
3110 ret
= vn_rdwr(UIO_WRITE
, vp
, (caddr_t
)&header
, (int)sizeof(RAW_header
), RAW_file_offset
,
3111 UIO_SYSSPACE
, IO_NODELOCKED
| IO_UNIT
, vfs_context_ucred(ctx
), (int *) 0, vfs_context_proc(ctx
));
3115 RAW_file_offset
+= sizeof(RAW_header
);
3116 RAW_file_written
+= sizeof(RAW_header
);
3118 if (write_thread_map
) {
3119 assert(map_size
< INT_MAX
);
3120 ret
= vn_rdwr(UIO_WRITE
, vp
, (caddr_t
)kd_mapptr
, (int)map_size
, RAW_file_offset
,
3121 UIO_SYSSPACE
, IO_NODELOCKED
| IO_UNIT
, vfs_context_ucred(ctx
), (int *) 0, vfs_context_proc(ctx
));
3126 RAW_file_offset
+= map_size
;
3127 RAW_file_written
+= map_size
;
3130 if (extra_thread_count
) {
3131 pad_size
= extra_thread_count
* sizeof(kd_threadmap
);
3132 pad_buf
= kheap_alloc(KHEAP_TEMP
, pad_size
, Z_WAITOK
| Z_ZERO
);
3138 assert(pad_size
< INT_MAX
);
3139 ret
= vn_rdwr(UIO_WRITE
, vp
, (caddr_t
)pad_buf
, (int)pad_size
, RAW_file_offset
,
3140 UIO_SYSSPACE
, IO_NODELOCKED
| IO_UNIT
, vfs_context_ucred(ctx
), (int *) 0, vfs_context_proc(ctx
));
3141 kheap_free(KHEAP_TEMP
, pad_buf
, pad_size
);
3146 RAW_file_offset
+= pad_size
;
3147 RAW_file_written
+= pad_size
;
3150 pad_size
= PAGE_SIZE
- (RAW_file_offset
& PAGE_MASK
);
3152 pad_buf
= (char *)kheap_alloc(KHEAP_TEMP
, pad_size
, Z_WAITOK
| Z_ZERO
);
3159 * embed a cpumap in the padding bytes.
3160 * older code will skip this.
3161 * newer code will know how to read it.
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
);
3168 assert(pad_size
< INT_MAX
);
3169 ret
= vn_rdwr(UIO_WRITE
, vp
, (caddr_t
)pad_buf
, (int)pad_size
, RAW_file_offset
,
3170 UIO_SYSSPACE
, IO_NODELOCKED
| IO_UNIT
, vfs_context_ucred(ctx
), (int *) 0, vfs_context_proc(ctx
));
3171 kheap_free(KHEAP_TEMP
, pad_buf
, pad_size
);
3176 RAW_file_offset
+= pad_size
;
3177 RAW_file_written
+= pad_size
;
3185 kdbg_clear_thread_map(void)
3187 ktrace_assert_lock_held();
3189 if (kd_ctrl_page
.kdebug_flags
& KDBG_MAPINIT
) {
3190 assert(kd_mapptr
!= NULL
);
3191 kfree(kd_mapptr
, kd_mapsize
);
3195 kd_ctrl_page
.kdebug_flags
&= ~KDBG_MAPINIT
;
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.
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.
3208 kdbg_write_thread_map(vnode_t vp
, vfs_context_t ctx
)
3211 bool map_initialized
;
3213 ktrace_assert_lock_held();
3214 assert(ctx
!= NULL
);
3216 map_initialized
= (kd_ctrl_page
.kdebug_flags
& KDBG_MAPINIT
);
3218 ret
= kdbg_write_v1_header(map_initialized
, vp
, ctx
);
3220 if (map_initialized
) {
3221 kdbg_clear_thread_map();
3231 * Copy out the thread map to a user space buffer. Used by KDTHRMAP.
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.
3238 kdbg_copyout_thread_map(user_addr_t buffer
, size_t *buffer_size
)
3240 bool map_initialized
;
3244 ktrace_assert_lock_held();
3245 assert(buffer_size
!= NULL
);
3247 map_initialized
= (kd_ctrl_page
.kdebug_flags
& KDBG_MAPINIT
);
3248 if (!map_initialized
) {
3252 map_size
= kd_mapcount
* sizeof(kd_threadmap
);
3253 if (*buffer_size
< map_size
) {
3257 ret
= copyout(kd_mapptr
, buffer
, map_size
);
3259 kdbg_clear_thread_map();
3266 kdbg_readthrmap_v3(user_addr_t buffer
, size_t buffer_size
, int fd
)
3269 bool map_initialized
;
3272 ktrace_assert_lock_held();
3274 if ((!fd
&& !buffer
) || (fd
&& buffer
)) {
3278 map_initialized
= (kd_ctrl_page
.kdebug_flags
& KDBG_MAPINIT
);
3279 map_size
= kd_mapcount
* sizeof(kd_threadmap
);
3281 if (map_initialized
&& (buffer_size
>= map_size
)) {
3282 ret
= kdbg_write_v3_header(buffer
, &buffer_size
, fd
);
3285 kdbg_clear_thread_map();
3295 kdbg_set_nkdbufs(unsigned int req_nkdbufs
)
3298 * Only allow allocation up to half the available memory (sane_size).
3300 uint64_t max_nkdbufs
= (sane_size
/ 2) / sizeof(kd_buf
);
3301 nkdbufs
= (req_nkdbufs
> max_nkdbufs
) ? (unsigned int)max_nkdbufs
:
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.
3311 * Returns true if the threshold was reached and false otherwise.
3313 * Called with `ktrace_lock` locked and interrupts enabled.
3316 kdbg_wait(uint64_t timeout_ms
, bool locked_wait
)
3318 int wait_result
= THREAD_AWAKENED
;
3319 uint64_t abstime
= 0;
3321 ktrace_assert_lock_held();
3323 if (timeout_ms
!= 0) {
3324 uint64_t ns
= timeout_ms
* NSEC_PER_MSEC
;
3325 nanoseconds_to_absolutetime(ns
, &abstime
);
3326 clock_absolutetime_interval_to_deadline(abstime
, &abstime
);
3329 bool s
= ml_set_interrupts_enabled(false);
3331 panic("kdbg_wait() called with interrupts disabled");
3333 lck_spin_lock_grp(&kdw_spin_lock
, &kdebug_lck_grp
);
3336 /* drop the mutex to allow others to access trace */
3340 while (wait_result
== THREAD_AWAKENED
&&
3341 kd_ctrl_page
.kds_inuse_count
< n_storage_threshold
) {
3345 wait_result
= lck_spin_sleep_deadline(&kdw_spin_lock
, 0, &kds_waiter
, THREAD_ABORTSAFE
, abstime
);
3347 wait_result
= lck_spin_sleep(&kdw_spin_lock
, 0, &kds_waiter
, THREAD_ABORTSAFE
);
3353 /* check the count under the spinlock */
3354 bool threshold_exceeded
= (kd_ctrl_page
.kds_inuse_count
>= n_storage_threshold
);
3356 lck_spin_unlock(&kdw_spin_lock
);
3357 ml_set_interrupts_enabled(s
);
3360 /* pick the mutex back up again */
3364 /* write out whether we've exceeded the threshold */
3365 return threshold_exceeded
;
3369 * Wakeup a thread waiting using `kdbg_wait` if there are at least
3370 * `n_storage_threshold` storage units in use.
3375 bool need_kds_wakeup
= false;
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.
3385 bool s
= ml_set_interrupts_enabled(false);
3387 if (lck_spin_try_lock(&kdw_spin_lock
)) {
3389 (kd_ctrl_page
.kds_inuse_count
>= n_storage_threshold
)) {
3391 need_kds_wakeup
= true;
3393 lck_spin_unlock(&kdw_spin_lock
);
3396 ml_set_interrupts_enabled(s
);
3398 if (need_kds_wakeup
== true) {
3399 wakeup(&kds_waiter
);
3404 kdbg_control(int *name
, u_int namelen
, user_addr_t where
, size_t *sizep
)
3407 size_t size
= *sizep
;
3408 unsigned int value
= 0;
3410 kbufinfo_t kd_bufinfo
;
3413 if (name
[0] == KERN_KDWRITETR
||
3414 name
[0] == KERN_KDWRITETR_V3
||
3415 name
[0] == KERN_KDWRITEMAP
||
3416 name
[0] == KERN_KDWRITEMAP_V3
||
3417 name
[0] == KERN_KDEFLAGS
||
3418 name
[0] == KERN_KDDFLAGS
||
3419 name
[0] == KERN_KDENABLE
||
3420 name
[0] == KERN_KDSETBUF
) {
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
3434 if (name
[0] != KERN_KDGETBUF
&&
3435 name
[0] != KERN_KDGETREG
&&
3436 name
[0] != KERN_KDREADCURTHRMAP
) {
3437 if ((ret
= ktrace_configure(KTRACE_KDEBUG
))) {
3441 if ((ret
= ktrace_read_check())) {
3448 if (size
< sizeof(kd_bufinfo
.nkdbufs
)) {
3450 * There is not enough room to return even
3451 * the first element of the info structure.
3457 memset(&kd_bufinfo
, 0, sizeof(kd_bufinfo
));
3459 kd_bufinfo
.nkdbufs
= nkdbufs
;
3460 kd_bufinfo
.nkdthreads
= kd_mapcount
< INT_MAX
? (int)kd_mapcount
:
3462 if ((kd_ctrl_page
.kdebug_slowcheck
& SLOW_NOLOG
)) {
3463 kd_bufinfo
.nolog
= 1;
3465 kd_bufinfo
.nolog
= 0;
3468 kd_bufinfo
.flags
= kd_ctrl_page
.kdebug_flags
;
3469 #if defined(__LP64__)
3470 kd_bufinfo
.flags
|= KDBG_LP64
;
3473 int pid
= ktrace_get_owning_pid();
3474 kd_bufinfo
.bufid
= (pid
== 0 ? -1 : pid
);
3477 if (size
>= sizeof(kd_bufinfo
)) {
3479 * Provide all the info we have
3481 if (copyout(&kd_bufinfo
, where
, sizeof(kd_bufinfo
))) {
3486 * For backwards compatibility, only provide
3487 * as much info as there is room for.
3489 if (copyout(&kd_bufinfo
, where
, size
)) {
3495 case KERN_KDREADCURTHRMAP
:
3496 ret
= kdbg_readcurthrmap(where
, sizep
);
3500 value
&= KDBG_USERFLAGS
;
3501 kd_ctrl_page
.kdebug_flags
|= value
;
3505 value
&= KDBG_USERFLAGS
;
3506 kd_ctrl_page
.kdebug_flags
&= ~value
;
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.
3518 * enable only if buffer is initialized
3520 if (!(kd_ctrl_page
.kdebug_flags
& KDBG_BUFINIT
) ||
3521 !(value
== KDEBUG_ENABLE_TRACE
|| value
== KDEBUG_ENABLE_PPT
)) {
3527 kdbg_set_tracing_enabled(true, value
);
3529 if (!kdebug_enable
) {
3533 kernel_debug_disable();
3538 kdbg_set_nkdbufs(value
);
3542 ret
= kdbg_reinit(false);
3546 ktrace_reset(KTRACE_KDEBUG
);
3550 if (size
< sizeof(kd_regtype
)) {
3554 if (copyin(where
, &kd_Reg
, sizeof(kd_regtype
))) {
3559 ret
= kdbg_setreg(&kd_Reg
);
3567 ret
= kdbg_read(where
, sizep
, NULL
, NULL
, RAW_VERSION1
);
3570 case KERN_KDWRITETR
:
3571 case KERN_KDWRITETR_V3
:
3572 case KERN_KDWRITEMAP
:
3573 case KERN_KDWRITEMAP_V3
:
3575 struct vfs_context context
;
3576 struct fileproc
*fp
;
3581 if (name
[0] == KERN_KDWRITETR
|| name
[0] == KERN_KDWRITETR_V3
) {
3582 (void)kdbg_wait(size
, true);
3588 if (fp_get_ftype(p
, fd
, DTYPE_VNODE
, EBADF
, &fp
)) {
3593 vp
= fp
->fp_glob
->fg_data
;
3594 context
.vc_thread
= current_thread();
3595 context
.vc_ucred
= fp
->fp_glob
->fg_cred
;
3597 if ((ret
= vnode_getwithref(vp
)) == 0) {
3598 RAW_file_offset
= fp
->fp_glob
->fg_offset
;
3599 if (name
[0] == KERN_KDWRITETR
|| name
[0] == KERN_KDWRITETR_V3
) {
3600 number
= nkdbufs
* sizeof(kd_buf
);
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
);
3606 ret
= kdbg_read(0, &number
, vp
, &context
, RAW_VERSION1
);
3608 KDBG_RELEASE(TRACE_WRITING_EVENTS
| DBG_FUNC_END
, number
);
3612 number
= kd_mapcount
* sizeof(kd_threadmap
);
3613 if (name
[0] == KERN_KDWRITEMAP_V3
) {
3614 ret
= kdbg_readthrmap_v3(0, number
, fd
);
3616 ret
= kdbg_write_thread_map(vp
, &context
);
3619 fp
->fp_glob
->fg_offset
= RAW_file_offset
;
3622 fp_drop(p
, fd
, fp
, 0);
3626 case KERN_KDBUFWAIT
:
3627 *sizep
= kdbg_wait(size
, false);
3631 if (size
< sizeof(kd_regtype
)) {
3635 if (copyin(where
, &kd_Reg
, sizeof(kd_regtype
))) {
3640 ret
= kdbg_setpid(&kd_Reg
);
3644 if (size
< sizeof(kd_regtype
)) {
3648 if (copyin(where
, &kd_Reg
, sizeof(kd_regtype
))) {
3653 ret
= kdbg_setpidex(&kd_Reg
);
3657 ret
= kdbg_readcpumap(where
, sizep
);
3661 ret
= kdbg_copyout_thread_map(where
, sizep
);
3664 case KERN_KDSET_TYPEFILTER
: {
3665 ret
= kdbg_copyin_typefilter(where
, size
);
3670 ret
= kdbg_test(size
);
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
3691 kdbg_read(user_addr_t buffer
, size_t *number
, vnode_t vp
, vfs_context_t ctx
, uint32_t file_version
)
3694 unsigned int cpu
, min_cpu
;
3695 uint64_t barrier_min
= 0, barrier_max
= 0, t
, earliest_time
;
3701 bool traced_retrograde
= false;
3702 struct kd_storage
*kdsp_actual
;
3703 struct kd_bufinfo
*kdbp
;
3704 struct kd_bufinfo
*min_kdbp
;
3705 size_t tempbuf_count
;
3706 uint32_t tempbuf_number
;
3707 uint32_t old_kdebug_flags
;
3708 uint32_t old_kdebug_slowcheck
;
3709 bool out_of_events
= false;
3710 bool wrapped
= false;
3712 assert(number
!= NULL
);
3713 count
= *number
/ sizeof(kd_buf
);
3716 ktrace_assert_lock_held();
3718 if (count
== 0 || !(kd_ctrl_page
.kdebug_flags
& KDBG_BUFINIT
) || kdcopybuf
== 0) {
3722 thread_set_eager_preempt(current_thread());
3724 memset(&lostevent
, 0, sizeof(lostevent
));
3725 lostevent
.debugid
= TRACE_LOST_EVENTS
;
3728 * Request each IOP to provide us with up to date entries before merging
3731 kdbg_iop_list_callback(kd_ctrl_page
.kdebug_iops
, KD_CALLBACK_SYNC_FLUSH
, NULL
);
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.
3738 barrier_max
= kdbg_timestamp() & KDBG_TIMESTAMP_MASK
;
3741 * Disable wrap so storage units cannot be stolen out from underneath us
3742 * while merging events.
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.
3750 wrapped
= disable_wrap(&old_kdebug_slowcheck
, &old_kdebug_flags
);
3752 if (count
> nkdbufs
) {
3756 if ((tempbuf_count
= count
) > KDCOPYBUF_COUNT
) {
3757 tempbuf_count
= KDCOPYBUF_COUNT
;
3761 * If the buffers have wrapped, do not emit additional lost events for the
3762 * oldest storage units.
3765 kd_ctrl_page
.kdebug_flags
&= ~KDBG_WRAPPED
;
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
) {
3771 kdsp_actual
= POINTER_FROM_KDS_PTR(kdsp
);
3772 kdsp_actual
->kds_lostevents
= false;
3776 * Capture the earliest time where there are events for all CPUs and don't
3777 * emit events with timestamps prior.
3779 barrier_min
= kd_ctrl_page
.oldest_time
;
3782 tempbuf
= kdcopybuf
;
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
3792 kdbg_set_timestamp_and_cpu(&lostevent
, barrier_min
, 0);
3793 *tempbuf
= lostevent
;
3798 /* While space left in merged events scratch buffer. */
3799 while (tempbuf_count
) {
3800 bool lostevents
= false;
3802 earliest_time
= UINT64_MAX
;
3806 /* Check each CPU's buffers for the earliest event. */
3807 for (cpu
= 0, kdbp
= &kdbip
[0]; cpu
< kd_ctrl_page
.kdebug_cpus
; cpu
++, kdbp
++) {
3808 /* Skip CPUs without data in their oldest storage unit. */
3809 if ((kdsp
= kdbp
->kd_list_head
).raw
== KDS_PTR_NULL
) {
3813 /* From CPU data to buffer header to buffer. */
3814 kdsp_actual
= POINTER_FROM_KDS_PTR(kdsp
);
3817 /* The next event to be read from this buffer. */
3818 rcursor
= kdsp_actual
->kds_readlast
;
3820 /* Skip this buffer if there are no events left. */
3821 if (rcursor
== kdsp_actual
->kds_bufindx
) {
3826 * Check that this storage unit wasn't stolen and events were
3827 * lost. This must have happened while wrapping was disabled
3830 if (kdsp_actual
->kds_lostevents
) {
3832 kdsp_actual
->kds_lostevents
= false;
3835 * The earliest event we can trust is the first one in this
3836 * stolen storage unit.
3838 uint64_t lost_time
=
3839 kdbg_get_timestamp(&kdsp_actual
->kds_records
[0]);
3840 if (kd_ctrl_page
.oldest_time
< lost_time
) {
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
3847 kd_ctrl_page
.oldest_time
= barrier_min
= lost_time
;
3852 t
= kdbg_get_timestamp(&kdsp_actual
->kds_records
[rcursor
]);
3854 if (t
> barrier_max
) {
3856 printf("kdebug: FUTURE EVENT: debugid %#8x: "
3857 "time %lld from CPU %u "
3858 "(barrier at time %lld, read %lu events)\n",
3859 kdsp_actual
->kds_records
[rcursor
].debugid
,
3860 t
, cpu
, barrier_max
, *number
+ tempbuf_number
);
3864 if (t
< kdsp_actual
->kds_timestamp
) {
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.
3872 * Bail out so we don't get out-of-order events by
3873 * continuing to read events from other CPUs' events.
3875 out_of_events
= true;
3880 * Ignore events that have aged out due to wrapping or storage
3881 * unit exhaustion while merging events.
3883 if (t
< barrier_min
) {
3884 kdsp_actual
->kds_readlast
++;
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
);
3893 if (kdsp_actual
->kds_readlast
>= EVENTS_PER_STORAGE_UNIT
) {
3894 release_storage_unit(cpu
, kdsp
.raw
);
3896 if ((kdsp
= kdbp
->kd_list_head
).raw
== KDS_PTR_NULL
) {
3899 kdsp_actual
= POINTER_FROM_KDS_PTR(kdsp
);
3906 * Don't worry about merging any events -- just walk through
3907 * the CPUs and find the latest timestamp of lost events.
3913 if (t
< earliest_time
) {
3921 * If any lost events were hit in the buffers, emit an event
3922 * with the latest timestamp.
3924 kdbg_set_timestamp_and_cpu(&lostevent
, barrier_min
, lostcpu
);
3925 *tempbuf
= lostevent
;
3929 if (min_kdbp
== NULL
) {
3930 /* All buffers ran empty. */
3931 out_of_events
= true;
3933 if (out_of_events
) {
3937 kdsp
= min_kdbp
->kd_list_head
;
3938 kdsp_actual
= POINTER_FROM_KDS_PTR(kdsp
);
3940 /* Copy earliest event into merged events scratch buffer. */
3941 *tempbuf
= kdsp_actual
->kds_records
[kdsp_actual
->kds_readlast
++];
3943 if (kdsp_actual
->kds_readlast
== EVENTS_PER_STORAGE_UNIT
) {
3944 release_storage_unit(min_cpu
, kdsp
.raw
);
3948 * Watch for out of order timestamps (from IOPs).
3950 if (earliest_time
< min_kdbp
->kd_prev_timebase
) {
3952 * If we haven't already, emit a retrograde events event.
3953 * Otherwise, ignore this event.
3955 if (traced_retrograde
) {
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
);
3966 kdbg_set_timestamp_and_cpu(tempbuf
, min_kdbp
->kd_prev_timebase
, kdbg_get_cpu(tempbuf
));
3967 tempbuf
->arg1
= tempbuf
->debugid
;
3968 tempbuf
->arg2
= (kd_buf_argtype
)earliest_time
;
3971 tempbuf
->debugid
= TRACE_RETROGRADE_EVENTS
;
3972 traced_retrograde
= true;
3974 min_kdbp
->kd_prev_timebase
= earliest_time
;
3981 if ((RAW_file_written
+= sizeof(kd_buf
)) >= RAW_FLUSH_SIZE
) {
3985 if (tempbuf_number
) {
3987 * Remember the latest timestamp of events that we've merged so we
3988 * don't think we've lost events later.
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
;
3994 if (file_version
== RAW_VERSION3
) {
3995 if (!(kdbg_write_v3_event_chunk_header(buffer
, V3_RAW_EVENTS
, (tempbuf_number
* sizeof(kd_buf
)), vp
, ctx
))) {
4000 buffer
+= (sizeof(kd_chunk_header_v3
) + sizeof(uint64_t));
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));
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
);
4011 RAW_file_offset
+= write_size
;
4014 if (RAW_file_written
>= RAW_FLUSH_SIZE
) {
4015 error
= VNOP_FSYNC(vp
, MNT_NOWAIT
, ctx
);
4017 RAW_file_written
= 0;
4020 error
= copyout(kdcopybuf
, buffer
, tempbuf_number
* sizeof(kd_buf
));
4021 buffer
+= (tempbuf_number
* sizeof(kd_buf
));
4029 count
-= tempbuf_number
;
4030 *number
+= tempbuf_number
;
4032 if (out_of_events
== true) {
4034 * all trace buffers are empty
4039 if ((tempbuf_count
= count
) > KDCOPYBUF_COUNT
) {
4040 tempbuf_count
= KDCOPYBUF_COUNT
;
4043 if (!(old_kdebug_flags
& KDBG_NOWRAP
)) {
4044 enable_wrap(old_kdebug_slowcheck
);
4046 thread_clear_eager_preempt(current_thread());
4050 #define KDEBUG_TEST_CODE(code) BSDDBG_CODE(DBG_BSD_KDEBUG_TEST, (code))
4053 * A test IOP for the SYNC_FLUSH callback.
4056 static int sync_flush_iop
= 0;
4059 sync_flush_callback(void * __unused context
, kd_callback_type reason
,
4060 void * __unused arg
)
4062 assert(sync_flush_iop
> 0);
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);
4070 static struct kd_callback sync_flush_kdcb
= {
4071 .func
= sync_flush_callback
,
4072 .iop_name
= "test_sf",
4076 kdbg_test(size_t flavor
)
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
++;
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
++;
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
++;
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
++;
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
++;
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
;
4121 /* ensure old timestamps are not emitted from kernel_debug_enter */
4122 kernel_debug_enter(dummy_iop
, KDEBUG_TEST_CODE(code
),
4123 100 /* very old timestamp */, 0, 0, 0, 0, 0);
4125 kernel_debug_enter(dummy_iop
, KDEBUG_TEST_CODE(code
),
4126 kdbg_timestamp(), 0, 0, 0, 0, 0);
4131 if (kd_ctrl_page
.kdebug_iops
) {
4132 dummy_iop
= kd_ctrl_page
.kdebug_iops
[0].cpu_id
;
4134 kernel_debug_enter(dummy_iop
, KDEBUG_TEST_CODE(code
),
4135 kdbg_timestamp() * 2 /* !!! */, 0, 0, 0, 0, 0);
4139 if (!sync_flush_iop
) {
4140 sync_flush_iop
= kernel_debug_register_callback(
4142 assert(sync_flush_iop
> 0);
4153 #undef KDEBUG_TEST_CODE
4156 kdebug_init(unsigned int n_events
, char *filter_desc
, enum kdebug_opts opts
)
4158 assert(filter_desc
!= NULL
);
4160 if (log_leaks
&& n_events
== 0) {
4164 kdebug_trace_start(n_events
, filter_desc
, opts
);
4168 kdbg_set_typefilter_string(const char *filter_desc
)
4172 ktrace_assert_lock_held();
4174 assert(filter_desc
!= NULL
);
4176 typefilter_reject_all(kdbg_typefilter
);
4177 typefilter_allow_class(kdbg_typefilter
, DBG_TRACE
);
4179 /* if the filter description starts with a number, assume it's a csc */
4180 if (filter_desc
[0] >= '0' && filter_desc
[0] <= '9') {
4181 unsigned long csc
= strtoul(filter_desc
, NULL
, 0);
4182 if (filter_desc
!= end
&& csc
<= KDBG_CSC_MAX
) {
4183 typefilter_allow_csc(kdbg_typefilter
, (uint16_t)csc
);
4188 while (filter_desc
[0] != '\0') {
4189 unsigned long allow_value
;
4191 char filter_type
= filter_desc
[0];
4192 if (filter_type
!= 'C' && filter_type
!= 'S') {
4193 printf("kdebug: unexpected filter type `%c'\n", filter_type
);
4198 allow_value
= strtoul(filter_desc
, &end
, 0);
4199 if (filter_desc
== end
) {
4200 printf("kdebug: cannot parse `%s' as integer\n", filter_desc
);
4204 switch (filter_type
) {
4206 if (allow_value
> KDBG_CLASS_MAX
) {
4207 printf("kdebug: class 0x%lx is invalid\n", allow_value
);
4210 printf("kdebug: C 0x%lx\n", allow_value
);
4211 typefilter_allow_class(kdbg_typefilter
, (uint8_t)allow_value
);
4214 if (allow_value
> KDBG_CSC_MAX
) {
4215 printf("kdebug: class-subclass 0x%lx is invalid\n", allow_value
);
4218 printf("kdebug: S 0x%lx\n", allow_value
);
4219 typefilter_allow_csc(kdbg_typefilter
, (uint16_t)allow_value
);
4222 __builtin_unreachable();
4225 /* advance to next filter entry */
4227 if (filter_desc
[0] == ',') {
4236 if (!wake_nkdbufs
) {
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
;
4245 * This function is meant to be called from the bootstrap thread or kdebug_wake.
4248 kdebug_trace_start(unsigned int n_events
, const char *filter_desc
,
4249 enum kdebug_opts opts
)
4252 kd_early_done
= true;
4256 ktrace_start_single_threaded();
4258 ktrace_kernel_configure(KTRACE_KDEBUG
);
4260 kdbg_set_nkdbufs(n_events
);
4262 kernel_debug_string_early("start_kern_tracing");
4264 if (kdbg_reinit((opts
& KDOPT_ATBOOT
))) {
4265 printf("error from kdbg_reinit, kernel tracing not started\n");
4270 * Wrapping is disabled because boot and wake tracing is interested in
4271 * the earliest events, at the expense of later ones.
4273 if (!(opts
& KDOPT_WRAPPING
)) {
4274 uint32_t old1
, old2
;
4275 (void)disable_wrap(&old1
, &old2
);
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();
4286 * Hold off interrupts between getting a thread map and enabling trace
4287 * and until the early traces are recorded.
4289 bool s
= ml_set_interrupts_enabled(false);
4291 if (!(opts
& KDOPT_ATBOOT
)) {
4295 kdbg_set_tracing_enabled(true, KDEBUG_ENABLE_TRACE
);
4297 if ((opts
& KDOPT_ATBOOT
)) {
4299 * Transfer all very early events from the static buffer into the real
4302 kernel_debug_early_end();
4305 ml_set_interrupts_enabled(s
);
4307 printf("kernel tracing started with %u events, filter = %s\n", n_events
,
4308 filter_desc
?: "none");
4311 ktrace_end_single_threaded();
4315 kdbg_dump_trace_to_file(const char *filename
)
4324 if (!(kdebug_enable
& KDEBUG_ENABLE_TRACE
)) {
4328 if (ktrace_get_owning_pid() != 0) {
4330 * Another process owns ktrace and is still active, disable tracing to
4334 kd_ctrl_page
.enabled
= 0;
4335 commpage_update_kdebug_state();
4339 KDBG_RELEASE(TRACE_WRITING_EVENTS
| DBG_FUNC_START
);
4342 kd_ctrl_page
.enabled
= 0;
4343 commpage_update_kdebug_state();
4345 ctx
= vfs_context_kernel();
4347 if (vnode_open(filename
, (O_CREAT
| FWRITE
| O_NOFOLLOW
), 0600, 0, &vp
, ctx
)) {
4351 kdbg_write_thread_map(vp
, ctx
);
4353 write_size
= nkdbufs
* sizeof(kd_buf
);
4354 ret
= kdbg_read(0, &write_size
, vp
, ctx
, RAW_VERSION1
);
4360 * Wait to synchronize the file to capture the I/O in the
4361 * TRACE_WRITING_EVENTS interval.
4363 ret
= VNOP_FSYNC(vp
, MNT_WAIT
, ctx
);
4366 * Balance the starting TRACE_WRITING_EVENTS tracepoint manually.
4368 kd_buf end_event
= {
4369 .debugid
= TRACE_WRITING_EVENTS
| DBG_FUNC_END
,
4372 .arg5
= (kd_buf_argtype
)thread_tid(current_thread()),
4374 kdbg_set_timestamp_and_cpu(&end_event
, kdbg_timestamp(),
4377 /* this is best effort -- ignore any errors */
4378 (void)kdbg_write_to_vnode((caddr_t
)&end_event
, sizeof(kd_buf
), vp
, ctx
,
4382 vnode_close(vp
, FWRITE
, ctx
);
4383 sync(current_proc(), (void *)NULL
, (int *)NULL
);
4390 kdbg_sysctl_continuous SYSCTL_HANDLER_ARGS
4392 #pragma unused(oidp, arg1, arg2)
4393 int value
= kdbg_continuous_time
;
4394 int ret
= sysctl_io_number(req
, value
, sizeof(value
), &value
, NULL
);
4396 if (ret
|| !req
->newptr
) {
4400 kdbg_continuous_time
= value
;
4404 SYSCTL_NODE(_kern
, OID_AUTO
, kdbg
, CTLFLAG_RD
| CTLFLAG_LOCKED
, 0,
4407 SYSCTL_PROC(_kern_kdbg
, OID_AUTO
, experimental_continuous
,
4408 CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
, 0,
4409 sizeof(int), kdbg_sysctl_continuous
, "I",
4410 "Set kdebug to use mach_continuous_time");
4412 SYSCTL_INT(_kern_kdbg
, OID_AUTO
, debug
,
4413 CTLFLAG_RW
| CTLFLAG_LOCKED
,
4414 &kdbg_debug
, 0, "Set kdebug debug mode");
4416 SYSCTL_QUAD(_kern_kdbg
, OID_AUTO
, oldest_time
,
4417 CTLTYPE_QUAD
| CTLFLAG_RD
| CTLFLAG_LOCKED
,
4418 &kd_ctrl_page
.oldest_time
,
4419 "Find the oldest timestamp still in trace");