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_data.h>
60 #include <kern/assert.h>
61 #include <kern/telemetry.h>
62 #include <kern/sched_prim.h>
63 #include <vm/vm_kern.h>
65 #include <kperf/kperf.h>
66 #include <pexpert/device_tree.h>
68 #include <sys/malloc.h>
69 #include <sys/mcache.h>
71 #include <sys/vnode.h>
72 #include <sys/vnode_internal.h>
73 #include <sys/fcntl.h>
74 #include <sys/file_internal.h>
76 #include <sys/param.h> /* for isset() */
78 #include <mach/mach_host.h> /* for host_info() */
79 #include <libkern/OSAtomic.h>
81 #include <machine/pal_routines.h>
82 #include <machine/atomic.h>
87 * https://coreoswiki.apple.com/wiki/pages/U6z3i0q9/Consistent_Logging_Implementers_Guide.html
89 * IOP(s) are auxiliary cores that want to participate in kdebug event logging.
90 * They are registered dynamically. Each is assigned a cpu_id at registration.
92 * NOTE: IOP trace events may not use the same clock hardware as "normal"
93 * cpus. There is an effort made to synchronize the IOP timebase with the
94 * AP, but it should be understood that there may be discrepancies.
96 * Once registered, an IOP is permanent, it cannot be unloaded/unregistered.
97 * The current implementation depends on this for thread safety.
99 * New registrations occur by allocating an kd_iop struct and assigning
100 * a provisional cpu_id of list_head->cpu_id + 1. Then a CAS to claim the
101 * list_head pointer resolves any races.
103 * You may safely walk the kd_iops list at any time, without holding locks.
105 * When allocating buffers, the current kd_iops head is captured. Any operations
106 * that depend on the buffer state (such as flushing IOP traces on reads,
107 * etc.) should use the captured list head. This will allow registrations to
108 * take place while trace is in use.
111 typedef struct kd_iop
{
112 kd_callback_t callback
;
114 uint64_t last_timestamp
; /* Prevent timer rollback */
118 static kd_iop_t
* kd_iops
= NULL
;
123 * A typefilter is a 8KB bitmap that is used to selectively filter events
124 * being recorded. It is able to individually address every class & subclass.
126 * There is a shared typefilter in the kernel which is lazily allocated. Once
127 * allocated, the shared typefilter is never deallocated. The shared typefilter
128 * is also mapped on demand into userspace processes that invoke kdebug_trace
129 * API from Libsyscall. When mapped into a userspace process, the memory is
130 * read only, and does not have a fixed address.
132 * It is a requirement that the kernel's shared typefilter always pass DBG_TRACE
133 * events. This is enforced automatically, by having the needed bits set any
134 * time the shared typefilter is mutated.
137 typedef uint8_t* typefilter_t
;
139 static typefilter_t kdbg_typefilter
;
140 static mach_port_t kdbg_typefilter_memory_entry
;
143 * There are 3 combinations of page sizes:
149 * The typefilter is exactly 8KB. In the first two scenarios, we would like
150 * to use 2 pages exactly; in the third scenario we must make certain that
151 * a full page is allocated so we do not inadvertantly share 8KB of random
152 * data to userspace. The round_page_32 macro rounds to kernel page size.
154 #define TYPEFILTER_ALLOC_SIZE MAX(round_page_32(KDBG_TYPEFILTER_BITMAP_SIZE), KDBG_TYPEFILTER_BITMAP_SIZE)
157 typefilter_create(void)
160 if (KERN_SUCCESS
== kmem_alloc(kernel_map
, (vm_offset_t
*)&tf
, TYPEFILTER_ALLOC_SIZE
, VM_KERN_MEMORY_DIAG
)) {
161 memset(&tf
[KDBG_TYPEFILTER_BITMAP_SIZE
], 0, TYPEFILTER_ALLOC_SIZE
- KDBG_TYPEFILTER_BITMAP_SIZE
);
168 typefilter_deallocate(typefilter_t tf
)
171 assert(tf
!= kdbg_typefilter
);
172 kmem_free(kernel_map
, (vm_offset_t
)tf
, TYPEFILTER_ALLOC_SIZE
);
176 typefilter_copy(typefilter_t dst
, typefilter_t src
)
180 memcpy(dst
, src
, KDBG_TYPEFILTER_BITMAP_SIZE
);
184 typefilter_reject_all(typefilter_t tf
)
187 memset(tf
, 0, KDBG_TYPEFILTER_BITMAP_SIZE
);
191 typefilter_allow_all(typefilter_t tf
)
194 memset(tf
, ~0, KDBG_TYPEFILTER_BITMAP_SIZE
);
198 typefilter_allow_class(typefilter_t tf
, uint8_t class)
201 const uint32_t BYTES_PER_CLASS
= 256 / 8; // 256 subclasses, 1 bit each
202 memset(&tf
[class * BYTES_PER_CLASS
], 0xFF, BYTES_PER_CLASS
);
206 typefilter_allow_csc(typefilter_t tf
, uint16_t csc
)
213 typefilter_is_debugid_allowed(typefilter_t tf
, uint32_t id
)
216 return isset(tf
, KDBG_EXTRACT_CSC(id
));
220 typefilter_create_memory_entry(typefilter_t tf
)
224 mach_port_t memory_entry
= MACH_PORT_NULL
;
225 memory_object_size_t size
= TYPEFILTER_ALLOC_SIZE
;
227 mach_make_memory_entry_64(kernel_map
,
229 (memory_object_offset_t
)tf
,
237 static int kdbg_copyin_typefilter(user_addr_t addr
, size_t size
);
238 static void kdbg_enable_typefilter(void);
239 static void kdbg_disable_typefilter(void);
242 * External prototypes
245 void task_act_iterate_wth_args(task_t
, void (*)(thread_t
, void *), void *);
246 int cpu_number(void); /* XXX <machine/...> include path broken */
247 void commpage_update_kdebug_state(void); /* XXX sign */
249 extern int log_leaks
;
252 * This flag is for testing purposes only -- it's highly experimental and tools
253 * have not been updated to support it.
255 static bool kdbg_continuous_time
= false;
257 static inline uint64_t
260 if (kdbg_continuous_time
) {
261 return mach_continuous_time();
263 return mach_absolute_time();
267 static int kdbg_debug
= 0;
269 #if KDEBUG_MOJO_TRACE
270 #include <sys/kdebugevents.h>
271 static void kdebug_serial_print( /* forward */
272 uint32_t, uint32_t, uint64_t,
273 uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t);
276 int kdbg_control(int *, u_int
, user_addr_t
, size_t *);
278 static int kdbg_read(user_addr_t
, size_t *, vnode_t
, vfs_context_t
, uint32_t);
279 static int kdbg_readcpumap(user_addr_t
, size_t *);
280 static int kdbg_readthrmap_v3(user_addr_t
, size_t, int);
281 static int kdbg_readcurthrmap(user_addr_t
, size_t *);
282 static int kdbg_setreg(kd_regtype
*);
283 static int kdbg_setpidex(kd_regtype
*);
284 static int kdbg_setpid(kd_regtype
*);
285 static void kdbg_thrmap_init(void);
286 static int kdbg_reinit(bool);
287 static int kdbg_bootstrap(bool);
288 static int kdbg_test(size_t flavor
);
290 static int kdbg_write_v1_header(bool write_thread_map
, vnode_t vp
, vfs_context_t ctx
);
291 static int kdbg_write_thread_map(vnode_t vp
, vfs_context_t ctx
);
292 static int kdbg_copyout_thread_map(user_addr_t buffer
, size_t *buffer_size
);
293 static void kdbg_clear_thread_map(void);
295 static bool kdbg_wait(uint64_t timeout_ms
, bool locked_wait
);
296 static void kdbg_wakeup(void);
298 int kdbg_cpumap_init_internal(kd_iop_t
* iops
, uint32_t cpu_count
,
299 uint8_t** cpumap
, uint32_t* cpumap_size
);
301 static kd_threadmap
*kdbg_thrmap_init_internal(unsigned int count
,
302 unsigned int *mapsize
,
303 unsigned int *mapcount
);
305 static bool kdebug_current_proc_enabled(uint32_t debugid
);
306 static errno_t
kdebug_check_trace_string(uint32_t debugid
, uint64_t str_id
);
308 int kdbg_write_v3_header(user_addr_t
, size_t *, int);
309 int kdbg_write_v3_chunk_header(user_addr_t buffer
, uint32_t tag
,
310 uint32_t sub_tag
, uint64_t length
,
311 vnode_t vp
, vfs_context_t ctx
);
313 user_addr_t
kdbg_write_v3_event_chunk_header(user_addr_t buffer
, uint32_t tag
,
314 uint64_t length
, vnode_t vp
,
319 static int create_buffers(bool);
320 static void delete_buffers(void);
322 extern int tasks_count
;
323 extern int threads_count
;
324 extern void IOSleep(int);
326 /* trace enable status */
327 unsigned int kdebug_enable
= 0;
329 /* A static buffer to record events prior to the start of regular logging */
331 #define KD_EARLY_BUFFER_SIZE (16 * 1024)
332 #define KD_EARLY_BUFFER_NBUFS (KD_EARLY_BUFFER_SIZE / sizeof(kd_buf))
335 * On embedded, the space for this is carved out by osfmk/arm/data.s -- clang
336 * has problems aligning to greater than 4K.
338 extern kd_buf kd_early_buffer
[KD_EARLY_BUFFER_NBUFS
];
339 #else /* CONFIG_EMBEDDED */
340 __attribute__((aligned(KD_EARLY_BUFFER_SIZE
)))
341 static kd_buf kd_early_buffer
[KD_EARLY_BUFFER_NBUFS
];
342 #endif /* !CONFIG_EMBEDDED */
344 static unsigned int kd_early_index
= 0;
345 static bool kd_early_overflow
= false;
346 static bool kd_early_done
= false;
348 #define SLOW_NOLOG 0x01
349 #define SLOW_CHECKS 0x02
351 #define EVENTS_PER_STORAGE_UNIT 2048
352 #define MIN_STORAGE_UNITS_PER_CPU 4
354 #define POINTER_FROM_KDS_PTR(x) (&kd_bufs[x.buffer_index].kdsb_addr[x.offset])
358 uint32_t buffer_index
:21;
365 union kds_ptr kds_next
;
366 uint32_t kds_bufindx
;
368 uint32_t kds_readlast
;
370 uint64_t kds_timestamp
;
372 kd_buf kds_records
[EVENTS_PER_STORAGE_UNIT
];
375 #define MAX_BUFFER_SIZE (1024 * 1024 * 128)
376 #define N_STORAGE_UNITS_PER_BUFFER (MAX_BUFFER_SIZE / sizeof(struct kd_storage))
377 static_assert(N_STORAGE_UNITS_PER_BUFFER
<= 0x7ff,
378 "shoudn't overflow kds_ptr.offset");
380 struct kd_storage_buffers
{
381 struct kd_storage
*kdsb_addr
;
385 #define KDS_PTR_NULL 0xffffffff
386 struct kd_storage_buffers
*kd_bufs
= NULL
;
387 int n_storage_units
= 0;
388 unsigned int n_storage_buffers
= 0;
389 int n_storage_threshold
= 0;
394 union kds_ptr kd_list_head
;
395 union kds_ptr kd_list_tail
;
398 uint64_t kd_prev_timebase
;
400 } __attribute__((aligned(MAX_CPU_CACHE_LINE_SIZE
)));
404 * In principle, this control block can be shared in DRAM with other
405 * coprocessors and runtimes, for configuring what tracing is enabled.
407 struct kd_ctrl_page_t
{
408 union kds_ptr kds_free_list
;
412 uint32_t kdebug_flags
;
413 uint32_t kdebug_slowcheck
;
414 uint64_t oldest_time
;
416 * The number of kd_bufinfo structs allocated may not match the current
417 * number of active cpus. We capture the iops list head at initialization
418 * which we could use to calculate the number of cpus we allocated data for,
419 * unless it happens to be null. To avoid that case, we explicitly also
420 * capture a cpu count.
422 kd_iop_t
* kdebug_iops
;
423 uint32_t kdebug_cpus
;
425 .kds_free_list
= {.raw
= KDS_PTR_NULL
},
426 .kdebug_slowcheck
= SLOW_NOLOG
,
432 struct kd_bufinfo
*kdbip
= NULL
;
434 #define KDCOPYBUF_COUNT 8192
435 #define KDCOPYBUF_SIZE (KDCOPYBUF_COUNT * sizeof(kd_buf))
437 #define PAGE_4KB 4096
438 #define PAGE_16KB 16384
440 kd_buf
*kdcopybuf
= NULL
;
442 unsigned int nkdbufs
= 0;
443 unsigned int kdlog_beg
= 0;
444 unsigned int kdlog_end
= 0;
445 unsigned int kdlog_value1
= 0;
446 unsigned int kdlog_value2
= 0;
447 unsigned int kdlog_value3
= 0;
448 unsigned int kdlog_value4
= 0;
450 static lck_spin_t
* kdw_spin_lock
;
451 static lck_spin_t
* kds_spin_lock
;
453 kd_threadmap
*kd_mapptr
= 0;
454 unsigned int kd_mapsize
= 0;
455 unsigned int kd_mapcount
= 0;
457 off_t RAW_file_offset
= 0;
458 int RAW_file_written
= 0;
460 #define RAW_FLUSH_SIZE (2 * 1024 * 1024)
463 * A globally increasing counter for identifying strings in trace. Starts at
464 * 1 because 0 is a reserved return value.
466 __attribute__((aligned(MAX_CPU_CACHE_LINE_SIZE
)))
467 static uint64_t g_curr_str_id
= 1;
469 #define STR_ID_SIG_OFFSET (48)
470 #define STR_ID_MASK ((1ULL << STR_ID_SIG_OFFSET) - 1)
471 #define STR_ID_SIG_MASK (~STR_ID_MASK)
474 * A bit pattern for identifying string IDs generated by
475 * kdebug_trace_string(2).
477 static uint64_t g_str_id_signature
= (0x70acULL
<< STR_ID_SIG_OFFSET
);
479 #define INTERRUPT 0x01050000
480 #define MACH_vmfault 0x01300008
481 #define BSC_SysCall 0x040c0000
482 #define MACH_SysCall 0x010c0000
484 /* task to string structure */
486 task_t task
; /* from procs task */
487 pid_t pid
; /* from procs p_pid */
488 char task_comm
[20];/* from procs p_comm */
491 typedef struct tts tts_t
;
494 kd_threadmap
*map
; /* pointer to the map buffer */
501 * TRACE file formats...
505 * uint32_t #threadmaps
511 * RAW_header, with version_no set to RAW_VERSION1
513 * Empty space to pad alignment to the nearest page boundary.
518 * RAW_header, with version_no set to RAW_VERSION1
520 * kd_cpumap_header, with version_no set to RAW_VERSION1
522 * Empty space to pad alignment to the nearest page boundary.
525 * V1+ implementation details...
527 * It would have been nice to add the cpumap data "correctly", but there were
528 * several obstacles. Existing code attempts to parse both V1 and V0 files.
529 * Due to the fact that V0 has no versioning or header, the test looks like
533 * if (header.version_no != RAW_VERSION1) { // Assume V0 }
535 * If we add a VERSION2 file format, all existing code is going to treat that
536 * as a VERSION0 file when reading it, and crash terribly when trying to read
537 * RAW_VERSION2 threadmap entries.
539 * To differentiate between a V1 and V1+ file, read as V1 until you reach
540 * the padding bytes. Then:
542 * boolean_t is_v1plus = FALSE;
543 * if (padding_bytes >= sizeof(kd_cpumap_header)) {
544 * kd_cpumap_header header = // read header;
545 * if (header.version_no == RAW_VERSION1) {
552 #define RAW_VERSION3 0x00001000
555 // The header chunk has the tag 0x00001000 which also serves as a magic word
556 // that identifies the file as a version 3 trace file. The header payload is
557 // a set of fixed fields followed by a variable number of sub-chunks:
559 * ____________________________________________________________________________
560 | Offset | Size | Field |
561 | ----------------------------------------------------------------------------
562 | 0 | 4 | Tag (0x00001000) |
563 | 4 | 4 | Sub-tag. Represents the version of the header. |
564 | 8 | 8 | Length of header payload (40+8x) |
565 | 16 | 8 | Time base info. Two 32-bit numbers, numer/denom, |
566 | | | for converting timestamps to nanoseconds. |
567 | 24 | 8 | Timestamp of trace start. |
568 | 32 | 8 | Wall time seconds since Unix epoch. |
569 | | | As returned by gettimeofday(). |
570 | 40 | 4 | Wall time microseconds. As returned by gettimeofday(). |
571 | 44 | 4 | Local time zone offset in minutes. ( " ) |
572 | 48 | 4 | Type of daylight savings time correction to apply. ( " ) |
573 | 52 | 4 | Flags. 1 = 64-bit. Remaining bits should be written |
574 | | | as 0 and ignored when reading. |
575 | 56 | 8x | Variable number of sub-chunks. None are required. |
576 | | | Ignore unknown chunks. |
577 | ----------------------------------------------------------------------------
579 // NOTE: The header sub-chunks are considered part of the header chunk,
580 // so they must be included in the header chunk’s length field.
581 // The CPU map is an optional sub-chunk of the header chunk. It provides
582 // information about the CPUs that are referenced from the trace events.
587 uint32_t timebase_numer
;
588 uint32_t timebase_denom
;
590 uint64_t walltime_secs
;
591 uint32_t walltime_usecs
;
592 uint32_t timezone_minuteswest
;
593 uint32_t timezone_dst
;
595 } __attribute__((packed
)) kd_header_v3
;
601 } __attribute__((packed
)) kd_chunk_header_v3
;
603 #define V3_CONFIG 0x00001b00
604 #define V3_CPU_MAP 0x00001c00
605 #define V3_THREAD_MAP 0x00001d00
606 #define V3_RAW_EVENTS 0x00001e00
607 #define V3_NULL_CHUNK 0x00002000
609 // The current version of all kernel managed chunks is 1. The
610 // V3_CURRENT_CHUNK_VERSION is added to ease the simple case
611 // when most/all the kernel managed chunks have the same version.
613 #define V3_CURRENT_CHUNK_VERSION 1
614 #define V3_HEADER_VERSION V3_CURRENT_CHUNK_VERSION
615 #define V3_CPUMAP_VERSION V3_CURRENT_CHUNK_VERSION
616 #define V3_THRMAP_VERSION V3_CURRENT_CHUNK_VERSION
617 #define V3_EVENT_DATA_VERSION V3_CURRENT_CHUNK_VERSION
619 typedef struct krt krt_t
;
622 kdbg_cpu_count(bool early_trace
)
626 return ml_get_cpu_count();
632 host_basic_info_data_t hinfo
;
633 mach_msg_type_number_t count
= HOST_BASIC_INFO_COUNT
;
634 host_info((host_t
)1 /* BSD_HOST */, HOST_BASIC_INFO
, (host_info_t
)&hinfo
, &count
);
635 assert(hinfo
.logical_cpu_max
> 0);
636 return hinfo
.logical_cpu_max
;
642 kdbg_iop_list_is_valid(kd_iop_t
* iop
)
645 /* Is list sorted by cpu_id? */
646 kd_iop_t
* temp
= iop
;
648 assert(!temp
->next
|| temp
->next
->cpu_id
== temp
->cpu_id
- 1);
649 assert(temp
->next
|| (temp
->cpu_id
== kdbg_cpu_count(false) || temp
->cpu_id
== kdbg_cpu_count(true)));
650 } while ((temp
= temp
->next
));
652 /* Does each entry have a function and a name? */
655 assert(temp
->callback
.func
);
656 assert(strlen(temp
->callback
.iop_name
) < sizeof(temp
->callback
.iop_name
));
657 } while ((temp
= temp
->next
));
664 kdbg_iop_list_contains_cpu_id(kd_iop_t
* list
, uint32_t cpu_id
)
667 if (list
->cpu_id
== cpu_id
) {
675 #endif /* CONFIG_EMBEDDED */
676 #endif /* MACH_ASSERT */
679 kdbg_iop_list_callback(kd_iop_t
* iop
, kd_callback_type type
, void* arg
)
682 iop
->callback
.func(iop
->callback
.context
, type
, arg
);
687 static lck_grp_t
*kdebug_lck_grp
= NULL
;
690 kdbg_set_tracing_enabled(bool enabled
, uint32_t trace_type
)
693 * Drain any events from IOPs before making the state change. On
694 * enabling, this removes any stale events from before tracing. On
695 * disabling, this saves any events up to the point tracing is disabled.
697 kdbg_iop_list_callback(kd_ctrl_page
.kdebug_iops
, KD_CALLBACK_SYNC_FLUSH
,
700 int s
= ml_set_interrupts_enabled(false);
701 lck_spin_lock_grp(kds_spin_lock
, kdebug_lck_grp
);
705 * The oldest valid time is now; reject past events from IOPs.
707 kd_ctrl_page
.oldest_time
= kdbg_timestamp();
708 kdebug_enable
|= trace_type
;
709 kd_ctrl_page
.kdebug_slowcheck
&= ~SLOW_NOLOG
;
710 kd_ctrl_page
.enabled
= 1;
711 commpage_update_kdebug_state();
713 kdebug_enable
&= ~(KDEBUG_ENABLE_TRACE
| KDEBUG_ENABLE_PPT
);
714 kd_ctrl_page
.kdebug_slowcheck
|= SLOW_NOLOG
;
715 kd_ctrl_page
.enabled
= 0;
716 commpage_update_kdebug_state();
718 lck_spin_unlock(kds_spin_lock
);
719 ml_set_interrupts_enabled(s
);
722 kdbg_iop_list_callback(kd_ctrl_page
.kdebug_iops
,
723 KD_CALLBACK_KDEBUG_ENABLED
, NULL
);
725 kdbg_iop_list_callback(kd_ctrl_page
.kdebug_iops
,
726 KD_CALLBACK_KDEBUG_DISABLED
, NULL
);
731 kdbg_set_flags(int slowflag
, int enableflag
, bool enabled
)
733 int s
= ml_set_interrupts_enabled(false);
734 lck_spin_lock_grp(kds_spin_lock
, kdebug_lck_grp
);
737 kd_ctrl_page
.kdebug_slowcheck
|= slowflag
;
738 kdebug_enable
|= enableflag
;
740 kd_ctrl_page
.kdebug_slowcheck
&= ~slowflag
;
741 kdebug_enable
&= ~enableflag
;
744 lck_spin_unlock(kds_spin_lock
);
745 ml_set_interrupts_enabled(s
);
749 * Disable wrapping and return true if trace wrapped, false otherwise.
752 disable_wrap(uint32_t *old_slowcheck
, uint32_t *old_flags
)
755 int s
= ml_set_interrupts_enabled(false);
756 lck_spin_lock_grp(kds_spin_lock
, kdebug_lck_grp
);
758 *old_slowcheck
= kd_ctrl_page
.kdebug_slowcheck
;
759 *old_flags
= kd_ctrl_page
.kdebug_flags
;
761 wrapped
= kd_ctrl_page
.kdebug_flags
& KDBG_WRAPPED
;
762 kd_ctrl_page
.kdebug_flags
&= ~KDBG_WRAPPED
;
763 kd_ctrl_page
.kdebug_flags
|= KDBG_NOWRAP
;
765 lck_spin_unlock(kds_spin_lock
);
766 ml_set_interrupts_enabled(s
);
772 enable_wrap(uint32_t old_slowcheck
)
774 int s
= ml_set_interrupts_enabled(false);
775 lck_spin_lock_grp(kds_spin_lock
, kdebug_lck_grp
);
777 kd_ctrl_page
.kdebug_flags
&= ~KDBG_NOWRAP
;
779 if (!(old_slowcheck
& SLOW_NOLOG
)) {
780 kd_ctrl_page
.kdebug_slowcheck
&= ~SLOW_NOLOG
;
783 lck_spin_unlock(kds_spin_lock
);
784 ml_set_interrupts_enabled(s
);
788 create_buffers(bool early_trace
)
791 unsigned int p_buffer_size
;
792 unsigned int f_buffer_size
;
793 unsigned int f_buffers
;
797 * For the duration of this allocation, trace code will only reference
798 * kdebug_iops. Any iops registered after this enabling will not be
799 * messaged until the buffers are reallocated.
801 * TLDR; Must read kd_iops once and only once!
803 kd_ctrl_page
.kdebug_iops
= kd_iops
;
806 assert(kdbg_iop_list_is_valid(kd_ctrl_page
.kdebug_iops
));
810 * If the list is valid, it is sorted, newest -> oldest. Each iop entry
811 * has a cpu_id of "the older entry + 1", so the highest cpu_id will
812 * be the list head + 1.
815 kd_ctrl_page
.kdebug_cpus
= kd_ctrl_page
.kdebug_iops
? kd_ctrl_page
.kdebug_iops
->cpu_id
+ 1 : kdbg_cpu_count(early_trace
);
817 if (kmem_alloc(kernel_map
, (vm_offset_t
*)&kdbip
, sizeof(struct kd_bufinfo
) * kd_ctrl_page
.kdebug_cpus
, VM_KERN_MEMORY_DIAG
) != KERN_SUCCESS
) {
822 if (nkdbufs
< (kd_ctrl_page
.kdebug_cpus
* EVENTS_PER_STORAGE_UNIT
* MIN_STORAGE_UNITS_PER_CPU
)) {
823 n_storage_units
= kd_ctrl_page
.kdebug_cpus
* MIN_STORAGE_UNITS_PER_CPU
;
825 n_storage_units
= nkdbufs
/ EVENTS_PER_STORAGE_UNIT
;
828 nkdbufs
= n_storage_units
* EVENTS_PER_STORAGE_UNIT
;
830 f_buffers
= n_storage_units
/ N_STORAGE_UNITS_PER_BUFFER
;
831 n_storage_buffers
= f_buffers
;
833 f_buffer_size
= N_STORAGE_UNITS_PER_BUFFER
* sizeof(struct kd_storage
);
834 p_buffer_size
= (n_storage_units
% N_STORAGE_UNITS_PER_BUFFER
) * sizeof(struct kd_storage
);
842 if (kdcopybuf
== 0) {
843 if (kmem_alloc(kernel_map
, (vm_offset_t
*)&kdcopybuf
, (vm_size_t
)KDCOPYBUF_SIZE
, VM_KERN_MEMORY_DIAG
) != KERN_SUCCESS
) {
848 if (kmem_alloc(kernel_map
, (vm_offset_t
*)&kd_bufs
, (vm_size_t
)(n_storage_buffers
* sizeof(struct kd_storage_buffers
)), VM_KERN_MEMORY_DIAG
) != KERN_SUCCESS
) {
852 bzero(kd_bufs
, n_storage_buffers
* sizeof(struct kd_storage_buffers
));
854 for (i
= 0; i
< f_buffers
; i
++) {
855 if (kmem_alloc(kernel_map
, (vm_offset_t
*)&kd_bufs
[i
].kdsb_addr
, (vm_size_t
)f_buffer_size
, VM_KERN_MEMORY_DIAG
) != KERN_SUCCESS
) {
859 bzero(kd_bufs
[i
].kdsb_addr
, f_buffer_size
);
861 kd_bufs
[i
].kdsb_size
= f_buffer_size
;
864 if (kmem_alloc(kernel_map
, (vm_offset_t
*)&kd_bufs
[i
].kdsb_addr
, (vm_size_t
)p_buffer_size
, VM_KERN_MEMORY_DIAG
) != KERN_SUCCESS
) {
868 bzero(kd_bufs
[i
].kdsb_addr
, p_buffer_size
);
870 kd_bufs
[i
].kdsb_size
= p_buffer_size
;
874 for (i
= 0; i
< n_storage_buffers
; i
++) {
875 struct kd_storage
*kds
;
879 n_elements
= kd_bufs
[i
].kdsb_size
/ sizeof(struct kd_storage
);
880 kds
= kd_bufs
[i
].kdsb_addr
;
882 for (n
= 0; n
< n_elements
; n
++) {
883 kds
[n
].kds_next
.buffer_index
= kd_ctrl_page
.kds_free_list
.buffer_index
;
884 kds
[n
].kds_next
.offset
= kd_ctrl_page
.kds_free_list
.offset
;
886 kd_ctrl_page
.kds_free_list
.buffer_index
= i
;
887 kd_ctrl_page
.kds_free_list
.offset
= n
;
889 n_storage_units
+= n_elements
;
892 bzero((char *)kdbip
, sizeof(struct kd_bufinfo
) * kd_ctrl_page
.kdebug_cpus
);
894 for (i
= 0; i
< kd_ctrl_page
.kdebug_cpus
; i
++) {
895 kdbip
[i
].kd_list_head
.raw
= KDS_PTR_NULL
;
896 kdbip
[i
].kd_list_tail
.raw
= KDS_PTR_NULL
;
897 kdbip
[i
].kd_lostevents
= false;
898 kdbip
[i
].num_bufs
= 0;
901 kd_ctrl_page
.kdebug_flags
|= KDBG_BUFINIT
;
903 kd_ctrl_page
.kds_inuse_count
= 0;
904 n_storage_threshold
= n_storage_units
/ 2;
919 for (i
= 0; i
< n_storage_buffers
; i
++) {
920 if (kd_bufs
[i
].kdsb_addr
) {
921 kmem_free(kernel_map
, (vm_offset_t
)kd_bufs
[i
].kdsb_addr
, (vm_size_t
)kd_bufs
[i
].kdsb_size
);
924 kmem_free(kernel_map
, (vm_offset_t
)kd_bufs
, (vm_size_t
)(n_storage_buffers
* sizeof(struct kd_storage_buffers
)));
927 n_storage_buffers
= 0;
930 kmem_free(kernel_map
, (vm_offset_t
)kdcopybuf
, KDCOPYBUF_SIZE
);
934 kd_ctrl_page
.kds_free_list
.raw
= KDS_PTR_NULL
;
937 kmem_free(kernel_map
, (vm_offset_t
)kdbip
, sizeof(struct kd_bufinfo
) * kd_ctrl_page
.kdebug_cpus
);
941 kd_ctrl_page
.kdebug_iops
= NULL
;
942 kd_ctrl_page
.kdebug_cpus
= 0;
943 kd_ctrl_page
.kdebug_flags
&= ~KDBG_BUFINIT
;
947 release_storage_unit(int cpu
, uint32_t kdsp_raw
)
950 struct kd_storage
*kdsp_actual
;
951 struct kd_bufinfo
*kdbp
;
956 s
= ml_set_interrupts_enabled(false);
957 lck_spin_lock_grp(kds_spin_lock
, kdebug_lck_grp
);
961 if (kdsp
.raw
== kdbp
->kd_list_head
.raw
) {
963 * it's possible for the storage unit pointed to
964 * by kdsp to have already been stolen... so
965 * check to see if it's still the head of the list
966 * now that we're behind the lock that protects
967 * adding and removing from the queue...
968 * since we only ever release and steal units from
969 * that position, if it's no longer the head
970 * we having nothing to do in this context
972 kdsp_actual
= POINTER_FROM_KDS_PTR(kdsp
);
973 kdbp
->kd_list_head
= kdsp_actual
->kds_next
;
975 kdsp_actual
->kds_next
= kd_ctrl_page
.kds_free_list
;
976 kd_ctrl_page
.kds_free_list
= kdsp
;
978 kd_ctrl_page
.kds_inuse_count
--;
980 lck_spin_unlock(kds_spin_lock
);
981 ml_set_interrupts_enabled(s
);
985 allocate_storage_unit(int cpu
)
988 struct kd_storage
*kdsp_actual
, *kdsp_next_actual
;
989 struct kd_bufinfo
*kdbp
, *kdbp_vict
, *kdbp_try
;
990 uint64_t oldest_ts
, ts
;
994 s
= ml_set_interrupts_enabled(false);
995 lck_spin_lock_grp(kds_spin_lock
, kdebug_lck_grp
);
999 /* If someone beat us to the allocate, return success */
1000 if (kdbp
->kd_list_tail
.raw
!= KDS_PTR_NULL
) {
1001 kdsp_actual
= POINTER_FROM_KDS_PTR(kdbp
->kd_list_tail
);
1003 if (kdsp_actual
->kds_bufindx
< EVENTS_PER_STORAGE_UNIT
) {
1008 if ((kdsp
= kd_ctrl_page
.kds_free_list
).raw
!= KDS_PTR_NULL
) {
1010 * If there's a free page, grab it from the free list.
1012 kdsp_actual
= POINTER_FROM_KDS_PTR(kdsp
);
1013 kd_ctrl_page
.kds_free_list
= kdsp_actual
->kds_next
;
1015 kd_ctrl_page
.kds_inuse_count
++;
1018 * Otherwise, we're going to lose events and repurpose the oldest
1019 * storage unit we can find.
1021 if (kd_ctrl_page
.kdebug_flags
& KDBG_NOWRAP
) {
1022 kd_ctrl_page
.kdebug_slowcheck
|= SLOW_NOLOG
;
1023 kdbp
->kd_lostevents
= true;
1028 oldest_ts
= UINT64_MAX
;
1030 for (kdbp_try
= &kdbip
[0]; kdbp_try
< &kdbip
[kd_ctrl_page
.kdebug_cpus
]; kdbp_try
++) {
1031 if (kdbp_try
->kd_list_head
.raw
== KDS_PTR_NULL
) {
1033 * no storage unit to steal
1038 kdsp_actual
= POINTER_FROM_KDS_PTR(kdbp_try
->kd_list_head
);
1040 if (kdsp_actual
->kds_bufcnt
< EVENTS_PER_STORAGE_UNIT
) {
1042 * make sure we don't steal the storage unit
1043 * being actively recorded to... need to
1044 * move on because we don't want an out-of-order
1045 * set of events showing up later
1051 * When wrapping, steal the storage unit with the
1052 * earliest timestamp on its last event, instead of the
1053 * earliest timestamp on the first event. This allows a
1054 * storage unit with more recent events to be preserved,
1055 * even if the storage unit contains events that are
1056 * older than those found in other CPUs.
1058 ts
= kdbg_get_timestamp(&kdsp_actual
->kds_records
[EVENTS_PER_STORAGE_UNIT
- 1]);
1059 if (ts
< oldest_ts
) {
1061 kdbp_vict
= kdbp_try
;
1064 if (kdbp_vict
== NULL
) {
1066 kd_ctrl_page
.enabled
= 0;
1067 commpage_update_kdebug_state();
1071 kdsp
= kdbp_vict
->kd_list_head
;
1072 kdsp_actual
= POINTER_FROM_KDS_PTR(kdsp
);
1073 kdbp_vict
->kd_list_head
= kdsp_actual
->kds_next
;
1075 if (kdbp_vict
->kd_list_head
.raw
!= KDS_PTR_NULL
) {
1076 kdsp_next_actual
= POINTER_FROM_KDS_PTR(kdbp_vict
->kd_list_head
);
1077 kdsp_next_actual
->kds_lostevents
= true;
1079 kdbp_vict
->kd_lostevents
= true;
1082 if (kd_ctrl_page
.oldest_time
< oldest_ts
) {
1083 kd_ctrl_page
.oldest_time
= oldest_ts
;
1085 kd_ctrl_page
.kdebug_flags
|= KDBG_WRAPPED
;
1087 kdsp_actual
->kds_timestamp
= kdbg_timestamp();
1088 kdsp_actual
->kds_next
.raw
= KDS_PTR_NULL
;
1089 kdsp_actual
->kds_bufcnt
= 0;
1090 kdsp_actual
->kds_readlast
= 0;
1092 kdsp_actual
->kds_lostevents
= kdbp
->kd_lostevents
;
1093 kdbp
->kd_lostevents
= false;
1094 kdsp_actual
->kds_bufindx
= 0;
1096 if (kdbp
->kd_list_head
.raw
== KDS_PTR_NULL
) {
1097 kdbp
->kd_list_head
= kdsp
;
1099 POINTER_FROM_KDS_PTR(kdbp
->kd_list_tail
)->kds_next
= kdsp
;
1101 kdbp
->kd_list_tail
= kdsp
;
1103 lck_spin_unlock(kds_spin_lock
);
1104 ml_set_interrupts_enabled(s
);
1110 kernel_debug_register_callback(kd_callback_t callback
)
1113 if (kmem_alloc(kernel_map
, (vm_offset_t
*)&iop
, sizeof(kd_iop_t
), VM_KERN_MEMORY_DIAG
) == KERN_SUCCESS
) {
1114 memcpy(&iop
->callback
, &callback
, sizeof(kd_callback_t
));
1117 * <rdar://problem/13351477> Some IOP clients are not providing a name.
1119 * Remove when fixed.
1122 bool is_valid_name
= false;
1123 for (uint32_t length
= 0; length
< sizeof(callback
.iop_name
); ++length
) {
1124 /* This is roughly isprintable(c) */
1125 if (callback
.iop_name
[length
] > 0x20 && callback
.iop_name
[length
] < 0x7F) {
1128 if (callback
.iop_name
[length
] == 0) {
1130 is_valid_name
= true;
1136 if (!is_valid_name
) {
1137 strlcpy(iop
->callback
.iop_name
, "IOP-???", sizeof(iop
->callback
.iop_name
));
1141 iop
->last_timestamp
= 0;
1145 * We use two pieces of state, the old list head
1146 * pointer, and the value of old_list_head->cpu_id.
1147 * If we read kd_iops more than once, it can change
1150 * TLDR; Must not read kd_iops more than once per loop.
1152 iop
->next
= kd_iops
;
1153 iop
->cpu_id
= iop
->next
? (iop
->next
->cpu_id
+ 1) : kdbg_cpu_count(false);
1156 * Header says OSCompareAndSwapPtr has a memory barrier
1158 } while (!OSCompareAndSwapPtr(iop
->next
, iop
, (void* volatile*)&kd_iops
));
1180 struct kd_bufinfo
*kdbp
;
1181 struct kd_storage
*kdsp_actual
;
1182 union kds_ptr kds_raw
;
1184 if (kd_ctrl_page
.kdebug_slowcheck
) {
1185 if ((kd_ctrl_page
.kdebug_slowcheck
& SLOW_NOLOG
) || !(kdebug_enable
& (KDEBUG_ENABLE_TRACE
| KDEBUG_ENABLE_PPT
))) {
1189 if (kd_ctrl_page
.kdebug_flags
& KDBG_TYPEFILTER_CHECK
) {
1190 if (typefilter_is_debugid_allowed(kdbg_typefilter
, debugid
)) {
1194 } else if (kd_ctrl_page
.kdebug_flags
& KDBG_RANGECHECK
) {
1195 if (debugid
>= kdlog_beg
&& debugid
<= kdlog_end
) {
1199 } else if (kd_ctrl_page
.kdebug_flags
& KDBG_VALCHECK
) {
1200 if ((debugid
& KDBG_EVENTID_MASK
) != kdlog_value1
&&
1201 (debugid
& KDBG_EVENTID_MASK
) != kdlog_value2
&&
1202 (debugid
& KDBG_EVENTID_MASK
) != kdlog_value3
&&
1203 (debugid
& KDBG_EVENTID_MASK
) != kdlog_value4
) {
1210 if (timestamp
< kd_ctrl_page
.oldest_time
) {
1216 * When start_kern_tracing is called by the kernel to trace very
1217 * early kernel events, it saves data to a secondary buffer until
1218 * it is possible to initialize ktrace, and then dumps the events
1219 * into the ktrace buffer using this method. In this case, iops will
1220 * be NULL, and the coreid will be zero. It is not possible to have
1221 * a valid IOP coreid of zero, so pass if both iops is NULL and coreid
1224 assert(kdbg_iop_list_contains_cpu_id(kd_ctrl_page
.kdebug_iops
, coreid
) || (kd_ctrl_page
.kdebug_iops
== NULL
&& coreid
== 0));
1227 disable_preemption();
1229 if (kd_ctrl_page
.enabled
== 0) {
1233 kdbp
= &kdbip
[coreid
];
1234 timestamp
&= KDBG_TIMESTAMP_MASK
;
1236 #if KDEBUG_MOJO_TRACE
1237 if (kdebug_enable
& KDEBUG_ENABLE_SERIAL
) {
1238 kdebug_serial_print(coreid
, debugid
, timestamp
,
1239 arg1
, arg2
, arg3
, arg4
, threadid
);
1244 kds_raw
= kdbp
->kd_list_tail
;
1246 if (kds_raw
.raw
!= KDS_PTR_NULL
) {
1247 kdsp_actual
= POINTER_FROM_KDS_PTR(kds_raw
);
1248 bindx
= kdsp_actual
->kds_bufindx
;
1251 bindx
= EVENTS_PER_STORAGE_UNIT
;
1254 if (kdsp_actual
== NULL
|| bindx
>= EVENTS_PER_STORAGE_UNIT
) {
1255 if (allocate_storage_unit(coreid
) == false) {
1257 * this can only happen if wrapping
1264 if (!OSCompareAndSwap(bindx
, bindx
+ 1, &kdsp_actual
->kds_bufindx
)) {
1268 // IOP entries can be allocated before xnu allocates and inits the buffer
1269 if (timestamp
< kdsp_actual
->kds_timestamp
) {
1270 kdsp_actual
->kds_timestamp
= timestamp
;
1273 kd
= &kdsp_actual
->kds_records
[bindx
];
1275 kd
->debugid
= debugid
;
1280 kd
->arg5
= threadid
;
1282 kdbg_set_timestamp_and_cpu(kd
, timestamp
, coreid
);
1284 OSAddAtomic(1, &kdsp_actual
->kds_bufcnt
);
1286 enable_preemption();
1288 if ((kds_waiter
&& kd_ctrl_page
.kds_inuse_count
>= n_storage_threshold
)) {
1294 * Check if the given debug ID is allowed to be traced on the current process.
1296 * Returns true if allowed and false otherwise.
1299 kdebug_debugid_procfilt_allowed(uint32_t debugid
)
1301 uint32_t procfilt_flags
= kd_ctrl_page
.kdebug_flags
&
1302 (KDBG_PIDCHECK
| KDBG_PIDEXCLUDE
);
1304 if (!procfilt_flags
) {
1309 * DBG_TRACE and MACH_SCHED tracepoints ignore the process filter.
1311 if ((debugid
& 0xffff0000) == MACHDBG_CODE(DBG_MACH_SCHED
, 0) ||
1312 (debugid
>> 24 == DBG_TRACE
)) {
1316 struct proc
*curproc
= current_proc();
1318 * If the process is missing (early in boot), allow it.
1324 if (procfilt_flags
& KDBG_PIDCHECK
) {
1326 * Allow only processes marked with the kdebug bit.
1328 return curproc
->p_kdebug
;
1329 } else if (procfilt_flags
& KDBG_PIDEXCLUDE
) {
1331 * Exclude any process marked with the kdebug bit.
1333 return !curproc
->p_kdebug
;
1335 panic("kdebug: invalid procfilt flags %x", kd_ctrl_page
.kdebug_flags
);
1336 __builtin_unreachable();
1341 kernel_debug_internal(
1354 struct kd_bufinfo
*kdbp
;
1355 struct kd_storage
*kdsp_actual
;
1356 union kds_ptr kds_raw
;
1357 bool only_filter
= flags
& KDBG_FLAG_FILTERED
;
1358 bool observe_procfilt
= !(flags
& KDBG_FLAG_NOPROCFILT
);
1360 if (kd_ctrl_page
.kdebug_slowcheck
) {
1361 if ((kd_ctrl_page
.kdebug_slowcheck
& SLOW_NOLOG
) ||
1362 !(kdebug_enable
& (KDEBUG_ENABLE_TRACE
| KDEBUG_ENABLE_PPT
))) {
1366 if (!ml_at_interrupt_context() && observe_procfilt
&&
1367 !kdebug_debugid_procfilt_allowed(debugid
)) {
1371 if (kd_ctrl_page
.kdebug_flags
& KDBG_TYPEFILTER_CHECK
) {
1372 if (typefilter_is_debugid_allowed(kdbg_typefilter
, debugid
)) {
1377 } else if (only_filter
) {
1379 } else if (kd_ctrl_page
.kdebug_flags
& KDBG_RANGECHECK
) {
1380 /* Always record trace system info */
1381 if (KDBG_EXTRACT_CLASS(debugid
) == DBG_TRACE
) {
1385 if (debugid
< kdlog_beg
|| debugid
> kdlog_end
) {
1388 } else if (kd_ctrl_page
.kdebug_flags
& KDBG_VALCHECK
) {
1389 /* Always record trace system info */
1390 if (KDBG_EXTRACT_CLASS(debugid
) == DBG_TRACE
) {
1394 if ((debugid
& KDBG_EVENTID_MASK
) != kdlog_value1
&&
1395 (debugid
& KDBG_EVENTID_MASK
) != kdlog_value2
&&
1396 (debugid
& KDBG_EVENTID_MASK
) != kdlog_value3
&&
1397 (debugid
& KDBG_EVENTID_MASK
) != kdlog_value4
) {
1401 } else if (only_filter
) {
1406 disable_preemption();
1408 if (kd_ctrl_page
.enabled
== 0) {
1415 #if KDEBUG_MOJO_TRACE
1416 if (kdebug_enable
& KDEBUG_ENABLE_SERIAL
) {
1417 kdebug_serial_print(cpu
, debugid
,
1418 kdbg_timestamp() & KDBG_TIMESTAMP_MASK
,
1419 arg1
, arg2
, arg3
, arg4
, arg5
);
1424 kds_raw
= kdbp
->kd_list_tail
;
1426 if (kds_raw
.raw
!= KDS_PTR_NULL
) {
1427 kdsp_actual
= POINTER_FROM_KDS_PTR(kds_raw
);
1428 bindx
= kdsp_actual
->kds_bufindx
;
1431 bindx
= EVENTS_PER_STORAGE_UNIT
;
1434 if (kdsp_actual
== NULL
|| bindx
>= EVENTS_PER_STORAGE_UNIT
) {
1435 if (allocate_storage_unit(cpu
) == false) {
1437 * this can only happen if wrapping
1445 now
= kdbg_timestamp() & KDBG_TIMESTAMP_MASK
;
1447 if (!OSCompareAndSwap(bindx
, bindx
+ 1, &kdsp_actual
->kds_bufindx
)) {
1451 kd
= &kdsp_actual
->kds_records
[bindx
];
1453 kd
->debugid
= debugid
;
1460 kdbg_set_timestamp_and_cpu(kd
, now
, cpu
);
1462 OSAddAtomic(1, &kdsp_actual
->kds_bufcnt
);
1465 kperf_kdebug_callback(debugid
, __builtin_frame_address(0));
1468 enable_preemption();
1470 if (kds_waiter
&& kd_ctrl_page
.kds_inuse_count
>= n_storage_threshold
) {
1474 etype
= debugid
& KDBG_EVENTID_MASK
;
1475 stype
= debugid
& KDBG_CSC_MASK
;
1477 if (etype
== INTERRUPT
|| etype
== MACH_vmfault
||
1478 stype
== BSC_SysCall
|| stype
== MACH_SysCall
) {
1484 __attribute__((noinline
))
1492 __unused
uintptr_t arg5
)
1494 kernel_debug_internal(debugid
, arg1
, arg2
, arg3
, arg4
,
1495 (uintptr_t)thread_tid(current_thread()), 0);
1498 __attribute__((noinline
))
1508 kernel_debug_internal(debugid
, arg1
, arg2
, arg3
, arg4
, arg5
, 0);
1511 __attribute__((noinline
))
1521 kernel_debug_internal(debugid
, arg1
, arg2
, arg3
, arg4
,
1522 (uintptr_t)thread_tid(current_thread()), flags
);
1525 __attribute__((noinline
))
1527 kernel_debug_filtered(
1534 kernel_debug_flags(debugid
, arg1
, arg2
, arg3
, arg4
, KDBG_FLAG_FILTERED
);
1538 kernel_debug_string_early(const char *message
)
1540 uintptr_t arg
[4] = {0, 0, 0, 0};
1542 /* Stuff the message string in the args and log it. */
1543 strncpy((char *)arg
, message
, MIN(sizeof(arg
), strlen(message
)));
1546 arg
[0], arg
[1], arg
[2], arg
[3]);
1549 #define SIMPLE_STR_LEN (64)
1550 static_assert(SIMPLE_STR_LEN
% sizeof(uintptr_t) == 0);
1553 kernel_debug_string_simple(uint32_t eventid
, const char *str
)
1555 if (!kdebug_enable
) {
1559 /* array of uintptr_ts simplifies emitting the string as arguments */
1560 uintptr_t str_buf
[(SIMPLE_STR_LEN
/ sizeof(uintptr_t)) + 1] = { 0 };
1561 size_t len
= strlcpy((char *)str_buf
, str
, SIMPLE_STR_LEN
+ 1);
1563 uintptr_t thread_id
= (uintptr_t)thread_tid(current_thread());
1564 uint32_t debugid
= eventid
| DBG_FUNC_START
;
1566 /* string can fit in a single tracepoint */
1567 if (len
<= (4 * sizeof(uintptr_t))) {
1568 debugid
|= DBG_FUNC_END
;
1571 kernel_debug_internal(debugid
, str_buf
[0],
1574 str_buf
[3], thread_id
, 0);
1576 debugid
&= KDBG_EVENTID_MASK
;
1578 size_t written
= 4 * sizeof(uintptr_t);
1580 for (; written
< len
; i
+= 4, written
+= 4 * sizeof(uintptr_t)) {
1581 /* if this is the last tracepoint to be emitted */
1582 if ((written
+ (4 * sizeof(uintptr_t))) >= len
) {
1583 debugid
|= DBG_FUNC_END
;
1585 kernel_debug_internal(debugid
, str_buf
[i
],
1588 str_buf
[i
+ 3], thread_id
, 0);
1592 extern int master_cpu
; /* MACH_KERNEL_PRIVATE */
1594 * Used prior to start_kern_tracing() being called.
1595 * Log temporarily into a static buffer.
1605 #if defined(__x86_64__)
1606 extern int early_boot
;
1608 * Note that "early" isn't early enough in some cases where
1609 * we're invoked before gsbase is set on x86, hence the
1610 * check of "early_boot".
1617 /* If early tracing is over, use the normal path. */
1618 if (kd_early_done
) {
1619 KERNEL_DEBUG_CONSTANT(debugid
, arg1
, arg2
, arg3
, arg4
, 0);
1623 /* Do nothing if the buffer is full or we're not on the boot cpu. */
1624 kd_early_overflow
= kd_early_index
>= KD_EARLY_BUFFER_NBUFS
;
1625 if (kd_early_overflow
|| cpu_number() != master_cpu
) {
1629 kd_early_buffer
[kd_early_index
].debugid
= debugid
;
1630 kd_early_buffer
[kd_early_index
].timestamp
= mach_absolute_time();
1631 kd_early_buffer
[kd_early_index
].arg1
= arg1
;
1632 kd_early_buffer
[kd_early_index
].arg2
= arg2
;
1633 kd_early_buffer
[kd_early_index
].arg3
= arg3
;
1634 kd_early_buffer
[kd_early_index
].arg4
= arg4
;
1635 kd_early_buffer
[kd_early_index
].arg5
= 0;
1640 * Transfer the contents of the temporary buffer into the trace buffers.
1641 * Precede that by logging the rebase time (offset) - the TSC-based time (in ns)
1642 * when mach_absolute_time is set to 0.
1645 kernel_debug_early_end(void)
1647 if (cpu_number() != master_cpu
) {
1648 panic("kernel_debug_early_end() not call on boot processor");
1651 /* reset the current oldest time to allow early events */
1652 kd_ctrl_page
.oldest_time
= 0;
1654 #if !CONFIG_EMBEDDED
1655 /* Fake sentinel marking the start of kernel time relative to TSC */
1656 kernel_debug_enter(0,
1659 (uint32_t)(tsc_rebase_abs_time
>> 32),
1660 (uint32_t)tsc_rebase_abs_time
,
1665 for (unsigned int i
= 0; i
< kd_early_index
; i
++) {
1666 kernel_debug_enter(0,
1667 kd_early_buffer
[i
].debugid
,
1668 kd_early_buffer
[i
].timestamp
,
1669 kd_early_buffer
[i
].arg1
,
1670 kd_early_buffer
[i
].arg2
,
1671 kd_early_buffer
[i
].arg3
,
1672 kd_early_buffer
[i
].arg4
,
1676 /* Cut events-lost event on overflow */
1677 if (kd_early_overflow
) {
1678 KDBG_RELEASE(TRACE_LOST_EVENTS
, 1);
1681 kd_early_done
= true;
1683 /* This trace marks the start of kernel tracing */
1684 kernel_debug_string_early("early trace done");
1688 kernel_debug_disable(void)
1690 if (kdebug_enable
) {
1691 kdbg_set_tracing_enabled(false, 0);
1696 * Returns non-zero if debugid is in a reserved class.
1699 kdebug_validate_debugid(uint32_t debugid
)
1701 uint8_t debugid_class
;
1703 debugid_class
= KDBG_EXTRACT_CLASS(debugid
);
1704 switch (debugid_class
) {
1713 * Support syscall SYS_kdebug_typefilter.
1716 kdebug_typefilter(__unused
struct proc
* p
,
1717 struct kdebug_typefilter_args
* uap
,
1718 __unused
int *retval
)
1720 int ret
= KERN_SUCCESS
;
1722 if (uap
->addr
== USER_ADDR_NULL
||
1723 uap
->size
== USER_ADDR_NULL
) {
1728 * The atomic load is to close a race window with setting the typefilter
1729 * and memory entry values. A description follows:
1733 * Allocate Typefilter
1734 * Allocate MemoryEntry
1735 * Write Global MemoryEntry Ptr
1736 * Atomic Store (Release) Global Typefilter Ptr
1738 * Thread 2 (reader, AKA us)
1740 * if ((Atomic Load (Acquire) Global Typefilter Ptr) == NULL)
1743 * Without the atomic store, it isn't guaranteed that the write of
1744 * Global MemoryEntry Ptr is visible before we can see the write of
1745 * Global Typefilter Ptr.
1747 * Without the atomic load, it isn't guaranteed that the loads of
1748 * Global MemoryEntry Ptr aren't speculated.
1750 * The global pointers transition from NULL -> valid once and only once,
1751 * and never change after becoming valid. This means that having passed
1752 * the first atomic load test of Global Typefilter Ptr, this function
1753 * can then safely use the remaining global state without atomic checks.
1755 if (!os_atomic_load(&kdbg_typefilter
, acquire
)) {
1759 assert(kdbg_typefilter_memory_entry
);
1761 mach_vm_offset_t user_addr
= 0;
1762 vm_map_t user_map
= current_map();
1764 ret
= mach_to_bsd_errno(
1765 mach_vm_map_kernel(user_map
, // target map
1766 &user_addr
, // [in, out] target address
1767 TYPEFILTER_ALLOC_SIZE
, // initial size
1768 0, // mask (alignment?)
1769 VM_FLAGS_ANYWHERE
, // flags
1770 VM_MAP_KERNEL_FLAGS_NONE
,
1771 VM_KERN_MEMORY_NONE
,
1772 kdbg_typefilter_memory_entry
, // port (memory entry!)
1773 0, // offset (in memory entry)
1774 false, // should copy
1775 VM_PROT_READ
, // cur_prot
1776 VM_PROT_READ
, // max_prot
1777 VM_INHERIT_SHARE
)); // inherit behavior on fork
1779 if (ret
== KERN_SUCCESS
) {
1780 vm_size_t user_ptr_size
= vm_map_is_64bit(user_map
) ? 8 : 4;
1781 ret
= copyout(CAST_DOWN(void *, &user_addr
), uap
->addr
, user_ptr_size
);
1783 if (ret
!= KERN_SUCCESS
) {
1784 mach_vm_deallocate(user_map
, user_addr
, TYPEFILTER_ALLOC_SIZE
);
1792 * Support syscall SYS_kdebug_trace. U64->K32 args may get truncated in kdebug_trace64
1795 kdebug_trace(struct proc
*p
, struct kdebug_trace_args
*uap
, int32_t *retval
)
1797 struct kdebug_trace64_args uap64
;
1799 uap64
.code
= uap
->code
;
1800 uap64
.arg1
= uap
->arg1
;
1801 uap64
.arg2
= uap
->arg2
;
1802 uap64
.arg3
= uap
->arg3
;
1803 uap64
.arg4
= uap
->arg4
;
1805 return kdebug_trace64(p
, &uap64
, retval
);
1809 * Support syscall SYS_kdebug_trace64. 64-bit args on K32 will get truncated
1810 * to fit in 32-bit record format.
1812 * It is intentional that error conditions are not checked until kdebug is
1813 * enabled. This is to match the userspace wrapper behavior, which is optimizing
1814 * for non-error case performance.
1817 kdebug_trace64(__unused
struct proc
*p
, struct kdebug_trace64_args
*uap
, __unused
int32_t *retval
)
1821 if (__probable(kdebug_enable
== 0)) {
1825 if ((err
= kdebug_validate_debugid(uap
->code
)) != 0) {
1829 kernel_debug_internal(uap
->code
, (uintptr_t)uap
->arg1
,
1830 (uintptr_t)uap
->arg2
, (uintptr_t)uap
->arg3
, (uintptr_t)uap
->arg4
,
1831 (uintptr_t)thread_tid(current_thread()), 0);
1837 * Adding enough padding to contain a full tracepoint for the last
1838 * portion of the string greatly simplifies the logic of splitting the
1839 * string between tracepoints. Full tracepoints can be generated using
1840 * the buffer itself, without having to manually add zeros to pad the
1844 /* 2 string args in first tracepoint and 9 string data tracepoints */
1845 #define STR_BUF_ARGS (2 + (9 * 4))
1846 /* times the size of each arg on K64 */
1847 #define MAX_STR_LEN (STR_BUF_ARGS * sizeof(uint64_t))
1848 /* on K32, ending straddles a tracepoint, so reserve blanks */
1849 #define STR_BUF_SIZE (MAX_STR_LEN + (2 * sizeof(uint32_t)))
1852 * This function does no error checking and assumes that it is called with
1853 * the correct arguments, including that the buffer pointed to by str is at
1854 * least STR_BUF_SIZE bytes. However, str must be aligned to word-size and
1855 * be NUL-terminated. In cases where a string can fit evenly into a final
1856 * tracepoint without its NUL-terminator, this function will not end those
1857 * strings with a NUL in trace. It's up to clients to look at the function
1858 * qualifier for DBG_FUNC_END in this case, to end the string.
1861 kernel_debug_string_internal(uint32_t debugid
, uint64_t str_id
, void *vstr
,
1864 /* str must be word-aligned */
1865 uintptr_t *str
= vstr
;
1867 uintptr_t thread_id
;
1869 uint32_t trace_debugid
= TRACEDBG_CODE(DBG_TRACE_STRING
,
1870 TRACE_STRING_GLOBAL
);
1872 thread_id
= (uintptr_t)thread_tid(current_thread());
1874 /* if the ID is being invalidated, just emit that */
1875 if (str_id
!= 0 && str_len
== 0) {
1876 kernel_debug_internal(trace_debugid
| DBG_FUNC_START
| DBG_FUNC_END
,
1877 (uintptr_t)debugid
, (uintptr_t)str_id
, 0, 0, thread_id
, 0);
1881 /* generate an ID, if necessary */
1883 str_id
= OSIncrementAtomic64((SInt64
*)&g_curr_str_id
);
1884 str_id
= (str_id
& STR_ID_MASK
) | g_str_id_signature
;
1887 trace_debugid
|= DBG_FUNC_START
;
1888 /* string can fit in a single tracepoint */
1889 if (str_len
<= (2 * sizeof(uintptr_t))) {
1890 trace_debugid
|= DBG_FUNC_END
;
1893 kernel_debug_internal(trace_debugid
, (uintptr_t)debugid
, (uintptr_t)str_id
,
1894 str
[0], str
[1], thread_id
, 0);
1896 trace_debugid
&= KDBG_EVENTID_MASK
;
1898 written
+= 2 * sizeof(uintptr_t);
1900 for (; written
< str_len
; i
+= 4, written
+= 4 * sizeof(uintptr_t)) {
1901 if ((written
+ (4 * sizeof(uintptr_t))) >= str_len
) {
1902 trace_debugid
|= DBG_FUNC_END
;
1904 kernel_debug_internal(trace_debugid
, str
[i
],
1907 str
[i
+ 3], thread_id
, 0);
1914 * Returns true if the current process can emit events, and false otherwise.
1915 * Trace system and scheduling events circumvent this check, as do events
1916 * emitted in interrupt context.
1919 kdebug_current_proc_enabled(uint32_t debugid
)
1921 /* can't determine current process in interrupt context */
1922 if (ml_at_interrupt_context()) {
1926 /* always emit trace system and scheduling events */
1927 if ((KDBG_EXTRACT_CLASS(debugid
) == DBG_TRACE
||
1928 (debugid
& KDBG_CSC_MASK
) == MACHDBG_CODE(DBG_MACH_SCHED
, 0))) {
1932 if (kd_ctrl_page
.kdebug_flags
& KDBG_PIDCHECK
) {
1933 proc_t cur_proc
= current_proc();
1935 /* only the process with the kdebug bit set is allowed */
1936 if (cur_proc
&& !(cur_proc
->p_kdebug
)) {
1939 } else if (kd_ctrl_page
.kdebug_flags
& KDBG_PIDEXCLUDE
) {
1940 proc_t cur_proc
= current_proc();
1942 /* every process except the one with the kdebug bit set is allowed */
1943 if (cur_proc
&& cur_proc
->p_kdebug
) {
1952 kdebug_debugid_enabled(uint32_t debugid
)
1954 /* if no filtering is enabled */
1955 if (!kd_ctrl_page
.kdebug_slowcheck
) {
1959 return kdebug_debugid_explicitly_enabled(debugid
);
1963 kdebug_debugid_explicitly_enabled(uint32_t debugid
)
1965 if (kd_ctrl_page
.kdebug_flags
& KDBG_TYPEFILTER_CHECK
) {
1966 return typefilter_is_debugid_allowed(kdbg_typefilter
, debugid
);
1967 } else if (KDBG_EXTRACT_CLASS(debugid
) == DBG_TRACE
) {
1969 } else if (kd_ctrl_page
.kdebug_flags
& KDBG_RANGECHECK
) {
1970 if (debugid
< kdlog_beg
|| debugid
> kdlog_end
) {
1973 } else if (kd_ctrl_page
.kdebug_flags
& KDBG_VALCHECK
) {
1974 if ((debugid
& KDBG_EVENTID_MASK
) != kdlog_value1
&&
1975 (debugid
& KDBG_EVENTID_MASK
) != kdlog_value2
&&
1976 (debugid
& KDBG_EVENTID_MASK
) != kdlog_value3
&&
1977 (debugid
& KDBG_EVENTID_MASK
) != kdlog_value4
) {
1986 kdebug_using_continuous_time(void)
1988 return kdebug_enable
& KDEBUG_ENABLE_CONT_TIME
;
1992 * Returns 0 if a string can be traced with these arguments. Returns errno
1993 * value if error occurred.
1996 kdebug_check_trace_string(uint32_t debugid
, uint64_t str_id
)
1998 /* if there are function qualifiers on the debugid */
1999 if (debugid
& ~KDBG_EVENTID_MASK
) {
2003 if (kdebug_validate_debugid(debugid
)) {
2007 if (str_id
!= 0 && (str_id
& STR_ID_SIG_MASK
) != g_str_id_signature
) {
2015 * Implementation of KPI kernel_debug_string.
2018 kernel_debug_string(uint32_t debugid
, uint64_t *str_id
, const char *str
)
2020 /* arguments to tracepoints must be word-aligned */
2021 __attribute__((aligned(sizeof(uintptr_t)))) char str_buf
[STR_BUF_SIZE
];
2022 static_assert(sizeof(str_buf
) > MAX_STR_LEN
);
2023 vm_size_t len_copied
;
2028 if (__probable(kdebug_enable
== 0)) {
2032 if (!kdebug_current_proc_enabled(debugid
)) {
2036 if (!kdebug_debugid_enabled(debugid
)) {
2040 if ((err
= kdebug_check_trace_string(debugid
, *str_id
)) != 0) {
2049 *str_id
= kernel_debug_string_internal(debugid
, *str_id
, NULL
, 0);
2053 memset(str_buf
, 0, sizeof(str_buf
));
2054 len_copied
= strlcpy(str_buf
, str
, MAX_STR_LEN
+ 1);
2055 *str_id
= kernel_debug_string_internal(debugid
, *str_id
, str_buf
,
2061 * Support syscall kdebug_trace_string.
2064 kdebug_trace_string(__unused
struct proc
*p
,
2065 struct kdebug_trace_string_args
*uap
,
2068 __attribute__((aligned(sizeof(uintptr_t)))) char str_buf
[STR_BUF_SIZE
];
2069 static_assert(sizeof(str_buf
) > MAX_STR_LEN
);
2073 if (__probable(kdebug_enable
== 0)) {
2077 if (!kdebug_current_proc_enabled(uap
->debugid
)) {
2081 if (!kdebug_debugid_enabled(uap
->debugid
)) {
2085 if ((err
= kdebug_check_trace_string(uap
->debugid
, uap
->str_id
)) != 0) {
2089 if (uap
->str
== USER_ADDR_NULL
) {
2090 if (uap
->str_id
== 0) {
2094 *retval
= kernel_debug_string_internal(uap
->debugid
, uap
->str_id
,
2099 memset(str_buf
, 0, sizeof(str_buf
));
2100 err
= copyinstr(uap
->str
, str_buf
, MAX_STR_LEN
+ 1, &len_copied
);
2102 /* it's alright to truncate the string, so allow ENAMETOOLONG */
2103 if (err
== ENAMETOOLONG
) {
2104 str_buf
[MAX_STR_LEN
] = '\0';
2109 if (len_copied
<= 1) {
2113 /* convert back to a length */
2116 *retval
= kernel_debug_string_internal(uap
->debugid
, uap
->str_id
, str_buf
,
2122 kdbg_lock_init(void)
2124 static lck_grp_attr_t
*kdebug_lck_grp_attr
= NULL
;
2125 static lck_attr_t
*kdebug_lck_attr
= NULL
;
2127 if (kd_ctrl_page
.kdebug_flags
& KDBG_LOCKINIT
) {
2131 assert(kdebug_lck_grp_attr
== NULL
);
2132 kdebug_lck_grp_attr
= lck_grp_attr_alloc_init();
2133 kdebug_lck_grp
= lck_grp_alloc_init("kdebug", kdebug_lck_grp_attr
);
2134 kdebug_lck_attr
= lck_attr_alloc_init();
2136 kds_spin_lock
= lck_spin_alloc_init(kdebug_lck_grp
, kdebug_lck_attr
);
2137 kdw_spin_lock
= lck_spin_alloc_init(kdebug_lck_grp
, kdebug_lck_attr
);
2139 kd_ctrl_page
.kdebug_flags
|= KDBG_LOCKINIT
;
2143 kdbg_bootstrap(bool early_trace
)
2145 kd_ctrl_page
.kdebug_flags
&= ~KDBG_WRAPPED
;
2147 return create_buffers(early_trace
);
2151 kdbg_reinit(bool early_trace
)
2156 * Disable trace collecting
2157 * First make sure we're not in
2158 * the middle of cutting a trace
2160 kernel_debug_disable();
2163 * make sure the SLOW_NOLOG is seen
2164 * by everyone that might be trying
2171 kdbg_clear_thread_map();
2172 ret
= kdbg_bootstrap(early_trace
);
2174 RAW_file_offset
= 0;
2175 RAW_file_written
= 0;
2181 kdbg_trace_data(struct proc
*proc
, long *arg_pid
, long *arg_uniqueid
)
2187 *arg_pid
= proc
->p_pid
;
2188 *arg_uniqueid
= proc
->p_uniqueid
;
2189 if ((uint64_t) *arg_uniqueid
!= proc
->p_uniqueid
) {
2197 kdbg_trace_string(struct proc
*proc
, long *arg1
, long *arg2
, long *arg3
,
2208 const char *procname
= proc_best_name(proc
);
2209 size_t namelen
= strlen(procname
);
2211 long args
[4] = { 0 };
2213 if (namelen
> sizeof(args
)) {
2214 namelen
= sizeof(args
);
2217 strncpy((char *)args
, procname
, namelen
);
2226 kdbg_resolve_map(thread_t th_act
, void *opaque
)
2228 kd_threadmap
*mapptr
;
2229 krt_t
*t
= (krt_t
*)opaque
;
2231 if (t
->count
< t
->maxcount
) {
2232 mapptr
= &t
->map
[t
->count
];
2233 mapptr
->thread
= (uintptr_t)thread_tid(th_act
);
2235 (void) strlcpy(mapptr
->command
, t
->atts
->task_comm
,
2236 sizeof(t
->atts
->task_comm
));
2238 * Some kernel threads have no associated pid.
2239 * We still need to mark the entry as valid.
2242 mapptr
->valid
= t
->atts
->pid
;
2253 * Writes a cpumap for the given iops_list/cpu_count to the provided buffer.
2255 * You may provide a buffer and size, or if you set the buffer to NULL, a
2256 * buffer of sufficient size will be allocated.
2258 * If you provide a buffer and it is too small, sets cpumap_size to the number
2259 * of bytes required and returns EINVAL.
2261 * On success, if you provided a buffer, cpumap_size is set to the number of
2262 * bytes written. If you did not provide a buffer, cpumap is set to the newly
2263 * allocated buffer and cpumap_size is set to the number of bytes allocated.
2265 * NOTE: It may seem redundant to pass both iops and a cpu_count.
2267 * We may be reporting data from "now", or from the "past".
2269 * The "past" data would be for kdbg_readcpumap().
2271 * If we do not pass both iops and cpu_count, and iops is NULL, this function
2272 * will need to read "now" state to get the number of cpus, which would be in
2273 * error if we were reporting "past" state.
2277 kdbg_cpumap_init_internal(kd_iop_t
* iops
, uint32_t cpu_count
, uint8_t** cpumap
, uint32_t* cpumap_size
)
2280 assert(cpumap_size
);
2282 assert(!iops
|| iops
->cpu_id
+ 1 == cpu_count
);
2284 uint32_t bytes_needed
= sizeof(kd_cpumap_header
) + cpu_count
* sizeof(kd_cpumap
);
2285 uint32_t bytes_available
= *cpumap_size
;
2286 *cpumap_size
= bytes_needed
;
2288 if (*cpumap
== NULL
) {
2289 if (kmem_alloc(kernel_map
, (vm_offset_t
*)cpumap
, (vm_size_t
)*cpumap_size
, VM_KERN_MEMORY_DIAG
) != KERN_SUCCESS
) {
2292 bzero(*cpumap
, *cpumap_size
);
2293 } else if (bytes_available
< bytes_needed
) {
2297 kd_cpumap_header
* header
= (kd_cpumap_header
*)(uintptr_t)*cpumap
;
2299 header
->version_no
= RAW_VERSION1
;
2300 header
->cpu_count
= cpu_count
;
2302 kd_cpumap
* cpus
= (kd_cpumap
*)&header
[1];
2304 int32_t index
= cpu_count
- 1;
2306 cpus
[index
].cpu_id
= iops
->cpu_id
;
2307 cpus
[index
].flags
= KDBG_CPUMAP_IS_IOP
;
2308 strlcpy(cpus
[index
].name
, iops
->callback
.iop_name
, sizeof(cpus
->name
));
2314 while (index
>= 0) {
2315 cpus
[index
].cpu_id
= index
;
2316 cpus
[index
].flags
= 0;
2317 strlcpy(cpus
[index
].name
, "AP", sizeof(cpus
->name
));
2322 return KERN_SUCCESS
;
2326 kdbg_thrmap_init(void)
2328 ktrace_assert_lock_held();
2330 if (kd_ctrl_page
.kdebug_flags
& KDBG_MAPINIT
) {
2334 kd_mapptr
= kdbg_thrmap_init_internal(0, &kd_mapsize
, &kd_mapcount
);
2337 kd_ctrl_page
.kdebug_flags
|= KDBG_MAPINIT
;
2341 static kd_threadmap
*
2342 kdbg_thrmap_init_internal(unsigned int count
, unsigned int *mapsize
, unsigned int *mapcount
)
2344 kd_threadmap
*mapptr
;
2347 int tts_count
= 0; /* number of task-to-string structures */
2348 struct tts
*tts_mapptr
;
2349 unsigned int tts_mapsize
= 0;
2352 assert(mapsize
!= NULL
);
2353 assert(mapcount
!= NULL
);
2355 *mapcount
= threads_count
;
2356 tts_count
= tasks_count
;
2359 * The proc count could change during buffer allocation,
2360 * so introduce a small fudge factor to bump up the
2361 * buffer sizes. This gives new tasks some chance of
2362 * making into the tables. Bump up by 25%.
2364 *mapcount
+= *mapcount
/ 4;
2365 tts_count
+= tts_count
/ 4;
2367 *mapsize
= *mapcount
* sizeof(kd_threadmap
);
2369 if (count
&& count
< *mapcount
) {
2373 if ((kmem_alloc(kernel_map
, &kaddr
, (vm_size_t
)*mapsize
, VM_KERN_MEMORY_DIAG
) == KERN_SUCCESS
)) {
2374 bzero((void *)kaddr
, *mapsize
);
2375 mapptr
= (kd_threadmap
*)kaddr
;
2380 tts_mapsize
= tts_count
* sizeof(struct tts
);
2382 if ((kmem_alloc(kernel_map
, &kaddr
, (vm_size_t
)tts_mapsize
, VM_KERN_MEMORY_DIAG
) == KERN_SUCCESS
)) {
2383 bzero((void *)kaddr
, tts_mapsize
);
2384 tts_mapptr
= (struct tts
*)kaddr
;
2386 kmem_free(kernel_map
, (vm_offset_t
)mapptr
, *mapsize
);
2392 * Save the proc's name and take a reference for each task associated
2393 * with a valid process.
2398 ALLPROC_FOREACH(p
) {
2399 if (i
>= tts_count
) {
2402 if (p
->p_lflag
& P_LEXIT
) {
2406 task_reference(p
->task
);
2407 tts_mapptr
[i
].task
= p
->task
;
2408 tts_mapptr
[i
].pid
= p
->p_pid
;
2409 (void)strlcpy(tts_mapptr
[i
].task_comm
, proc_best_name(p
), sizeof(tts_mapptr
[i
].task_comm
));
2418 * Initialize thread map data
2422 akrt
.maxcount
= *mapcount
;
2424 for (i
= 0; i
< tts_count
; i
++) {
2425 akrt
.atts
= &tts_mapptr
[i
];
2426 task_act_iterate_wth_args(tts_mapptr
[i
].task
, kdbg_resolve_map
, &akrt
);
2427 task_deallocate((task_t
)tts_mapptr
[i
].task
);
2429 kmem_free(kernel_map
, (vm_offset_t
)tts_mapptr
, tts_mapsize
);
2431 *mapcount
= akrt
.count
;
2440 * Clean up the trace buffer
2441 * First make sure we're not in
2442 * the middle of cutting a trace
2444 kernel_debug_disable();
2445 kdbg_disable_typefilter();
2448 * make sure the SLOW_NOLOG is seen
2449 * by everyone that might be trying
2454 /* reset kdebug state for each process */
2455 if (kd_ctrl_page
.kdebug_flags
& (KDBG_PIDCHECK
| KDBG_PIDEXCLUDE
)) {
2458 ALLPROC_FOREACH(p
) {
2464 kd_ctrl_page
.kdebug_flags
&= (unsigned int)~KDBG_CKTYPES
;
2465 kd_ctrl_page
.kdebug_flags
&= ~(KDBG_NOWRAP
| KDBG_RANGECHECK
| KDBG_VALCHECK
);
2466 kd_ctrl_page
.kdebug_flags
&= ~(KDBG_PIDCHECK
| KDBG_PIDEXCLUDE
);
2468 kd_ctrl_page
.oldest_time
= 0;
2473 /* Clean up the thread map buffer */
2474 kdbg_clear_thread_map();
2476 RAW_file_offset
= 0;
2477 RAW_file_written
= 0;
2483 ktrace_assert_lock_held();
2488 if (kdbg_typefilter
) {
2489 typefilter_reject_all(kdbg_typefilter
);
2490 typefilter_allow_class(kdbg_typefilter
, DBG_TRACE
);
2495 kdebug_free_early_buf(void)
2497 #if !CONFIG_EMBEDDED
2498 /* Must be done with the buffer, so release it back to the VM.
2499 * On embedded targets this buffer is freed when the BOOTDATA segment is freed. */
2500 ml_static_mfree((vm_offset_t
)&kd_early_buffer
, sizeof(kd_early_buffer
));
2505 kdbg_setpid(kd_regtype
*kdr
)
2511 pid
= (pid_t
)kdr
->value1
;
2512 flag
= (int)kdr
->value2
;
2515 if ((p
= proc_find(pid
)) == NULL
) {
2520 * turn on pid check for this and all pids
2522 kd_ctrl_page
.kdebug_flags
|= KDBG_PIDCHECK
;
2523 kd_ctrl_page
.kdebug_flags
&= ~KDBG_PIDEXCLUDE
;
2524 kdbg_set_flags(SLOW_CHECKS
, 0, true);
2529 * turn off pid check for this pid value
2530 * Don't turn off all pid checking though
2532 * kd_ctrl_page.kdebug_flags &= ~KDBG_PIDCHECK;
2545 /* This is for pid exclusion in the trace buffer */
2547 kdbg_setpidex(kd_regtype
*kdr
)
2553 pid
= (pid_t
)kdr
->value1
;
2554 flag
= (int)kdr
->value2
;
2557 if ((p
= proc_find(pid
)) == NULL
) {
2562 * turn on pid exclusion
2564 kd_ctrl_page
.kdebug_flags
|= KDBG_PIDEXCLUDE
;
2565 kd_ctrl_page
.kdebug_flags
&= ~KDBG_PIDCHECK
;
2566 kdbg_set_flags(SLOW_CHECKS
, 0, true);
2571 * turn off pid exclusion for this pid value
2572 * Don't turn off all pid exclusion though
2574 * kd_ctrl_page.kdebug_flags &= ~KDBG_PIDEXCLUDE;
2588 * The following functions all operate on the "global" typefilter singleton.
2592 * The tf param is optional, you may pass either a valid typefilter or NULL.
2593 * If you pass a valid typefilter, you release ownership of that typefilter.
2596 kdbg_initialize_typefilter(typefilter_t tf
)
2598 ktrace_assert_lock_held();
2599 assert(!kdbg_typefilter
);
2600 assert(!kdbg_typefilter_memory_entry
);
2601 typefilter_t deallocate_tf
= NULL
;
2603 if (!tf
&& ((tf
= deallocate_tf
= typefilter_create()) == NULL
)) {
2607 if ((kdbg_typefilter_memory_entry
= typefilter_create_memory_entry(tf
)) == MACH_PORT_NULL
) {
2608 if (deallocate_tf
) {
2609 typefilter_deallocate(deallocate_tf
);
2615 * The atomic store closes a race window with
2616 * the kdebug_typefilter syscall, which assumes
2617 * that any non-null kdbg_typefilter means a
2618 * valid memory_entry is available.
2620 os_atomic_store(&kdbg_typefilter
, tf
, release
);
2622 return KERN_SUCCESS
;
2626 kdbg_copyin_typefilter(user_addr_t addr
, size_t size
)
2631 ktrace_assert_lock_held();
2633 if (size
!= KDBG_TYPEFILTER_BITMAP_SIZE
) {
2637 if ((tf
= typefilter_create())) {
2638 if ((ret
= copyin(addr
, tf
, KDBG_TYPEFILTER_BITMAP_SIZE
)) == 0) {
2639 /* The kernel typefilter must always allow DBG_TRACE */
2640 typefilter_allow_class(tf
, DBG_TRACE
);
2643 * If this is the first typefilter; claim it.
2644 * Otherwise copy and deallocate.
2646 * Allocating a typefilter for the copyin allows
2647 * the kernel to hold the invariant that DBG_TRACE
2648 * must always be allowed.
2650 if (!kdbg_typefilter
) {
2651 if ((ret
= kdbg_initialize_typefilter(tf
))) {
2656 typefilter_copy(kdbg_typefilter
, tf
);
2659 kdbg_enable_typefilter();
2660 kdbg_iop_list_callback(kd_ctrl_page
.kdebug_iops
, KD_CALLBACK_TYPEFILTER_CHANGED
, kdbg_typefilter
);
2664 typefilter_deallocate(tf
);
2672 * Enable the flags in the control page for the typefilter. Assumes that
2673 * kdbg_typefilter has already been allocated, so events being written
2674 * don't see a bad typefilter.
2677 kdbg_enable_typefilter(void)
2679 assert(kdbg_typefilter
);
2680 kd_ctrl_page
.kdebug_flags
&= ~(KDBG_RANGECHECK
| KDBG_VALCHECK
);
2681 kd_ctrl_page
.kdebug_flags
|= KDBG_TYPEFILTER_CHECK
;
2682 kdbg_set_flags(SLOW_CHECKS
, 0, true);
2683 commpage_update_kdebug_state();
2687 * Disable the flags in the control page for the typefilter. The typefilter
2688 * may be safely deallocated shortly after this function returns.
2691 kdbg_disable_typefilter(void)
2693 bool notify_iops
= kd_ctrl_page
.kdebug_flags
& KDBG_TYPEFILTER_CHECK
;
2694 kd_ctrl_page
.kdebug_flags
&= ~KDBG_TYPEFILTER_CHECK
;
2696 if ((kd_ctrl_page
.kdebug_flags
& (KDBG_PIDCHECK
| KDBG_PIDEXCLUDE
))) {
2697 kdbg_set_flags(SLOW_CHECKS
, 0, true);
2699 kdbg_set_flags(SLOW_CHECKS
, 0, false);
2701 commpage_update_kdebug_state();
2705 * Notify IOPs that the typefilter will now allow everything.
2706 * Otherwise, they won't know a typefilter is no longer in
2709 typefilter_allow_all(kdbg_typefilter
);
2710 kdbg_iop_list_callback(kd_ctrl_page
.kdebug_iops
,
2711 KD_CALLBACK_TYPEFILTER_CHANGED
, kdbg_typefilter
);
2716 kdebug_commpage_state(void)
2718 if (kdebug_enable
) {
2719 if (kd_ctrl_page
.kdebug_flags
& KDBG_TYPEFILTER_CHECK
) {
2720 return KDEBUG_COMMPAGE_ENABLE_TYPEFILTER
| KDEBUG_COMMPAGE_ENABLE_TRACE
;
2723 return KDEBUG_COMMPAGE_ENABLE_TRACE
;
2730 kdbg_setreg(kd_regtype
* kdr
)
2733 unsigned int val_1
, val_2
, val
;
2734 switch (kdr
->type
) {
2735 case KDBG_CLASSTYPE
:
2736 val_1
= (kdr
->value1
& 0xff);
2737 val_2
= (kdr
->value2
& 0xff);
2738 kdlog_beg
= (val_1
<< 24);
2739 kdlog_end
= (val_2
<< 24);
2740 kd_ctrl_page
.kdebug_flags
&= (unsigned int)~KDBG_CKTYPES
;
2741 kd_ctrl_page
.kdebug_flags
&= ~KDBG_VALCHECK
; /* Turn off specific value check */
2742 kd_ctrl_page
.kdebug_flags
|= (KDBG_RANGECHECK
| KDBG_CLASSTYPE
);
2743 kdbg_set_flags(SLOW_CHECKS
, 0, true);
2745 case KDBG_SUBCLSTYPE
:
2746 val_1
= (kdr
->value1
& 0xff);
2747 val_2
= (kdr
->value2
& 0xff);
2749 kdlog_beg
= ((val_1
<< 24) | (val_2
<< 16));
2750 kdlog_end
= ((val_1
<< 24) | (val
<< 16));
2751 kd_ctrl_page
.kdebug_flags
&= (unsigned int)~KDBG_CKTYPES
;
2752 kd_ctrl_page
.kdebug_flags
&= ~KDBG_VALCHECK
; /* Turn off specific value check */
2753 kd_ctrl_page
.kdebug_flags
|= (KDBG_RANGECHECK
| KDBG_SUBCLSTYPE
);
2754 kdbg_set_flags(SLOW_CHECKS
, 0, true);
2756 case KDBG_RANGETYPE
:
2757 kdlog_beg
= (kdr
->value1
);
2758 kdlog_end
= (kdr
->value2
);
2759 kd_ctrl_page
.kdebug_flags
&= (unsigned int)~KDBG_CKTYPES
;
2760 kd_ctrl_page
.kdebug_flags
&= ~KDBG_VALCHECK
; /* Turn off specific value check */
2761 kd_ctrl_page
.kdebug_flags
|= (KDBG_RANGECHECK
| KDBG_RANGETYPE
);
2762 kdbg_set_flags(SLOW_CHECKS
, 0, true);
2765 kdlog_value1
= (kdr
->value1
);
2766 kdlog_value2
= (kdr
->value2
);
2767 kdlog_value3
= (kdr
->value3
);
2768 kdlog_value4
= (kdr
->value4
);
2769 kd_ctrl_page
.kdebug_flags
&= (unsigned int)~KDBG_CKTYPES
;
2770 kd_ctrl_page
.kdebug_flags
&= ~KDBG_RANGECHECK
; /* Turn off range check */
2771 kd_ctrl_page
.kdebug_flags
|= KDBG_VALCHECK
; /* Turn on specific value check */
2772 kdbg_set_flags(SLOW_CHECKS
, 0, true);
2775 kd_ctrl_page
.kdebug_flags
&= (unsigned int)~KDBG_CKTYPES
;
2777 if ((kd_ctrl_page
.kdebug_flags
& (KDBG_RANGECHECK
| KDBG_VALCHECK
|
2778 KDBG_PIDCHECK
| KDBG_PIDEXCLUDE
|
2779 KDBG_TYPEFILTER_CHECK
))) {
2780 kdbg_set_flags(SLOW_CHECKS
, 0, true);
2782 kdbg_set_flags(SLOW_CHECKS
, 0, false);
2796 kdbg_write_to_vnode(caddr_t buffer
, size_t size
, vnode_t vp
, vfs_context_t ctx
, off_t file_offset
)
2798 return vn_rdwr(UIO_WRITE
, vp
, buffer
, size
, file_offset
, UIO_SYSSPACE
, IO_NODELOCKED
| IO_UNIT
,
2799 vfs_context_ucred(ctx
), (int *) 0, vfs_context_proc(ctx
));
2803 kdbg_write_v3_chunk_header(user_addr_t buffer
, uint32_t tag
, uint32_t sub_tag
, uint64_t length
, vnode_t vp
, vfs_context_t ctx
)
2805 int ret
= KERN_SUCCESS
;
2806 kd_chunk_header_v3 header
= {
2812 // Check that only one of them is valid
2813 assert(!buffer
^ !vp
);
2814 assert((vp
== NULL
) || (ctx
!= NULL
));
2816 // Write the 8-byte future_chunk_timestamp field in the payload
2819 ret
= kdbg_write_to_vnode((caddr_t
)&header
, sizeof(kd_chunk_header_v3
), vp
, ctx
, RAW_file_offset
);
2823 RAW_file_offset
+= (sizeof(kd_chunk_header_v3
));
2825 ret
= copyout(&header
, buffer
, sizeof(kd_chunk_header_v3
));
2836 kdbg_write_v3_chunk_to_fd(uint32_t tag
, uint32_t sub_tag
, uint64_t length
, void *payload
, uint64_t payload_size
, int fd
)
2839 struct vfs_context context
;
2840 struct fileproc
*fp
;
2845 if ((fp_lookup(p
, fd
, &fp
, 1))) {
2850 context
.vc_thread
= current_thread();
2851 context
.vc_ucred
= fp
->f_fglob
->fg_cred
;
2853 if (FILEGLOB_DTYPE(fp
->f_fglob
) != DTYPE_VNODE
) {
2854 fp_drop(p
, fd
, fp
, 1);
2858 vp
= (struct vnode
*) fp
->f_fglob
->fg_data
;
2861 if ((vnode_getwithref(vp
)) == 0) {
2862 RAW_file_offset
= fp
->f_fglob
->fg_offset
;
2864 kd_chunk_header_v3 chunk_header
= {
2870 int ret
= kdbg_write_to_vnode((caddr_t
) &chunk_header
, sizeof(kd_chunk_header_v3
), vp
, &context
, RAW_file_offset
);
2872 RAW_file_offset
+= sizeof(kd_chunk_header_v3
);
2875 ret
= kdbg_write_to_vnode((caddr_t
) payload
, (size_t) payload_size
, vp
, &context
, RAW_file_offset
);
2877 RAW_file_offset
+= payload_size
;
2880 fp
->f_fglob
->fg_offset
= RAW_file_offset
;
2884 fp_drop(p
, fd
, fp
, 0);
2885 return KERN_SUCCESS
;
2889 kdbg_write_v3_event_chunk_header(user_addr_t buffer
, uint32_t tag
, uint64_t length
, vnode_t vp
, vfs_context_t ctx
)
2891 uint64_t future_chunk_timestamp
= 0;
2892 length
+= sizeof(uint64_t);
2894 if (kdbg_write_v3_chunk_header(buffer
, tag
, V3_EVENT_DATA_VERSION
, length
, vp
, ctx
)) {
2898 buffer
+= sizeof(kd_chunk_header_v3
);
2901 // Check that only one of them is valid
2902 assert(!buffer
^ !vp
);
2903 assert((vp
== NULL
) || (ctx
!= NULL
));
2905 // Write the 8-byte future_chunk_timestamp field in the payload
2908 int ret
= kdbg_write_to_vnode((caddr_t
)&future_chunk_timestamp
, sizeof(uint64_t), vp
, ctx
, RAW_file_offset
);
2910 RAW_file_offset
+= (sizeof(uint64_t));
2913 if (copyout(&future_chunk_timestamp
, buffer
, sizeof(uint64_t))) {
2919 return buffer
+ sizeof(uint64_t);
2923 kdbg_write_v3_header(user_addr_t user_header
, size_t *user_header_size
, int fd
)
2925 int ret
= KERN_SUCCESS
;
2927 uint8_t* cpumap
= 0;
2928 uint32_t cpumap_size
= 0;
2929 uint32_t thrmap_size
= 0;
2931 size_t bytes_needed
= 0;
2933 // Check that only one of them is valid
2934 assert(!user_header
^ !fd
);
2935 assert(user_header_size
);
2937 if (!(kd_ctrl_page
.kdebug_flags
& KDBG_BUFINIT
)) {
2942 if (!(user_header
|| fd
)) {
2947 // Initialize the cpu map
2948 ret
= kdbg_cpumap_init_internal(kd_ctrl_page
.kdebug_iops
, kd_ctrl_page
.kdebug_cpus
, &cpumap
, &cpumap_size
);
2949 if (ret
!= KERN_SUCCESS
) {
2953 // Check if a thread map is initialized
2958 thrmap_size
= kd_mapcount
* sizeof(kd_threadmap
);
2960 mach_timebase_info_data_t timebase
= {0, 0};
2961 clock_timebase_info(&timebase
);
2963 // Setup the header.
2964 // See v3 header description in sys/kdebug.h for more inforamtion.
2965 kd_header_v3 header
= {
2966 .tag
= RAW_VERSION3
,
2967 .sub_tag
= V3_HEADER_VERSION
,
2968 .length
= (sizeof(kd_header_v3
) + cpumap_size
- sizeof(kd_cpumap_header
)),
2969 .timebase_numer
= timebase
.numer
,
2970 .timebase_denom
= timebase
.denom
,
2971 .timestamp
= 0, /* FIXME rdar://problem/22053009 */
2973 .walltime_usecs
= 0,
2974 .timezone_minuteswest
= 0,
2976 #if defined(__LP64__)
2983 // If its a buffer, check if we have enough space to copy the header and the maps.
2985 bytes_needed
= header
.length
+ thrmap_size
+ (2 * sizeof(kd_chunk_header_v3
));
2986 if (*user_header_size
< bytes_needed
) {
2992 // Start writing the header
2994 void *hdr_ptr
= (void *)(((uintptr_t) &header
) + sizeof(kd_chunk_header_v3
));
2995 size_t payload_size
= (sizeof(kd_header_v3
) - sizeof(kd_chunk_header_v3
));
2997 ret
= kdbg_write_v3_chunk_to_fd(RAW_VERSION3
, V3_HEADER_VERSION
, header
.length
, hdr_ptr
, payload_size
, fd
);
3002 if (copyout(&header
, user_header
, sizeof(kd_header_v3
))) {
3006 // Update the user pointer
3007 user_header
+= sizeof(kd_header_v3
);
3010 // Write a cpu map. This is a sub chunk of the header
3011 cpumap
= (uint8_t*)((uintptr_t) cpumap
+ sizeof(kd_cpumap_header
));
3012 size_t payload_size
= (size_t)(cpumap_size
- sizeof(kd_cpumap_header
));
3014 ret
= kdbg_write_v3_chunk_to_fd(V3_CPU_MAP
, V3_CPUMAP_VERSION
, payload_size
, (void *)cpumap
, payload_size
, fd
);
3019 ret
= kdbg_write_v3_chunk_header(user_header
, V3_CPU_MAP
, V3_CPUMAP_VERSION
, payload_size
, NULL
, NULL
);
3023 user_header
+= sizeof(kd_chunk_header_v3
);
3024 if (copyout(cpumap
, user_header
, payload_size
)) {
3028 // Update the user pointer
3029 user_header
+= payload_size
;
3032 // Write a thread map
3034 ret
= kdbg_write_v3_chunk_to_fd(V3_THREAD_MAP
, V3_THRMAP_VERSION
, thrmap_size
, (void *)kd_mapptr
, thrmap_size
, fd
);
3039 ret
= kdbg_write_v3_chunk_header(user_header
, V3_THREAD_MAP
, V3_THRMAP_VERSION
, thrmap_size
, NULL
, NULL
);
3043 user_header
+= sizeof(kd_chunk_header_v3
);
3044 if (copyout(kd_mapptr
, user_header
, thrmap_size
)) {
3048 user_header
+= thrmap_size
;
3052 RAW_file_written
+= bytes_needed
;
3055 *user_header_size
= bytes_needed
;
3058 kmem_free(kernel_map
, (vm_offset_t
)cpumap
, cpumap_size
);
3064 kdbg_readcpumap(user_addr_t user_cpumap
, size_t *user_cpumap_size
)
3066 uint8_t* cpumap
= NULL
;
3067 uint32_t cpumap_size
= 0;
3068 int ret
= KERN_SUCCESS
;
3070 if (kd_ctrl_page
.kdebug_flags
& KDBG_BUFINIT
) {
3071 if (kdbg_cpumap_init_internal(kd_ctrl_page
.kdebug_iops
, kd_ctrl_page
.kdebug_cpus
, &cpumap
, &cpumap_size
) == KERN_SUCCESS
) {
3073 size_t bytes_to_copy
= (*user_cpumap_size
>= cpumap_size
) ? cpumap_size
: *user_cpumap_size
;
3074 if (copyout(cpumap
, user_cpumap
, (size_t)bytes_to_copy
)) {
3078 *user_cpumap_size
= cpumap_size
;
3079 kmem_free(kernel_map
, (vm_offset_t
)cpumap
, cpumap_size
);
3091 kdbg_readcurthrmap(user_addr_t buffer
, size_t *bufsize
)
3093 kd_threadmap
*mapptr
;
3094 unsigned int mapsize
;
3095 unsigned int mapcount
;
3096 unsigned int count
= 0;
3099 count
= *bufsize
/ sizeof(kd_threadmap
);
3102 if ((mapptr
= kdbg_thrmap_init_internal(count
, &mapsize
, &mapcount
))) {
3103 if (copyout(mapptr
, buffer
, mapcount
* sizeof(kd_threadmap
))) {
3106 *bufsize
= (mapcount
* sizeof(kd_threadmap
));
3109 kmem_free(kernel_map
, (vm_offset_t
)mapptr
, mapsize
);
3118 kdbg_write_v1_header(bool write_thread_map
, vnode_t vp
, vfs_context_t ctx
)
3126 uint32_t extra_thread_count
= 0;
3127 uint32_t cpumap_size
;
3128 size_t map_size
= 0;
3129 size_t map_count
= 0;
3131 if (write_thread_map
) {
3132 assert(kd_ctrl_page
.kdebug_flags
& KDBG_MAPINIT
);
3133 map_count
= kd_mapcount
;
3134 map_size
= map_count
* sizeof(kd_threadmap
);
3138 * Without the buffers initialized, we cannot construct a CPU map or a
3139 * thread map, and cannot write a header.
3141 if (!(kd_ctrl_page
.kdebug_flags
& KDBG_BUFINIT
)) {
3146 * To write a RAW_VERSION1+ file, we must embed a cpumap in the
3147 * "padding" used to page align the events following the threadmap. If
3148 * the threadmap happens to not require enough padding, we artificially
3149 * increase its footprint until it needs enough padding.
3155 pad_size
= PAGE_16KB
- ((sizeof(RAW_header
) + map_size
) & PAGE_MASK_64
);
3156 cpumap_size
= sizeof(kd_cpumap_header
) + kd_ctrl_page
.kdebug_cpus
* sizeof(kd_cpumap
);
3158 if (cpumap_size
> pad_size
) {
3159 /* If the cpu map doesn't fit in the current available pad_size,
3160 * we increase the pad_size by 16K. We do this so that the event
3161 * data is always available on a page aligned boundary for both
3162 * 4k and 16k systems. We enforce this alignment for the event
3163 * data so that we can take advantage of optimized file/disk writes.
3165 pad_size
+= PAGE_16KB
;
3168 /* The way we are silently embedding a cpumap in the "padding" is by artificially
3169 * increasing the number of thread entries. However, we'll also need to ensure that
3170 * the cpumap is embedded in the last 4K page before when the event data is expected.
3171 * This way the tools can read the data starting the next page boundary on both
3172 * 4K and 16K systems preserving compatibility with older versions of the tools
3174 if (pad_size
> PAGE_4KB
) {
3175 pad_size
-= PAGE_4KB
;
3176 extra_thread_count
= (pad_size
/ sizeof(kd_threadmap
)) + 1;
3179 memset(&header
, 0, sizeof(header
));
3180 header
.version_no
= RAW_VERSION1
;
3181 header
.thread_count
= map_count
+ extra_thread_count
;
3183 clock_get_calendar_microtime(&secs
, &usecs
);
3184 header
.TOD_secs
= secs
;
3185 header
.TOD_usecs
= usecs
;
3187 ret
= vn_rdwr(UIO_WRITE
, vp
, (caddr_t
)&header
, sizeof(RAW_header
), RAW_file_offset
,
3188 UIO_SYSSPACE
, IO_NODELOCKED
| IO_UNIT
, vfs_context_ucred(ctx
), (int *) 0, vfs_context_proc(ctx
));
3192 RAW_file_offset
+= sizeof(RAW_header
);
3193 RAW_file_written
+= sizeof(RAW_header
);
3195 if (write_thread_map
) {
3196 ret
= vn_rdwr(UIO_WRITE
, vp
, (caddr_t
)kd_mapptr
, map_size
, RAW_file_offset
,
3197 UIO_SYSSPACE
, IO_NODELOCKED
| IO_UNIT
, vfs_context_ucred(ctx
), (int *) 0, vfs_context_proc(ctx
));
3202 RAW_file_offset
+= map_size
;
3203 RAW_file_written
+= map_size
;
3206 if (extra_thread_count
) {
3207 pad_size
= extra_thread_count
* sizeof(kd_threadmap
);
3208 pad_buf
= kalloc(pad_size
);
3213 memset(pad_buf
, 0, pad_size
);
3215 ret
= vn_rdwr(UIO_WRITE
, vp
, (caddr_t
)pad_buf
, pad_size
, RAW_file_offset
,
3216 UIO_SYSSPACE
, IO_NODELOCKED
| IO_UNIT
, vfs_context_ucred(ctx
), (int *) 0, vfs_context_proc(ctx
));
3217 kfree(pad_buf
, pad_size
);
3222 RAW_file_offset
+= pad_size
;
3223 RAW_file_written
+= pad_size
;
3226 pad_size
= PAGE_SIZE
- (RAW_file_offset
& PAGE_MASK_64
);
3228 pad_buf
= (char *)kalloc(pad_size
);
3233 memset(pad_buf
, 0, pad_size
);
3236 * embed a cpumap in the padding bytes.
3237 * older code will skip this.
3238 * newer code will know how to read it.
3240 uint32_t temp
= pad_size
;
3241 if (kdbg_cpumap_init_internal(kd_ctrl_page
.kdebug_iops
, kd_ctrl_page
.kdebug_cpus
, (uint8_t**)&pad_buf
, &temp
) != KERN_SUCCESS
) {
3242 memset(pad_buf
, 0, pad_size
);
3245 ret
= vn_rdwr(UIO_WRITE
, vp
, (caddr_t
)pad_buf
, pad_size
, RAW_file_offset
,
3246 UIO_SYSSPACE
, IO_NODELOCKED
| IO_UNIT
, vfs_context_ucred(ctx
), (int *) 0, vfs_context_proc(ctx
));
3247 kfree(pad_buf
, pad_size
);
3252 RAW_file_offset
+= pad_size
;
3253 RAW_file_written
+= pad_size
;
3261 kdbg_clear_thread_map(void)
3263 ktrace_assert_lock_held();
3265 if (kd_ctrl_page
.kdebug_flags
& KDBG_MAPINIT
) {
3266 assert(kd_mapptr
!= NULL
);
3267 kmem_free(kernel_map
, (vm_offset_t
)kd_mapptr
, kd_mapsize
);
3271 kd_ctrl_page
.kdebug_flags
&= ~KDBG_MAPINIT
;
3276 * Write out a version 1 header and the thread map, if it is initialized, to a
3277 * vnode. Used by KDWRITEMAP and kdbg_dump_trace_to_file.
3279 * Returns write errors from vn_rdwr if a write fails. Returns ENODATA if the
3280 * thread map has not been initialized, but the header will still be written.
3281 * Returns ENOMEM if padding could not be allocated. Returns 0 otherwise.
3284 kdbg_write_thread_map(vnode_t vp
, vfs_context_t ctx
)
3287 bool map_initialized
;
3289 ktrace_assert_lock_held();
3290 assert(ctx
!= NULL
);
3292 map_initialized
= (kd_ctrl_page
.kdebug_flags
& KDBG_MAPINIT
);
3294 ret
= kdbg_write_v1_header(map_initialized
, vp
, ctx
);
3296 if (map_initialized
) {
3297 kdbg_clear_thread_map();
3307 * Copy out the thread map to a user space buffer. Used by KDTHRMAP.
3309 * Returns copyout errors if the copyout fails. Returns ENODATA if the thread
3310 * map has not been initialized. Returns EINVAL if the buffer provided is not
3311 * large enough for the entire thread map. Returns 0 otherwise.
3314 kdbg_copyout_thread_map(user_addr_t buffer
, size_t *buffer_size
)
3316 bool map_initialized
;
3320 ktrace_assert_lock_held();
3321 assert(buffer_size
!= NULL
);
3323 map_initialized
= (kd_ctrl_page
.kdebug_flags
& KDBG_MAPINIT
);
3324 if (!map_initialized
) {
3328 map_size
= kd_mapcount
* sizeof(kd_threadmap
);
3329 if (*buffer_size
< map_size
) {
3333 ret
= copyout(kd_mapptr
, buffer
, map_size
);
3335 kdbg_clear_thread_map();
3342 kdbg_readthrmap_v3(user_addr_t buffer
, size_t buffer_size
, int fd
)
3345 bool map_initialized
;
3348 ktrace_assert_lock_held();
3350 if ((!fd
&& !buffer
) || (fd
&& buffer
)) {
3354 map_initialized
= (kd_ctrl_page
.kdebug_flags
& KDBG_MAPINIT
);
3355 map_size
= kd_mapcount
* sizeof(kd_threadmap
);
3357 if (map_initialized
&& (buffer_size
>= map_size
)) {
3358 ret
= kdbg_write_v3_header(buffer
, &buffer_size
, fd
);
3361 kdbg_clear_thread_map();
3371 kdbg_set_nkdbufs(unsigned int req_nkdbufs
)
3374 * Only allow allocation up to half the available memory (sane_size).
3376 uint64_t max_nkdbufs
= (sane_size
/ 2) / sizeof(kd_buf
);
3377 nkdbufs
= (req_nkdbufs
> max_nkdbufs
) ? max_nkdbufs
: req_nkdbufs
;
3381 * Block until there are `n_storage_threshold` storage units filled with
3382 * events or `timeout_ms` milliseconds have passed. If `locked_wait` is true,
3383 * `ktrace_lock` is held while waiting. This is necessary while waiting to
3384 * write events out of the buffers.
3386 * Returns true if the threshold was reached and false otherwise.
3388 * Called with `ktrace_lock` locked and interrupts enabled.
3391 kdbg_wait(uint64_t timeout_ms
, bool locked_wait
)
3393 int wait_result
= THREAD_AWAKENED
;
3394 uint64_t abstime
= 0;
3396 ktrace_assert_lock_held();
3398 if (timeout_ms
!= 0) {
3399 uint64_t ns
= timeout_ms
* NSEC_PER_MSEC
;
3400 nanoseconds_to_absolutetime(ns
, &abstime
);
3401 clock_absolutetime_interval_to_deadline(abstime
, &abstime
);
3404 bool s
= ml_set_interrupts_enabled(false);
3406 panic("kdbg_wait() called with interrupts disabled");
3408 lck_spin_lock_grp(kdw_spin_lock
, kdebug_lck_grp
);
3411 /* drop the mutex to allow others to access trace */
3415 while (wait_result
== THREAD_AWAKENED
&&
3416 kd_ctrl_page
.kds_inuse_count
< n_storage_threshold
) {
3420 wait_result
= lck_spin_sleep_deadline(kdw_spin_lock
, 0, &kds_waiter
, THREAD_ABORTSAFE
, abstime
);
3422 wait_result
= lck_spin_sleep(kdw_spin_lock
, 0, &kds_waiter
, THREAD_ABORTSAFE
);
3428 /* check the count under the spinlock */
3429 bool threshold_exceeded
= (kd_ctrl_page
.kds_inuse_count
>= n_storage_threshold
);
3431 lck_spin_unlock(kdw_spin_lock
);
3432 ml_set_interrupts_enabled(s
);
3435 /* pick the mutex back up again */
3439 /* write out whether we've exceeded the threshold */
3440 return threshold_exceeded
;
3444 * Wakeup a thread waiting using `kdbg_wait` if there are at least
3445 * `n_storage_threshold` storage units in use.
3450 bool need_kds_wakeup
= false;
3453 * Try to take the lock here to synchronize with the waiter entering
3454 * the blocked state. Use the try mode to prevent deadlocks caused by
3455 * re-entering this routine due to various trace points triggered in the
3456 * lck_spin_sleep_xxxx routines used to actually enter one of our 2 wait
3457 * conditions. No problem if we fail, there will be lots of additional
3458 * events coming in that will eventually succeed in grabbing this lock.
3460 bool s
= ml_set_interrupts_enabled(false);
3462 if (lck_spin_try_lock(kdw_spin_lock
)) {
3464 (kd_ctrl_page
.kds_inuse_count
>= n_storage_threshold
)) {
3466 need_kds_wakeup
= true;
3468 lck_spin_unlock(kdw_spin_lock
);
3471 ml_set_interrupts_enabled(s
);
3473 if (need_kds_wakeup
== true) {
3474 wakeup(&kds_waiter
);
3479 kdbg_control(int *name
, u_int namelen
, user_addr_t where
, size_t *sizep
)
3482 size_t size
= *sizep
;
3483 unsigned int value
= 0;
3485 kbufinfo_t kd_bufinfo
;
3488 if (name
[0] == KERN_KDWRITETR
||
3489 name
[0] == KERN_KDWRITETR_V3
||
3490 name
[0] == KERN_KDWRITEMAP
||
3491 name
[0] == KERN_KDWRITEMAP_V3
||
3492 name
[0] == KERN_KDEFLAGS
||
3493 name
[0] == KERN_KDDFLAGS
||
3494 name
[0] == KERN_KDENABLE
||
3495 name
[0] == KERN_KDSETBUF
) {
3503 assert(kd_ctrl_page
.kdebug_flags
& KDBG_LOCKINIT
);
3508 * Some requests only require "read" access to kdebug trace. Regardless,
3509 * tell ktrace that a configuration or read is occurring (and see if it's
3512 if (name
[0] != KERN_KDGETBUF
&&
3513 name
[0] != KERN_KDGETREG
&&
3514 name
[0] != KERN_KDREADCURTHRMAP
) {
3515 if ((ret
= ktrace_configure(KTRACE_KDEBUG
))) {
3519 if ((ret
= ktrace_read_check())) {
3526 if (size
< sizeof(kd_bufinfo
.nkdbufs
)) {
3528 * There is not enough room to return even
3529 * the first element of the info structure.
3535 memset(&kd_bufinfo
, 0, sizeof(kd_bufinfo
));
3537 kd_bufinfo
.nkdbufs
= nkdbufs
;
3538 kd_bufinfo
.nkdthreads
= kd_mapcount
;
3540 if ((kd_ctrl_page
.kdebug_slowcheck
& SLOW_NOLOG
)) {
3541 kd_bufinfo
.nolog
= 1;
3543 kd_bufinfo
.nolog
= 0;
3546 kd_bufinfo
.flags
= kd_ctrl_page
.kdebug_flags
;
3547 #if defined(__LP64__)
3548 kd_bufinfo
.flags
|= KDBG_LP64
;
3551 int pid
= ktrace_get_owning_pid();
3552 kd_bufinfo
.bufid
= (pid
== 0 ? -1 : pid
);
3555 if (size
>= sizeof(kd_bufinfo
)) {
3557 * Provide all the info we have
3559 if (copyout(&kd_bufinfo
, where
, sizeof(kd_bufinfo
))) {
3564 * For backwards compatibility, only provide
3565 * as much info as there is room for.
3567 if (copyout(&kd_bufinfo
, where
, size
)) {
3573 case KERN_KDREADCURTHRMAP
:
3574 ret
= kdbg_readcurthrmap(where
, sizep
);
3578 value
&= KDBG_USERFLAGS
;
3579 kd_ctrl_page
.kdebug_flags
|= value
;
3583 value
&= KDBG_USERFLAGS
;
3584 kd_ctrl_page
.kdebug_flags
&= ~value
;
3589 * Enable tracing mechanism. Two types:
3590 * KDEBUG_TRACE is the standard one,
3591 * and KDEBUG_PPT which is a carefully
3592 * chosen subset to avoid performance impact.
3596 * enable only if buffer is initialized
3598 if (!(kd_ctrl_page
.kdebug_flags
& KDBG_BUFINIT
) ||
3599 !(value
== KDEBUG_ENABLE_TRACE
|| value
== KDEBUG_ENABLE_PPT
)) {
3605 kdbg_set_tracing_enabled(true, value
);
3607 if (!kdebug_enable
) {
3611 kernel_debug_disable();
3616 kdbg_set_nkdbufs(value
);
3620 ret
= kdbg_reinit(false);
3624 ktrace_reset(KTRACE_KDEBUG
);
3628 if (size
< sizeof(kd_regtype
)) {
3632 if (copyin(where
, &kd_Reg
, sizeof(kd_regtype
))) {
3637 ret
= kdbg_setreg(&kd_Reg
);
3645 ret
= kdbg_read(where
, sizep
, NULL
, NULL
, RAW_VERSION1
);
3648 case KERN_KDWRITETR
:
3649 case KERN_KDWRITETR_V3
:
3650 case KERN_KDWRITEMAP
:
3651 case KERN_KDWRITEMAP_V3
:
3653 struct vfs_context context
;
3654 struct fileproc
*fp
;
3659 if (name
[0] == KERN_KDWRITETR
|| name
[0] == KERN_KDWRITETR_V3
) {
3660 (void)kdbg_wait(size
, true);
3666 if ((ret
= fp_lookup(p
, fd
, &fp
, 1))) {
3670 context
.vc_thread
= current_thread();
3671 context
.vc_ucred
= fp
->f_fglob
->fg_cred
;
3673 if (FILEGLOB_DTYPE(fp
->f_fglob
) != DTYPE_VNODE
) {
3674 fp_drop(p
, fd
, fp
, 1);
3680 vp
= (struct vnode
*)fp
->f_fglob
->fg_data
;
3683 if ((ret
= vnode_getwithref(vp
)) == 0) {
3684 RAW_file_offset
= fp
->f_fglob
->fg_offset
;
3685 if (name
[0] == KERN_KDWRITETR
|| name
[0] == KERN_KDWRITETR_V3
) {
3686 number
= nkdbufs
* sizeof(kd_buf
);
3688 KDBG_RELEASE(TRACE_WRITING_EVENTS
| DBG_FUNC_START
);
3689 if (name
[0] == KERN_KDWRITETR_V3
) {
3690 ret
= kdbg_read(0, &number
, vp
, &context
, RAW_VERSION3
);
3692 ret
= kdbg_read(0, &number
, vp
, &context
, RAW_VERSION1
);
3694 KDBG_RELEASE(TRACE_WRITING_EVENTS
| DBG_FUNC_END
, number
);
3698 number
= kd_mapcount
* sizeof(kd_threadmap
);
3699 if (name
[0] == KERN_KDWRITEMAP_V3
) {
3700 ret
= kdbg_readthrmap_v3(0, number
, fd
);
3702 ret
= kdbg_write_thread_map(vp
, &context
);
3705 fp
->f_fglob
->fg_offset
= RAW_file_offset
;
3708 fp_drop(p
, fd
, fp
, 0);
3712 case KERN_KDBUFWAIT
:
3713 *sizep
= kdbg_wait(size
, false);
3717 if (size
< sizeof(kd_regtype
)) {
3721 if (copyin(where
, &kd_Reg
, sizeof(kd_regtype
))) {
3726 ret
= kdbg_setpid(&kd_Reg
);
3730 if (size
< sizeof(kd_regtype
)) {
3734 if (copyin(where
, &kd_Reg
, sizeof(kd_regtype
))) {
3739 ret
= kdbg_setpidex(&kd_Reg
);
3743 ret
= kdbg_readcpumap(where
, sizep
);
3747 ret
= kdbg_copyout_thread_map(where
, sizep
);
3750 case KERN_KDSET_TYPEFILTER
: {
3751 ret
= kdbg_copyin_typefilter(where
, size
);
3756 ret
= kdbg_test(size
);
3771 * This code can run for the most part concurrently with kernel_debug_internal()...
3772 * 'release_storage_unit' will take the kds_spin_lock which may cause us to briefly
3773 * synchronize with the recording side of this puzzle... otherwise, we are able to
3774 * move through the lists w/o use of any locks
3777 kdbg_read(user_addr_t buffer
, size_t *number
, vnode_t vp
, vfs_context_t ctx
, uint32_t file_version
)
3780 unsigned int cpu
, min_cpu
;
3781 uint64_t barrier_min
= 0, barrier_max
= 0, t
, earliest_time
;
3787 bool traced_retrograde
= false;
3788 struct kd_storage
*kdsp_actual
;
3789 struct kd_bufinfo
*kdbp
;
3790 struct kd_bufinfo
*min_kdbp
;
3791 uint32_t tempbuf_count
;
3792 uint32_t tempbuf_number
;
3793 uint32_t old_kdebug_flags
;
3794 uint32_t old_kdebug_slowcheck
;
3795 bool out_of_events
= false;
3796 bool wrapped
= false;
3799 count
= *number
/ sizeof(kd_buf
);
3802 ktrace_assert_lock_held();
3804 if (count
== 0 || !(kd_ctrl_page
.kdebug_flags
& KDBG_BUFINIT
) || kdcopybuf
== 0) {
3808 thread_set_eager_preempt(current_thread());
3810 memset(&lostevent
, 0, sizeof(lostevent
));
3811 lostevent
.debugid
= TRACE_LOST_EVENTS
;
3814 * Request each IOP to provide us with up to date entries before merging
3817 kdbg_iop_list_callback(kd_ctrl_page
.kdebug_iops
, KD_CALLBACK_SYNC_FLUSH
, NULL
);
3820 * Capture the current time. Only sort events that have occured
3821 * before now. Since the IOPs are being flushed here, it is possible
3822 * that events occur on the AP while running live tracing.
3824 barrier_max
= kdbg_timestamp() & KDBG_TIMESTAMP_MASK
;
3827 * Disable wrap so storage units cannot be stolen out from underneath us
3828 * while merging events.
3830 * Because we hold ktrace_lock, no other control threads can be playing
3831 * with kdebug_flags. The code that emits new events could be running,
3832 * but it grabs kds_spin_lock if it needs to acquire a new storage
3833 * chunk, which is where it examines kdebug_flags. If it is adding to
3834 * the same chunk we're reading from, check for that below.
3836 wrapped
= disable_wrap(&old_kdebug_slowcheck
, &old_kdebug_flags
);
3838 if (count
> nkdbufs
) {
3842 if ((tempbuf_count
= count
) > KDCOPYBUF_COUNT
) {
3843 tempbuf_count
= KDCOPYBUF_COUNT
;
3847 * If the buffers have wrapped, do not emit additional lost events for the
3848 * oldest storage units.
3851 kd_ctrl_page
.kdebug_flags
&= ~KDBG_WRAPPED
;
3853 for (cpu
= 0, kdbp
= &kdbip
[0]; cpu
< kd_ctrl_page
.kdebug_cpus
; cpu
++, kdbp
++) {
3854 if ((kdsp
= kdbp
->kd_list_head
).raw
== KDS_PTR_NULL
) {
3857 kdsp_actual
= POINTER_FROM_KDS_PTR(kdsp
);
3858 kdsp_actual
->kds_lostevents
= false;
3862 * Capture the earliest time where there are events for all CPUs and don't
3863 * emit events with timestamps prior.
3865 barrier_min
= kd_ctrl_page
.oldest_time
;
3868 tempbuf
= kdcopybuf
;
3873 * Emit a lost events tracepoint to indicate that previous events
3874 * were lost -- the thread map cannot be trusted. A new one must
3875 * be taken so tools can analyze the trace in a backwards-facing
3878 kdbg_set_timestamp_and_cpu(&lostevent
, barrier_min
, 0);
3879 *tempbuf
= lostevent
;
3884 /* While space left in merged events scratch buffer. */
3885 while (tempbuf_count
) {
3886 bool lostevents
= false;
3888 earliest_time
= UINT64_MAX
;
3892 /* Check each CPU's buffers for the earliest event. */
3893 for (cpu
= 0, kdbp
= &kdbip
[0]; cpu
< kd_ctrl_page
.kdebug_cpus
; cpu
++, kdbp
++) {
3894 /* Skip CPUs without data in their oldest storage unit. */
3895 if ((kdsp
= kdbp
->kd_list_head
).raw
== KDS_PTR_NULL
) {
3899 /* From CPU data to buffer header to buffer. */
3900 kdsp_actual
= POINTER_FROM_KDS_PTR(kdsp
);
3903 /* The next event to be read from this buffer. */
3904 rcursor
= kdsp_actual
->kds_readlast
;
3906 /* Skip this buffer if there are no events left. */
3907 if (rcursor
== kdsp_actual
->kds_bufindx
) {
3912 * Check that this storage unit wasn't stolen and events were
3913 * lost. This must have happened while wrapping was disabled
3916 if (kdsp_actual
->kds_lostevents
) {
3918 kdsp_actual
->kds_lostevents
= false;
3921 * The earliest event we can trust is the first one in this
3922 * stolen storage unit.
3924 uint64_t lost_time
=
3925 kdbg_get_timestamp(&kdsp_actual
->kds_records
[0]);
3926 if (kd_ctrl_page
.oldest_time
< lost_time
) {
3928 * If this is the first time we've seen lost events for
3929 * this gap, record its timestamp as the oldest
3930 * timestamp we're willing to merge for the lost events
3933 kd_ctrl_page
.oldest_time
= barrier_min
= lost_time
;
3938 t
= kdbg_get_timestamp(&kdsp_actual
->kds_records
[rcursor
]);
3940 if (t
> barrier_max
) {
3942 printf("kdebug: FUTURE EVENT: debugid %#8x: "
3943 "time %lld from CPU %u "
3944 "(barrier at time %lld, read %lu events)\n",
3945 kdsp_actual
->kds_records
[rcursor
].debugid
,
3946 t
, cpu
, barrier_max
, *number
+ tempbuf_number
);
3950 if (t
< kdsp_actual
->kds_timestamp
) {
3952 * This indicates the event emitter hasn't completed
3953 * filling in the event (becuase we're looking at the
3954 * buffer that the record head is using). The max barrier
3955 * timestamp should have saved us from seeing these kinds
3956 * of things, but other CPUs might be slow on the up-take.
3958 * Bail out so we don't get out-of-order events by
3959 * continuing to read events from other CPUs' events.
3961 out_of_events
= true;
3966 * Ignore events that have aged out due to wrapping or storage
3967 * unit exhaustion while merging events.
3969 if (t
< barrier_min
) {
3970 kdsp_actual
->kds_readlast
++;
3972 printf("kdebug: PAST EVENT: debugid %#8x: "
3973 "time %lld from CPU %u "
3974 "(barrier at time %lld)\n",
3975 kdsp_actual
->kds_records
[rcursor
].debugid
,
3976 t
, cpu
, barrier_min
);
3979 if (kdsp_actual
->kds_readlast
>= EVENTS_PER_STORAGE_UNIT
) {
3980 release_storage_unit(cpu
, kdsp
.raw
);
3982 if ((kdsp
= kdbp
->kd_list_head
).raw
== KDS_PTR_NULL
) {
3985 kdsp_actual
= POINTER_FROM_KDS_PTR(kdsp
);
3992 * Don't worry about merging any events -- just walk through
3993 * the CPUs and find the latest timestamp of lost events.
3999 if (t
< earliest_time
) {
4007 * If any lost events were hit in the buffers, emit an event
4008 * with the latest timestamp.
4010 kdbg_set_timestamp_and_cpu(&lostevent
, barrier_min
, lostcpu
);
4011 *tempbuf
= lostevent
;
4015 if (min_kdbp
== NULL
) {
4016 /* All buffers ran empty. */
4017 out_of_events
= true;
4019 if (out_of_events
) {
4023 kdsp
= min_kdbp
->kd_list_head
;
4024 kdsp_actual
= POINTER_FROM_KDS_PTR(kdsp
);
4026 /* Copy earliest event into merged events scratch buffer. */
4027 *tempbuf
= kdsp_actual
->kds_records
[kdsp_actual
->kds_readlast
++];
4029 if (kdsp_actual
->kds_readlast
== EVENTS_PER_STORAGE_UNIT
) {
4030 release_storage_unit(min_cpu
, kdsp
.raw
);
4034 * Watch for out of order timestamps (from IOPs).
4036 if (earliest_time
< min_kdbp
->kd_prev_timebase
) {
4038 * If we haven't already, emit a retrograde events event.
4039 * Otherwise, ignore this event.
4041 if (traced_retrograde
) {
4045 kdbg_set_timestamp_and_cpu(tempbuf
, min_kdbp
->kd_prev_timebase
, kdbg_get_cpu(tempbuf
));
4046 tempbuf
->arg1
= tempbuf
->debugid
;
4047 tempbuf
->arg2
= earliest_time
;
4050 tempbuf
->debugid
= TRACE_RETROGRADE_EVENTS
;
4051 traced_retrograde
= true;
4053 min_kdbp
->kd_prev_timebase
= earliest_time
;
4060 if ((RAW_file_written
+= sizeof(kd_buf
)) >= RAW_FLUSH_SIZE
) {
4064 if (tempbuf_number
) {
4066 * Remember the latest timestamp of events that we've merged so we
4067 * don't think we've lost events later.
4069 uint64_t latest_time
= kdbg_get_timestamp(tempbuf
- 1);
4070 if (kd_ctrl_page
.oldest_time
< latest_time
) {
4071 kd_ctrl_page
.oldest_time
= latest_time
;
4073 if (file_version
== RAW_VERSION3
) {
4074 if (!(kdbg_write_v3_event_chunk_header(buffer
, V3_RAW_EVENTS
, (tempbuf_number
* sizeof(kd_buf
)), vp
, ctx
))) {
4079 buffer
+= (sizeof(kd_chunk_header_v3
) + sizeof(uint64_t));
4082 assert(count
>= (sizeof(kd_chunk_header_v3
) + sizeof(uint64_t)));
4083 count
-= (sizeof(kd_chunk_header_v3
) + sizeof(uint64_t));
4084 *number
+= (sizeof(kd_chunk_header_v3
) + sizeof(uint64_t));
4087 size_t write_size
= tempbuf_number
* sizeof(kd_buf
);
4088 error
= kdbg_write_to_vnode((caddr_t
)kdcopybuf
, write_size
, vp
, ctx
, RAW_file_offset
);
4090 RAW_file_offset
+= write_size
;
4093 if (RAW_file_written
>= RAW_FLUSH_SIZE
) {
4094 error
= VNOP_FSYNC(vp
, MNT_NOWAIT
, ctx
);
4096 RAW_file_written
= 0;
4099 error
= copyout(kdcopybuf
, buffer
, tempbuf_number
* sizeof(kd_buf
));
4100 buffer
+= (tempbuf_number
* sizeof(kd_buf
));
4108 count
-= tempbuf_number
;
4109 *number
+= tempbuf_number
;
4111 if (out_of_events
== true) {
4113 * all trace buffers are empty
4118 if ((tempbuf_count
= count
) > KDCOPYBUF_COUNT
) {
4119 tempbuf_count
= KDCOPYBUF_COUNT
;
4122 if (!(old_kdebug_flags
& KDBG_NOWRAP
)) {
4123 enable_wrap(old_kdebug_slowcheck
);
4125 thread_clear_eager_preempt(current_thread());
4129 #define KDEBUG_TEST_CODE(code) BSDDBG_CODE(DBG_BSD_KDEBUG_TEST, (code))
4132 * A test IOP for the SYNC_FLUSH callback.
4135 static int sync_flush_iop
= 0;
4138 sync_flush_callback(void * __unused context
, kd_callback_type reason
,
4139 void * __unused arg
)
4141 assert(sync_flush_iop
> 0);
4143 if (reason
== KD_CALLBACK_SYNC_FLUSH
) {
4144 kernel_debug_enter(sync_flush_iop
, KDEBUG_TEST_CODE(0xff),
4145 kdbg_timestamp(), 0, 0, 0, 0, 0);
4149 static struct kd_callback sync_flush_kdcb
= {
4150 .func
= sync_flush_callback
,
4151 .iop_name
= "test_sf",
4155 kdbg_test(size_t flavor
)
4162 /* try each macro */
4163 KDBG(KDEBUG_TEST_CODE(code
)); code
++;
4164 KDBG(KDEBUG_TEST_CODE(code
), 1); code
++;
4165 KDBG(KDEBUG_TEST_CODE(code
), 1, 2); code
++;
4166 KDBG(KDEBUG_TEST_CODE(code
), 1, 2, 3); code
++;
4167 KDBG(KDEBUG_TEST_CODE(code
), 1, 2, 3, 4); code
++;
4169 KDBG_RELEASE(KDEBUG_TEST_CODE(code
)); code
++;
4170 KDBG_RELEASE(KDEBUG_TEST_CODE(code
), 1); code
++;
4171 KDBG_RELEASE(KDEBUG_TEST_CODE(code
), 1, 2); code
++;
4172 KDBG_RELEASE(KDEBUG_TEST_CODE(code
), 1, 2, 3); code
++;
4173 KDBG_RELEASE(KDEBUG_TEST_CODE(code
), 1, 2, 3, 4); code
++;
4175 KDBG_FILTERED(KDEBUG_TEST_CODE(code
)); code
++;
4176 KDBG_FILTERED(KDEBUG_TEST_CODE(code
), 1); code
++;
4177 KDBG_FILTERED(KDEBUG_TEST_CODE(code
), 1, 2); code
++;
4178 KDBG_FILTERED(KDEBUG_TEST_CODE(code
), 1, 2, 3); code
++;
4179 KDBG_FILTERED(KDEBUG_TEST_CODE(code
), 1, 2, 3, 4); code
++;
4181 KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code
)); code
++;
4182 KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code
), 1); code
++;
4183 KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code
), 1, 2); code
++;
4184 KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code
), 1, 2, 3); code
++;
4185 KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code
), 1, 2, 3, 4); code
++;
4187 KDBG_DEBUG(KDEBUG_TEST_CODE(code
)); code
++;
4188 KDBG_DEBUG(KDEBUG_TEST_CODE(code
), 1); code
++;
4189 KDBG_DEBUG(KDEBUG_TEST_CODE(code
), 1, 2); code
++;
4190 KDBG_DEBUG(KDEBUG_TEST_CODE(code
), 1, 2, 3); code
++;
4191 KDBG_DEBUG(KDEBUG_TEST_CODE(code
), 1, 2, 3, 4); code
++;
4195 if (kd_ctrl_page
.kdebug_iops
) {
4196 /* avoid the assertion in kernel_debug_enter for a valid IOP */
4197 dummy_iop
= kd_ctrl_page
.kdebug_iops
[0].cpu_id
;
4200 /* ensure old timestamps are not emitted from kernel_debug_enter */
4201 kernel_debug_enter(dummy_iop
, KDEBUG_TEST_CODE(code
),
4202 100 /* very old timestamp */, 0, 0, 0, 0, 0);
4204 kernel_debug_enter(dummy_iop
, KDEBUG_TEST_CODE(code
),
4205 kdbg_timestamp(), 0, 0, 0, 0, 0);
4210 if (kd_ctrl_page
.kdebug_iops
) {
4211 dummy_iop
= kd_ctrl_page
.kdebug_iops
[0].cpu_id
;
4213 kernel_debug_enter(dummy_iop
, KDEBUG_TEST_CODE(code
),
4214 kdbg_timestamp() * 2 /* !!! */, 0, 0, 0, 0, 0);
4218 if (!sync_flush_iop
) {
4219 sync_flush_iop
= kernel_debug_register_callback(
4221 assert(sync_flush_iop
> 0);
4232 #undef KDEBUG_TEST_CODE
4235 kdebug_init(unsigned int n_events
, char *filter_desc
, bool wrapping
)
4237 assert(filter_desc
!= NULL
);
4239 #if defined(__x86_64__)
4240 /* only trace MACH events when outputting kdebug to serial */
4241 if (kdebug_serial
) {
4243 if (filter_desc
[0] == '\0') {
4244 filter_desc
[0] = 'C';
4245 filter_desc
[1] = '1';
4246 filter_desc
[2] = '\0';
4249 #endif /* defined(__x86_64__) */
4251 if (log_leaks
&& n_events
== 0) {
4255 kdebug_trace_start(n_events
, filter_desc
, wrapping
, false);
4259 kdbg_set_typefilter_string(const char *filter_desc
)
4263 ktrace_assert_lock_held();
4265 assert(filter_desc
!= NULL
);
4267 typefilter_reject_all(kdbg_typefilter
);
4268 typefilter_allow_class(kdbg_typefilter
, DBG_TRACE
);
4270 /* if the filter description starts with a number, assume it's a csc */
4271 if (filter_desc
[0] >= '0' && filter_desc
[0] <= '9') {
4272 unsigned long csc
= strtoul(filter_desc
, NULL
, 0);
4273 if (filter_desc
!= end
&& csc
<= KDBG_CSC_MAX
) {
4274 typefilter_allow_csc(kdbg_typefilter
, csc
);
4279 while (filter_desc
[0] != '\0') {
4280 unsigned long allow_value
;
4282 char filter_type
= filter_desc
[0];
4283 if (filter_type
!= 'C' && filter_type
!= 'S') {
4288 allow_value
= strtoul(filter_desc
, &end
, 0);
4289 if (filter_desc
== end
) {
4290 /* cannot parse as integer */
4294 switch (filter_type
) {
4296 if (allow_value
<= KDBG_CLASS_MAX
) {
4297 typefilter_allow_class(kdbg_typefilter
, allow_value
);
4304 if (allow_value
<= KDBG_CSC_MAX
) {
4305 typefilter_allow_csc(kdbg_typefilter
, allow_value
);
4307 /* illegal class subclass */
4315 /* advance to next filter entry */
4317 if (filter_desc
[0] == ',') {
4324 * This function is meant to be called from the bootstrap thread or coming out
4325 * of acpi_idle_kernel.
4328 kdebug_trace_start(unsigned int n_events
, const char *filter_desc
,
4329 bool wrapping
, bool at_wake
)
4332 kd_early_done
= true;
4336 ktrace_start_single_threaded();
4340 ktrace_kernel_configure(KTRACE_KDEBUG
);
4342 kdbg_set_nkdbufs(n_events
);
4344 kernel_debug_string_early("start_kern_tracing");
4346 if (kdbg_reinit(true)) {
4347 printf("error from kdbg_reinit, kernel tracing not started\n");
4352 * Wrapping is disabled because boot and wake tracing is interested in
4353 * the earliest events, at the expense of later ones.
4356 uint32_t old1
, old2
;
4357 (void)disable_wrap(&old1
, &old2
);
4360 if (filter_desc
&& filter_desc
[0] != '\0') {
4361 if (kdbg_initialize_typefilter(NULL
) == KERN_SUCCESS
) {
4362 kdbg_set_typefilter_string(filter_desc
);
4363 kdbg_enable_typefilter();
4368 * Hold off interrupts between getting a thread map and enabling trace
4369 * and until the early traces are recorded.
4371 bool s
= ml_set_interrupts_enabled(false);
4377 kdbg_set_tracing_enabled(true, KDEBUG_ENABLE_TRACE
| (kdebug_serial
?
4378 KDEBUG_ENABLE_SERIAL
: 0));
4382 * Transfer all very early events from the static buffer into the real
4385 kernel_debug_early_end();
4388 ml_set_interrupts_enabled(s
);
4390 printf("kernel tracing started with %u events\n", n_events
);
4392 #if KDEBUG_MOJO_TRACE
4393 if (kdebug_serial
) {
4394 printf("serial output enabled with %lu named events\n",
4395 sizeof(kd_events
) / sizeof(kd_event_t
));
4397 #endif /* KDEBUG_MOJO_TRACE */
4400 ktrace_end_single_threaded();
4404 kdbg_dump_trace_to_file(const char *filename
)
4413 if (!(kdebug_enable
& KDEBUG_ENABLE_TRACE
)) {
4417 if (ktrace_get_owning_pid() != 0) {
4419 * Another process owns ktrace and is still active, disable tracing to
4423 kd_ctrl_page
.enabled
= 0;
4424 commpage_update_kdebug_state();
4428 KDBG_RELEASE(TRACE_WRITING_EVENTS
| DBG_FUNC_START
);
4431 kd_ctrl_page
.enabled
= 0;
4432 commpage_update_kdebug_state();
4434 ctx
= vfs_context_kernel();
4436 if (vnode_open(filename
, (O_CREAT
| FWRITE
| O_NOFOLLOW
), 0600, 0, &vp
, ctx
)) {
4440 kdbg_write_thread_map(vp
, ctx
);
4442 write_size
= nkdbufs
* sizeof(kd_buf
);
4443 ret
= kdbg_read(0, &write_size
, vp
, ctx
, RAW_VERSION1
);
4449 * Wait to synchronize the file to capture the I/O in the
4450 * TRACE_WRITING_EVENTS interval.
4452 ret
= VNOP_FSYNC(vp
, MNT_WAIT
, ctx
);
4455 * Balance the starting TRACE_WRITING_EVENTS tracepoint manually.
4457 kd_buf end_event
= {
4458 .debugid
= TRACE_WRITING_EVENTS
| DBG_FUNC_END
,
4461 .arg5
= thread_tid(current_thread()),
4463 kdbg_set_timestamp_and_cpu(&end_event
, kdbg_timestamp(),
4466 /* this is best effort -- ignore any errors */
4467 (void)kdbg_write_to_vnode((caddr_t
)&end_event
, sizeof(kd_buf
), vp
, ctx
,
4471 vnode_close(vp
, FWRITE
, ctx
);
4472 sync(current_proc(), (void *)NULL
, (int *)NULL
);
4479 kdbg_sysctl_continuous SYSCTL_HANDLER_ARGS
4481 #pragma unused(oidp, arg1, arg2)
4482 int value
= kdbg_continuous_time
;
4483 int ret
= sysctl_io_number(req
, value
, sizeof(value
), &value
, NULL
);
4485 if (ret
|| !req
->newptr
) {
4489 kdbg_continuous_time
= value
;
4493 SYSCTL_NODE(_kern
, OID_AUTO
, kdbg
, CTLFLAG_RD
| CTLFLAG_LOCKED
, 0,
4496 SYSCTL_PROC(_kern_kdbg
, OID_AUTO
, experimental_continuous
,
4497 CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
, 0,
4498 sizeof(int), kdbg_sysctl_continuous
, "I",
4499 "Set kdebug to use mach_continuous_time");
4501 SYSCTL_INT(_kern_kdbg
, OID_AUTO
, debug
,
4502 CTLFLAG_RW
| CTLFLAG_LOCKED
,
4503 &kdbg_debug
, 0, "Set kdebug debug mode");
4505 SYSCTL_QUAD(_kern_kdbg
, OID_AUTO
, oldest_time
,
4506 CTLTYPE_QUAD
| CTLFLAG_RD
| CTLFLAG_LOCKED
,
4507 &kd_ctrl_page
.oldest_time
,
4508 "Find the oldest timestamp still in trace");
4510 #if KDEBUG_MOJO_TRACE
4512 binary_search(uint32_t id
)
4517 high
= (int)(sizeof(kd_events
) / sizeof(kd_event_t
)) - 1;
4520 mid
= (low
+ high
) / 2;
4523 return NULL
; /* failed */
4524 } else if (low
+ 1 >= high
) {
4525 /* We have a match */
4526 if (kd_events
[high
].id
== id
) {
4527 return &kd_events
[high
];
4528 } else if (kd_events
[low
].id
== id
) {
4529 return &kd_events
[low
];
4531 return NULL
; /* search failed */
4533 } else if (id
< kd_events
[mid
].id
) {
4542 * Look up event id to get name string.
4543 * Using a per-cpu cache of a single entry
4544 * before resorting to a binary search of the full table.
4547 static kd_event_t
*last_hit
[MAX_CPUS
];
4549 event_lookup_cache(uint32_t cpu
, uint32_t id
)
4551 if (last_hit
[cpu
] == NULL
|| last_hit
[cpu
]->id
!= id
) {
4552 last_hit
[cpu
] = binary_search(id
);
4554 return last_hit
[cpu
];
4557 static uint64_t kd_last_timstamp
;
4560 kdebug_serial_print(
4571 char kprintf_line
[192];
4573 uint64_t us
= timestamp
/ NSEC_PER_USEC
;
4574 uint64_t us_tenth
= (timestamp
% NSEC_PER_USEC
) / 100;
4575 uint64_t delta
= timestamp
- kd_last_timstamp
;
4576 uint64_t delta_us
= delta
/ NSEC_PER_USEC
;
4577 uint64_t delta_us_tenth
= (delta
% NSEC_PER_USEC
) / 100;
4578 uint32_t event_id
= debugid
& KDBG_EVENTID_MASK
;
4579 const char *command
;
4584 /* event time and delta from last */
4585 snprintf(kprintf_line
, sizeof(kprintf_line
),
4586 "%11llu.%1llu %8llu.%1llu ",
4587 us
, us_tenth
, delta_us
, delta_us_tenth
);
4590 /* event (id or name) - start prefixed by "[", end postfixed by "]" */
4591 bra
= (debugid
& DBG_FUNC_START
) ? "[" : " ";
4592 ket
= (debugid
& DBG_FUNC_END
) ? "]" : " ";
4593 ep
= event_lookup_cache(cpunum
, event_id
);
4595 if (strlen(ep
->name
) < sizeof(event
) - 3) {
4596 snprintf(event
, sizeof(event
), "%s%s%s",
4597 bra
, ep
->name
, ket
);
4599 snprintf(event
, sizeof(event
), "%s%x(name too long)%s",
4600 bra
, event_id
, ket
);
4603 snprintf(event
, sizeof(event
), "%s%x%s",
4604 bra
, event_id
, ket
);
4606 snprintf(kprintf_line
+ strlen(kprintf_line
),
4607 sizeof(kprintf_line
) - strlen(kprintf_line
),
4610 /* arg1 .. arg4 with special cases for strings */
4613 case VFS_LOOKUP_DONE
:
4614 if (debugid
& DBG_FUNC_START
) {
4615 /* arg1 hex then arg2..arg4 chars */
4616 snprintf(kprintf_line
+ strlen(kprintf_line
),
4617 sizeof(kprintf_line
) - strlen(kprintf_line
),
4618 "%-16lx %-8s%-8s%-8s ",
4619 arg1
, (char*)&arg2
, (char*)&arg3
, (char*)&arg4
);
4622 /* else fall through for arg1..arg4 chars */
4623 case TRACE_STRING_EXEC
:
4624 case TRACE_STRING_NEWTHREAD
:
4625 case TRACE_INFO_STRING
:
4626 snprintf(kprintf_line
+ strlen(kprintf_line
),
4627 sizeof(kprintf_line
) - strlen(kprintf_line
),
4628 "%-8s%-8s%-8s%-8s ",
4629 (char*)&arg1
, (char*)&arg2
, (char*)&arg3
, (char*)&arg4
);
4632 snprintf(kprintf_line
+ strlen(kprintf_line
),
4633 sizeof(kprintf_line
) - strlen(kprintf_line
),
4634 "%-16lx %-16lx %-16lx %-16lx",
4635 arg1
, arg2
, arg3
, arg4
);
4638 /* threadid, cpu and command name */
4639 if (threadid
== (uintptr_t)thread_tid(current_thread()) &&
4641 current_proc()->p_comm
[0]) {
4642 command
= current_proc()->p_comm
;
4646 snprintf(kprintf_line
+ strlen(kprintf_line
),
4647 sizeof(kprintf_line
) - strlen(kprintf_line
),
4648 " %-16lx %-2d %s\n",
4649 threadid
, cpunum
, command
);
4651 kprintf("%s", kprintf_line
);
4652 kd_last_timstamp
= timestamp
;