1 /*
2 * Copyright (c) 2000-2021 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28
29 #ifndef BSD_KDEBUG_PRIVATE_H
30 #define BSD_KDEBUG_PRIVATE_H
31
32 #include <os/base.h>
33 #include <stdint.h>
34 #include <stdbool.h>
35 #include <sys/cdefs.h>
36 #include <sys/kdebug.h>
37
38 __BEGIN_DECLS
39
40 #if !KERNEL
41
42 #include <Availability.h>
43
44 #pragma mark - User space SPI
45
46 // Internal software can trace events into kdebug, but the os_signpost(3)
47 // interfaces in `<os/signpost.h>` are recommended.
48 //
49 // kdebug_trace(KDBG_EVENTID(DBG_XPC, 15, 1), 1, 2, 3, 4);
50 //
51 // The performance impact when kernel tracing is not enabled is minimal.
52 // However, when tracing is enabled, each event requires a syscall.
53 //
54 // Classes can be reserved by filing a Radar in xnu | ktrace.
55 //
56 // 64-bit arguments may be truncated if the system is using a 32-bit kernel.
57 //
58 // On error, -1 will be returned and errno will indicate the error.
59 int kdebug_trace(uint32_t debugid, uint64_t arg1, uint64_t arg2, uint64_t arg3,
60 uint64_t arg4)
61 __API_AVAILABLE(macos(10.0), ios(8), tvos(8), watchos(1));
62
63 // Although the performance impact of kdebug_trace() when tracing is disabled is
64 // minimal, it may require the caller to perform an expensive calculation or
65 // summarization. This cost can be skipped by checking the kdebug_is_enabled()
66 // predicate:
67 //
68 // if (kdebug_is_enabled(KDBG_CODE(DBG_XPC, 15, 1))) {
69 // uint64_t arg1 = ...;
70 // uint64_t arg2 = ...;
71 // kdebug_trace(KDBG_EVENTID(DBG_XPC, 15, 1), arg1, arg2, 0, 0);
72 // }
73 //
74 // true is returned iff tracing is enabled for the debug ID at the time of the
75 // check.
76 extern bool kdebug_is_enabled(uint32_t debugid)
77 __API_AVAILABLE(macos(10.12), ios(10), watchos(3), tvos(10));
78
79 // Returns true if kdebug is using continuous time for its events, and false
80 // otherwise.
81 extern bool kdebug_using_continuous_time(void)
82 __API_AVAILABLE(macos(10.15), ios(13), tvos(13), watchos(6));
83
84 // Convert an absolute time to a kdebug timestamp.
85 extern uint64_t kdebug_timestamp_from_absolute(uint64_t abstime)
86 __API_AVAILABLE(macos(12), ios(15), tvos(15), watchos(8));
87
88 // Convert a continuous time to a kdebug timestamp.
89 extern uint64_t kdebug_timestamp_from_continuous(uint64_t conttime)
90 __API_AVAILABLE(macos(12), ios(15), tvos(15), watchos(8));
91
92 // Capture a kdebug timestamp for the current time.
93 extern uint64_t kdebug_timestamp(void)
94 __API_AVAILABLE(macos(12), ios(15), tvos(15), watchos(8));
95
96 /// @function kdebug_trace_string
97 ///
98 /// @discussion
99 /// This function emits strings to kdebug trace along with an ID and allows
100 /// for previously-traced strings to be overwritten and invalidated.
101 ///
102 /// To start tracing a string and generate an ID to use to refer to it:
103 ///
104 /// string_id = kdebug_trace_string(debugid, 0, "string");
105 ///
106 /// To replace a string previously traced:
107 ///
108 /// string_id = kdebug_trace_string(debugid, string_id, "new string");
109 ///
110 /// To invalidate a string ID:
111 ///
112 /// string_id = kdebug_trace_string(debugid, string_id, NULL);
113 ///
114 /// To check for errors:
115 ///
116 /// if ((int64_t)string_id == -1) { perror("string error") }
117 ///
118 /// @param debugid
119 /// The `debugid` to check if its enabled before tracing and include as
120 /// an argument in the event containing the string.
121 ///
122 /// Some classes or subclasses are reserved for specific uses and are not
123 /// allowed to be used with this function. No function qualifiers are
124 /// allowed on `debugid`.
125 ///
126 /// @param str_id
127 /// When 0, a new ID will be generated and returned if tracing is
128 /// enabled.
129 ///
130 /// Otherwise `str_id` must contain an ID that was previously generated
131 /// with this function. Clents should pass NULL in `str` if `str_id`
132 /// is no longer in use. Otherwise, the string previously mapped to
133 /// `str_id` will be overwritten with the contents of `str`.
134 ///
135 /// @param str
136 /// A NUL-terminated 'C' string containing the characters that should be
137 /// traced alongside `str_id`.
138 ///
139 /// If necessary, the string will be truncated at an
140 /// implementation-defined length of at least PATH_MAX characters. The string
141 /// must not be the empty string, but can be NULL if a valid `str_id` is
142 /// provided.
143 ///
144 /// @return
145 /// 0 if tracing is disabled or `debugid` is being filtered out of trace.
146 /// It can also return (int64_t)-1 if an error occured. Otherwise,
147 /// it returns the ID to use to refer to the string in future
148 /// kdebug_trace(2) calls.
149 ///
150 /// The errors that can occur are:
151 ///
152 /// EINVAL
153 /// There are function qualifiers on `debugid`, `str` is empty, or
154 /// `str_id` was not generated by this function.
155 /// EPERM
156 /// The `debugid`'s class or subclass is reserved for internal use.
157 /// EFAULT
158 /// `str` is an invalid address or NULL when `str_id` is 0.
159 extern uint64_t kdebug_trace_string(uint32_t debugid, uint64_t str_id,
160 const char *str)
161 __API_AVAILABLE(macos(10.11), ios(9), watchos(2), tvos(9));
162
163 // Returns a pointer to the userspace typefilter, if one is available.
164 // May return NULL.
165 extern void *kdebug_typefilter(void)
166 __API_AVAILABLE(macos(10.12), ios(10), watchos(3), tvos(10));
167
168 #endif /* !KERNEL */
169
170 #pragma mark - Private debug IDs
171
172 #define DBG_PPT 36
173 #define DBG_PERFCTRL 39
174 #define DBG_CLPC 50
175 #define DBG_MUSE 52
176
177 #define DBG_ANS 128
178 #define DBG_SIO 129
179 #define DBG_SEP 130
180 #define DBG_ISP 131
181 #define DBG_OSCAR 132
182 #define DBG_EMBEDDEDGFX 133
183 #define DBG_PMP 134
184 #define DBG_RTKIT 135
185
186 // DBG_SKYWALK is the same as DBG_DLIL, so don't reuse subclasses
187 #define DBG_SKYWALK_ALWAYSON 0x10
188 #define DBG_SKYWALK_FLOWSWITCH 0x11
189 #define DBG_SKYWALK_NETIF 0x12
190 #define DBG_SKYWALK_CHANNEL 0x13
191 #define DBG_SKYWALK_PACKET 0x14
192
193 //DBG_AQM is the same as DBG_DLIL and DBG_SKYWALK, so don't reuse subclasses
194 #define DBG_AQM_ALWAYSON 0x30
195 #define DBG_AQM_STATS 0x31
196
197 // DBG_IFNET is the same as DBG_DLIL, DBG_AQM and DBG_SKYWALK, so don't reuse subclasses
198 #define DBG_IFNET 0x40
199
200 #define PPT_TEST 0x01
201 #define PPT_JETSAM_HIWAT 0x02
202 #define PPT_JETSAM_TOPPROC 0x03
203
204 #define SKYWALKDBG_CODE(SubClass, code) KDBG_CODE(DBG_DLIL, SubClass, code)
205 #define PPTDBG_CODE(SubClass, code) KDBG_CODE(DBG_PPT, SubClass, code)
206 #define PERFCTRL_CODE(SubClass, code) KDBG_CODE(DBG_PERFCTRL, SubClass, code)
207 #define AQMDBG_CODE(SubClass, code) KDBG_CODE(DBG_DLIL, SubClass, code)
208 #define IFNETDBG_CODE(SubClass, code) KDBG_CODE(DBG_DLIL, SubClass, code)
209
210 #if !defined(DRIVERKIT)
211
212 extern unsigned int kdebug_enable;
213
214 // Options for `kdebug_enable`.
215
216 // Enable tracing.
217 #define KDEBUG_ENABLE_TRACE 0x001U
218 // Whether timestamps are continuous times or absolute times.
219 #define KDEBUG_ENABLE_CONT_TIME 0x020U
220
221 #define KDEBUG_TRACE (KDEBUG_ENABLE_TRACE)
222
223 // Control which kernel events are compiled in under different build
224 // configurations.
225
226 // No kdebug events are emitted with the macros.
227 #define KDEBUG_LEVEL_NONE 0
228 // In-System Tracing exposes a limited set of events for release kernels.
229 #define KDEBUG_LEVEL_IST 1
230 // The default for development kernels.
231 #define KDEBUG_LEVEL_STANDARD 2
232 // Truly verbose, debug-level logging, only set manually.
233 #define KDEBUG_LEVEL_FULL 3
234
235 // Use configuration options to set the kdebug level.
236 #if NO_KDEBUG
237 #define KDEBUG_LEVEL KDEBUG_LEVEL_NONE
238 #elif IST_KDEBUG
239 #define KDEBUG_LEVEL KDEBUG_LEVEL_IST
240 #elif KDEBUG
241 #define KDEBUG_LEVEL KDEBUG_LEVEL_FULL
242 #else // !NO_KDEBUG && !IST_KDEBUG && !KDEBUG
243 #define KDEBUG_LEVEL KDEBUG_LEVEL_STANDARD
244 #endif // !NO_KDEBUG && !IST_KDEBUG && !KDEBUG
245
246 #pragma mark - Implementation details
247
248 // Ensure that LP32 and LP64 variants of arm64 use the same kd_buf structure.
249 #if defined(__arm64__)
250 typedef uint64_t kd_buf_argtype;
251 #else // defined(__arm64__)
252 typedef uintptr_t kd_buf_argtype;
253 #endif // !defined(__arm64__)
254
255 // The main event ABI as recorded in the kernel.
256
257 typedef struct {
258 uint64_t timestamp;
259 kd_buf_argtype arg1;
260 kd_buf_argtype arg2;
261 kd_buf_argtype arg3;
262 kd_buf_argtype arg4;
263 kd_buf_argtype arg5; // Always the thread ID.
264 uint32_t debugid;
265 // Ensure that LP32 and LP64 variants of arm64 use the same kd_buf structure.
266 #if defined(__LP64__) || defined(__arm64__)
267 uint32_t cpuid;
268 kd_buf_argtype unused;
269 #endif // defined(__LP64__) || defined(__arm64__)
270 } kd_buf;
271
272 #if defined(__LP64__) || defined(__arm64__)
273
274 #define KDBG_TIMESTAMP_MASK 0xffffffffffffffffULL
275 static inline void
kdbg_set_cpu(kd_buf * kp,int cpu)276 kdbg_set_cpu(kd_buf *kp, int cpu)
277 {
278 kp->cpuid = (unsigned int)cpu;
279 }
280 static inline int
kdbg_get_cpu(kd_buf * kp)281 kdbg_get_cpu(kd_buf *kp)
282 {
283 return (int)kp->cpuid;
284 }
285 static inline void
kdbg_set_timestamp(kd_buf * kp,uint64_t thetime)286 kdbg_set_timestamp(kd_buf *kp, uint64_t thetime)
287 {
288 kp->timestamp = thetime;
289 }
290 static inline uint64_t
kdbg_get_timestamp(kd_buf * kp)291 kdbg_get_timestamp(kd_buf *kp)
292 {
293 return kp->timestamp;
294 }
295 static inline void
kdbg_set_timestamp_and_cpu(kd_buf * kp,uint64_t thetime,int cpu)296 kdbg_set_timestamp_and_cpu(kd_buf *kp, uint64_t thetime, int cpu)
297 {
298 kdbg_set_timestamp(kp, thetime);
299 kdbg_set_cpu(kp, cpu);
300 }
301 #else // defined(__LP64__) || defined(__arm64__)
302 #define KDBG_TIMESTAMP_MASK 0x00ffffffffffffffULL
303 #define KDBG_CPU_MASK 0xff00000000000000ULL
304 #define KDBG_CPU_SHIFT 56
305 static inline void
kdbg_set_cpu(kd_buf * kp,int cpu)306 kdbg_set_cpu(kd_buf *kp, int cpu)
307 {
308 kp->timestamp = (kp->timestamp & KDBG_TIMESTAMP_MASK) |
309 (((uint64_t) cpu) << KDBG_CPU_SHIFT);
310 }
311 static inline int
kdbg_get_cpu(kd_buf * kp)312 kdbg_get_cpu(kd_buf *kp)
313 {
314 return (int) (((kp)->timestamp & KDBG_CPU_MASK) >> KDBG_CPU_SHIFT);
315 }
316 static inline void
kdbg_set_timestamp(kd_buf * kp,uint64_t thetime)317 kdbg_set_timestamp(kd_buf *kp, uint64_t thetime)
318 {
319 kp->timestamp = thetime & KDBG_TIMESTAMP_MASK;
320 }
321 static inline uint64_t
kdbg_get_timestamp(kd_buf * kp)322 kdbg_get_timestamp(kd_buf *kp)
323 {
324 return kp->timestamp & KDBG_TIMESTAMP_MASK;
325 }
326 static inline void
kdbg_set_timestamp_and_cpu(kd_buf * kp,uint64_t thetime,int cpu)327 kdbg_set_timestamp_and_cpu(kd_buf *kp, uint64_t thetime, int cpu)
328 {
329 kp->timestamp = (thetime & KDBG_TIMESTAMP_MASK) |
330 (((uint64_t) cpu) << KDBG_CPU_SHIFT);
331 }
332 #endif // !defined(__LP64__) && !defined(__arm64__)
333
334 // 8KB, one bit for each possible class/subclass combination.
335 #define KDBG_TYPEFILTER_BITMAP_SIZE ((256 * 256) / 8)
336
337 // Settings that may need to be changed while tracing, protected by the storage
338 // lock or the ktrace lock if tracing is disabled.
339 //
340 // These flags must not overlap with `kdebug_flags_t`.
341 __options_decl(kdebug_live_flags_t, uint32_t, {
342 // Disable tracing when events wrap. Set while reading events.
343 KDBG_NOWRAP = 0x0002,
344 // Events have wrapped.
345 KDBG_WRAPPED = 0x0008,
346 });
347
348 // Mostly configuration options, protected by the ktrace lock.
349 __options_decl(kdebug_flags_t, uint32_t, {
350 // Only trace processes with the kdebug bit set.
351 KDBG_PIDCHECK = 0x0010,
352 // Thread map pointer is valid.
353 KDBG_MAPINIT = 0x0020,
354 // Exclude events from processes with the kdebug bit set.
355 KDBG_PIDEXCLUDE = 0x0040,
356 // Events are 64-bit, only for `kbufinfo_t`.
357 KDBG_LP64 = 0x0100,
358 // Timestamps are continuous time, instead of absolute time.
359 KDBG_CONTINUOUS_TIME = 0x0200,
360 // Exclude events from coprocessors (IOPs).
361 KDBG_DISABLE_COPROCS = 0x0400,
362 // Disable tracing on event match.
363 KDBG_MATCH_DISABLE = 0x0800,
364 // Check the typefilter.
365 KDBG_TYPEFILTER_CHECK = 0x00400000,
366 // 64-bit debug ID present in arg4 (triage-only).
367 KDBG_DEBUGID_64 = 0x00800000,
368 // Event storage buffers are initialized.
369 KDBG_BUFINIT = 0x80000000U,
370 });
371
372 // Obsolete flags.
373 #define KDBG_INIT 0x01
374 #define KDBG_FREERUN 0x04
375
376 // Flags in `kdebug_live_flags_t` and `kdebug_flags_t` that can be modified by
377 // user space.
378 #define KDBG_USERFLAGS (KDBG_NOWRAP | KDBG_CONTINUOUS_TIME | \
379 KDBG_DISABLE_COPROCS | KDBG_MATCH_DISABLE)
380
381 // Information about kdebug for user space consumption.
382 typedef struct {
383 // Size of buffers in number of events (kd_bufs).
384 int nkdbufs;
385 // True is tracing is disabled, false otherwise.
386 int nolog;
387 // Combined `kdebug_live_flags_t` and `kdebug_state_t`.
388 unsigned int flags;
389 // Number of threads in the thread map.
390 int nkdthreads;
391 // Owning process PID.
392 int bufid;
393 } kbufinfo_t;
394
395 // Header for CPU mapping list.
396 typedef struct {
397 uint32_t version_no;
398 uint32_t cpu_count;
399 } kd_cpumap_header;
400
401 // CPU map entry flags.
402 #define KDBG_CPUMAP_IS_IOP 0x1
403
404 // CPU map entries to map `cpuid` from events to names.
405 typedef struct {
406 uint32_t cpu_id;
407 uint32_t flags;
408 char name[32];
409 } kd_cpumap_ext;
410
411 // Match structured data from events.
412 typedef struct {
413 uint32_t kem_debugid;
414 uint32_t kem_padding;
415 uint64_t kem_args[4];
416 } kd_event_matcher;
417
418 // Options for `kdebug_enable` in the comm-page.
419 #define KDEBUG_COMMPAGE_ENABLE_TRACE 0x1
420 #define KDEBUG_COMMPAGE_ENABLE_TYPEFILTER 0x2
421 #define KDEBUG_COMMPAGE_CONTINUOUS 0x4
422
423 #pragma mark - Tests
424
425 // Test scenarios.
426 __enum_decl(kdebug_test_t, uint32_t, {
427 KDTEST_KERNEL_MACROS = 1,
428 KDTEST_OLD_TIMESTAMP,
429 KDTEST_FUTURE_TIMESTAMP,
430 KDTEST_SETUP_IOP,
431 KDTEST_SETUP_COPROCESSOR,
432 KDTEST_CONTINUOUS_TIMESTAMP,
433 KDTEST_ABSOLUTE_TIMESTAMP,
434 KDTEST_PAST_EVENT,
435 });
436
437 #pragma mark - Obsolete interfaces
438
439 // Some Apple-internal clients try to use the kernel macros in user space.
440 #ifndef KERNEL_DEBUG
441 #define KERNEL_DEBUG(...) do { } while (0)
442 #endif // !defined(KERNEL_DEBUG)
443
444 // Obsolete options for `kdebug_enable`.
445 #define KDEBUG_ENABLE_ENTROPY 0x002U
446 #define KDEBUG_ENABLE_CHUD 0x004U
447 #define KDEBUG_ENABLE_PPT 0x008U
448 #define KDEBUG_ENABLE_SERIAL 0x010U
449 #define KDEBUG_PPT (KDEBUG_ENABLE_PPT)
450 #define KDEBUG_COMMON (KDEBUG_ENABLE_TRACE | KDEBUG_ENABLE_PPT)
451
452 // Obsolete flags.
453 #define KDBG_LOCKINIT 0x0080
454 #define KDBG_RANGECHECK 0x00100000U
455 #define KDBG_VALCHECK 0x00200000U
456
457 // Type values for `kd_regtype`.
458 #define KDBG_CLASSTYPE 0x10000
459 #define KDBG_SUBCLSTYPE 0x20000
460 #define KDBG_RANGETYPE 0x40000
461 #define KDBG_TYPENONE 0x80000
462 #define KDBG_CKTYPES 0xF0000
463
464 typedef struct {
465 unsigned int type;
466 unsigned int value1;
467 unsigned int value2;
468 unsigned int value3;
469 unsigned int value4;
470 } kd_regtype;
471
472 // Entry for the legacy thread map system (replaced by stackshot).
473 typedef struct {
474 // A thread's unique ID.
475 #if defined(__arm64__)
476 uint64_t thread;
477 #else
478 uintptr_t thread __kernel_data_semantics;
479 #endif
480 // The process ID (or 1 for `kernproc`).
481 int valid;
482 // The name of the process owning this thread.
483 char command[20];
484 } kd_threadmap;
485
486 // Legacy CPU map entry.
487 typedef struct {
488 uint32_t cpu_id;
489 uint32_t flags;
490 char name[8];
491 } kd_cpumap;
492
493 // File header for legacy trace files.
494 typedef struct {
495 int version_no;
496 int thread_count;
497 uint64_t TOD_secs;
498 uint32_t TOD_usecs;
499 } RAW_header;
500
501 // Obsolete `version_no` for legacy trace files.
502 #define RAW_VERSION0 0x55aa0000
503 #define RAW_VERSION1 0x55aa0101
504 #define RAW_VERSION2 0x55aa0200
505
506 // Obsolete EnergyTracing definitions.
507
508 #define kEnTrCompKernel 2
509 #define kEnTrActKernSocket 1
510 #define kEnTrActKernSockRead 2
511 #define kEnTrActKernSockWrite 3
512 #define kEnTrActKernPoll 10
513 #define kEnTrActKernSelect 11
514 #define kEnTrActKernKQWait 12
515 #define kEnTrEvUnblocked 256
516 #define kEnTrFlagNonBlocking 0x1
517 #define kEnTrFlagNoWork 0x2
518
519 #if (KDEBUG_LEVEL >= KDEBUG_LEVEL_IST)
520 #define ENTR_SHOULDTRACE kdebug_enable
521 #define ENTR_KDTRACE(component, opcode, lifespan, id, quality, value) \
522 do { \
523 uint32_t kdcode__; \
524 uintptr_t highval__, lowval__, mask__ = 0xffffffff; \
525 kdcode__ = KDBG_CODE(DBG_ENERGYTRACE,component,opcode)|(lifespan); \
526 highval__ = ((value) >> 32) & mask__; \
527 lowval__ = (value) & mask__; \
528 ENTR_KDTRACEFUNC(kdcode__, id, quality, highval__, lowval__); \
529 } while(0)
530
531 #define kEnTrModAssociate (1 << 28)
532 #define ENTR_KDASSOCIATE(par_comp, par_opcode, par_act_id, \
533 sub_comp, sub_opcode, sub_act_id) \
534 do { \
535 unsigned sub_compcode = ((unsigned)sub_comp << 16) | sub_opcode; \
536 ENTR_KDTRACEFUNC(KDBG_CODE(DBG_ENERGYTRACE,par_comp,par_opcode), \
537 par_act_id, kEnTrModAssociate, sub_compcode, \
538 sub_act_id); \
539 } while(0)
540
541 #else // (KDEBUG_LEVEL >= KDEBUG_LEVEL_IST)
542
543 #define ENTR_SHOULDTRACE 0
544 #define ENTR_KDTRACE(component, opcode, lifespan, id, quality, value) do {} while (0)
545 #define ENTR_KDASSOCIATE(par_comp, par_opcode, par_act_id, sub_comp, sub_opcode, sub_act_id) do {} while (0)
546
547 #endif // (KDEBUG_LEVEL >= KDEBUG_LEVEL_IST)
548
549 #endif // !defined(DRIVERKIT)
550
551 __END_DECLS
552
553 #endif // !defined(BSD_KDEBUG_PRIVATE_H)
554