| 1 |
// Original design from: |
| 2 |
// ============================================================================= |
| 3 |
// XNU kperf/kpc |
| 4 |
// Available for 64-bit Intel/Apple Silicon, macOS/iOS, with root privileges |
| 5 |
// |
| 6 |
// References: |
| 7 |
// |
| 8 |
// XNU source (since xnu 2422.1.72): |
| 9 |
// https://github.com/apple/darwin-xnu/blob/main/osfmk/kern/kpc.h |
| 10 |
// https://github.com/apple/darwin-xnu/blob/main/bsd/kern/kern_kpc.c |
| 11 |
// |
| 12 |
// Lightweight PET (Profile Every Thread, since xnu 3789.1.32): |
| 13 |
// https://github.com/apple/darwin-xnu/blob/main/osfmk/kperf/pet.c |
| 14 |
// https://github.com/apple/darwin-xnu/blob/main/osfmk/kperf/kperf_kpc.c |
| 15 |
// |
| 16 |
// System Private frameworks (since macOS 10.11, iOS 8.0): |
| 17 |
// /System/Library/PrivateFrameworks/kperf.framework |
| 18 |
// /System/Library/PrivateFrameworks/kperfdata.framework |
| 19 |
// |
| 20 |
// Xcode framework (since Xcode 7.0): |
| 21 |
// /Applications/Xcode.app/Contents/SharedFrameworks/DVTInstrumentsFoundation.framework |
| 22 |
// |
| 23 |
// CPU database (plist files) |
| 24 |
// macOS (since macOS 10.11): |
| 25 |
// /usr/share/kpep/<name>.plist |
| 26 |
// iOS (copied from Xcode, since iOS 10.0, Xcode 8.0): |
| 27 |
// /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform |
| 28 |
// /DeviceSupport/<version>/DeveloperDiskImage.dmg/usr/share/kpep/<name>.plist |
| 29 |
// |
| 30 |
// |
| 31 |
// Created by YaoYuan <[email protected]> on 2021. |
| 32 |
// Released into the public domain (unlicense.org). |
| 33 |
// ============================================================================= |
| 34 |
|
| 35 |
#ifndef M1CYCLES_H |
| 36 |
#define M1CYCLES_H |
| 37 |
|
| 38 |
#include <stdbool.h> |
| 39 |
#include <stdint.h> |
| 40 |
#include <stdio.h> |
| 41 |
#include <stdlib.h> |
| 42 |
#include <string.h> |
| 43 |
|
| 44 |
#include <dlfcn.h> // for dlopen() and dlsym() |
| 45 |
#include <mach/mach_time.h> // for mach_absolute_time() |
| 46 |
#include <sys/kdebug.h> // for kdebug trace decode |
| 47 |
#include <sys/sysctl.h> // for sysctl() |
| 48 |
#include <unistd.h> // for usleep() |
| 49 |
|
| 50 |
struct performance_counters { |
| 51 |
double cycles; |
| 52 |
double branches; |
| 53 |
double missed_branches; |
| 54 |
double instructions; |
| 55 |
|
| 56 |
performance_counters(uint64_t c, uint64_t b, uint64_t m, uint64_t i) |
| 57 |
: cycles(c), branches(b), missed_branches(m), instructions(i) {} |
| 58 |
|
| 59 |
performance_counters(double c, double b, double m, double i) |
| 60 |
: cycles(c), branches(b), missed_branches(m), instructions(i) {} |
| 61 |
|
| 62 |
performance_counters(double init) |
| 63 |
: cycles(init), branches(init), missed_branches(init), |
| 64 |
instructions(init) {} |
| 65 |
|
| 66 |
inline performance_counters &operator-=(const performance_counters &other) { |
| 67 |
cycles -= other.cycles; |
| 68 |
branches -= other.branches; |
| 69 |
missed_branches -= other.missed_branches; |
| 70 |
instructions -= other.instructions; |
| 71 |
return *this; |
| 72 |
} |
| 73 |
|
| 74 |
inline performance_counters &min(const performance_counters &other) { |
| 75 |
cycles = other.cycles < cycles ? other.cycles : cycles; |
| 76 |
branches = other.branches < branches ? other.branches : branches; |
| 77 |
missed_branches = other.missed_branches < missed_branches |
| 78 |
? other.missed_branches |
| 79 |
: missed_branches; |
| 80 |
instructions = |
| 81 |
other.instructions < instructions ? other.instructions : instructions; |
| 82 |
return *this; |
| 83 |
} |
| 84 |
|
| 85 |
inline performance_counters &operator+=(const performance_counters &other) { |
| 86 |
cycles += other.cycles; |
| 87 |
branches += other.branches; |
| 88 |
missed_branches += other.missed_branches; |
| 89 |
instructions += other.instructions; |
| 90 |
return *this; |
| 91 |
} |
| 92 |
|
| 93 |
inline performance_counters &operator/=(double numerator) { |
| 94 |
cycles /= numerator; |
| 95 |
branches /= numerator; |
| 96 |
missed_branches /= numerator; |
| 97 |
instructions /= numerator; |
| 98 |
return *this; |
| 99 |
} |
| 100 |
}; |
| 101 |
|
| 102 |
inline performance_counters operator-(const performance_counters &a, |
| 103 |
const performance_counters &b) { |
| 104 |
return performance_counters(a.cycles - b.cycles, a.branches - b.branches, |
| 105 |
a.missed_branches - b.missed_branches, |
| 106 |
a.instructions - b.instructions); |
| 107 |
} |
| 108 |
|
| 109 |
typedef float f32; |
| 110 |
typedef double f64; |
| 111 |
typedef int8_t i8; |
| 112 |
typedef uint8_t u8; |
| 113 |
typedef int16_t i16; |
| 114 |
typedef uint16_t u16; |
| 115 |
typedef int32_t i32; |
| 116 |
typedef uint32_t u32; |
| 117 |
typedef int64_t i64; |
| 118 |
typedef uint64_t u64; |
| 119 |
typedef size_t usize; |
| 120 |
|
| 121 |
// ----------------------------------------------------------------------------- |
| 122 |
// <kperf.framework> header (reverse engineered) |
| 123 |
// This framework wraps some sysctl calls to communicate with the kpc in kernel. |
| 124 |
// Most functions requires root privileges, or process is "blessed". |
| 125 |
// ----------------------------------------------------------------------------- |
| 126 |
|
| 127 |
// Cross-platform class constants. |
| 128 |
#define KPC_CLASS_FIXED (0) |
| 129 |
#define KPC_CLASS_CONFIGURABLE (1) |
| 130 |
#define KPC_CLASS_POWER (2) |
| 131 |
#define KPC_CLASS_RAWPMU (3) |
| 132 |
|
| 133 |
// Cross-platform class mask constants. |
| 134 |
#define KPC_CLASS_FIXED_MASK (1u << KPC_CLASS_FIXED) // 1 |
| 135 |
#define KPC_CLASS_CONFIGURABLE_MASK (1u << KPC_CLASS_CONFIGURABLE) // 2 |
| 136 |
#define KPC_CLASS_POWER_MASK (1u << KPC_CLASS_POWER) // 4 |
| 137 |
#define KPC_CLASS_RAWPMU_MASK (1u << KPC_CLASS_RAWPMU) // 8 |
| 138 |
|
| 139 |
// PMU version constants. |
| 140 |
#define KPC_PMU_ERROR (0) // Error |
| 141 |
#define KPC_PMU_INTEL_V3 (1) // Intel |
| 142 |
#define KPC_PMU_ARM_APPLE (2) // ARM64 |
| 143 |
#define KPC_PMU_INTEL_V2 (3) // Old Intel |
| 144 |
#define KPC_PMU_ARM_V2 (4) // Old ARM |
| 145 |
|
| 146 |
// The maximum number of counters we could read from every class in one go. |
| 147 |
// ARMV7: FIXED: 1, CONFIGURABLE: 4 |
| 148 |
// ARM32: FIXED: 2, CONFIGURABLE: 6 |
| 149 |
// ARM64: FIXED: 2, CONFIGURABLE: CORE_NCTRS - FIXED (6 or 8) |
| 150 |
// x86: 32 |
| 151 |
#define KPC_MAX_COUNTERS 32 |
| 152 |
|
| 153 |
// Bits for defining what to do on an action. |
| 154 |
// Defined in https://github.com/apple/darwin-xnu/blob/main/osfmk/kperf/action.h |
| 155 |
#define KPERF_SAMPLER_TH_INFO (1U << 0) |
| 156 |
#define KPERF_SAMPLER_TH_SNAPSHOT (1U << 1) |
| 157 |
#define KPERF_SAMPLER_KSTACK (1U << 2) |
| 158 |
#define KPERF_SAMPLER_USTACK (1U << 3) |
| 159 |
#define KPERF_SAMPLER_PMC_THREAD (1U << 4) |
| 160 |
#define KPERF_SAMPLER_PMC_CPU (1U << 5) |
| 161 |
#define KPERF_SAMPLER_PMC_CONFIG (1U << 6) |
| 162 |
#define KPERF_SAMPLER_MEMINFO (1U << 7) |
| 163 |
#define KPERF_SAMPLER_TH_SCHEDULING (1U << 8) |
| 164 |
#define KPERF_SAMPLER_TH_DISPATCH (1U << 9) |
| 165 |
#define KPERF_SAMPLER_TK_SNAPSHOT (1U << 10) |
| 166 |
#define KPERF_SAMPLER_SYS_MEM (1U << 11) |
| 167 |
#define KPERF_SAMPLER_TH_INSCYC (1U << 12) |
| 168 |
#define KPERF_SAMPLER_TK_INFO (1U << 13) |
| 169 |
|
| 170 |
// Maximum number of kperf action ids. |
| 171 |
#define KPERF_ACTION_MAX (32) |
| 172 |
|
| 173 |
// Maximum number of kperf timer ids. |
| 174 |
#define KPERF_TIMER_MAX (8) |
| 175 |
|
| 176 |
// x86/arm config registers are 64-bit |
| 177 |
typedef u64 kpc_config_t; |
| 178 |
|
| 179 |
/// Print current CPU identification string to the buffer (same as snprintf), |
| 180 |
/// such as "cpu_7_8_10b282dc_46". This string can be used to locate the PMC |
| 181 |
/// database in /usr/share/kpep. |
| 182 |
/// @return string's length, or negative value if error occurs. |
| 183 |
/// @note This method does not requires root privileges. |
| 184 |
/// @details sysctl get(hw.cputype), get(hw.cpusubtype), |
| 185 |
/// get(hw.cpufamily), get(machdep.cpu.model) |
| 186 |
static int (*kpc_cpu_string)(char *buf, usize buf_size); |
| 187 |
|
| 188 |
/// Get the version of KPC that's being run. |
| 189 |
/// @return See `PMU version constants` above. |
| 190 |
/// @details sysctl get(kpc.pmu_version) |
| 191 |
static u32 (*kpc_pmu_version)(void); |
| 192 |
|
| 193 |
/// Get running PMC classes. |
| 194 |
/// @return See `class mask constants` above, |
| 195 |
/// 0 if error occurs or no class is set. |
| 196 |
/// @details sysctl get(kpc.counting) |
| 197 |
static u32 (*kpc_get_counting)(void); |
| 198 |
|
| 199 |
/// Set PMC classes to enable counting. |
| 200 |
/// @param classes See `class mask constants` above, set 0 to shutdown counting. |
| 201 |
/// @return 0 for success. |
| 202 |
/// @details sysctl set(kpc.counting) |
| 203 |
static int (*kpc_set_counting)(u32 classes); |
| 204 |
|
| 205 |
/// Get running PMC classes for current thread. |
| 206 |
/// @return See `class mask constants` above, |
| 207 |
/// 0 if error occurs or no class is set. |
| 208 |
/// @details sysctl get(kpc.thread_counting) |
| 209 |
static u32 (*kpc_get_thread_counting)(void); |
| 210 |
|
| 211 |
/// Set PMC classes to enable counting for current thread. |
| 212 |
/// @param classes See `class mask constants` above, set 0 to shutdown counting. |
| 213 |
/// @return 0 for success. |
| 214 |
/// @details sysctl set(kpc.thread_counting) |
| 215 |
static int (*kpc_set_thread_counting)(u32 classes); |
| 216 |
|
| 217 |
/// Get how many config registers there are for a given mask. |
| 218 |
/// For example: Intel may returns 1 for `KPC_CLASS_FIXED_MASK`, |
| 219 |
/// returns 4 for `KPC_CLASS_CONFIGURABLE_MASK`. |
| 220 |
/// @param classes See `class mask constants` above. |
| 221 |
/// @return 0 if error occurs or no class is set. |
| 222 |
/// @note This method does not requires root privileges. |
| 223 |
/// @details sysctl get(kpc.config_count) |
| 224 |
static u32 (*kpc_get_config_count)(u32 classes); |
| 225 |
|
| 226 |
/// Get config registers. |
| 227 |
/// @param classes see `class mask constants` above. |
| 228 |
/// @param config Config buffer to receive values, should not smaller than |
| 229 |
/// kpc_get_config_count(classes) * sizeof(kpc_config_t). |
| 230 |
/// @return 0 for success. |
| 231 |
/// @details sysctl get(kpc.config_count), get(kpc.config) |
| 232 |
static int (*kpc_get_config)(u32 classes, kpc_config_t *config); |
| 233 |
|
| 234 |
/// Set config registers. |
| 235 |
/// @param classes see `class mask constants` above. |
| 236 |
/// @param config Config buffer, should not smaller than |
| 237 |
/// kpc_get_config_count(classes) * sizeof(kpc_config_t). |
| 238 |
/// @return 0 for success. |
| 239 |
/// @details sysctl get(kpc.config_count), set(kpc.config) |
| 240 |
static int (*kpc_set_config)(u32 classes, kpc_config_t *config); |
| 241 |
|
| 242 |
/// Get how many counters there are for a given mask. |
| 243 |
/// For example: Intel may returns 3 for `KPC_CLASS_FIXED_MASK`, |
| 244 |
/// returns 4 for `KPC_CLASS_CONFIGURABLE_MASK`. |
| 245 |
/// @param classes See `class mask constants` above. |
| 246 |
/// @note This method does not requires root privileges. |
| 247 |
/// @details sysctl get(kpc.counter_count) |
| 248 |
static u32 (*kpc_get_counter_count)(u32 classes); |
| 249 |
|
| 250 |
/// Get counter accumulations. |
| 251 |
/// If `all_cpus` is true, the buffer count should not smaller than |
| 252 |
/// (cpu_count * counter_count). Otherwize, the buffer count should not smaller |
| 253 |
/// than (counter_count). |
| 254 |
/// @see kpc_get_counter_count(), kpc_cpu_count(). |
| 255 |
/// @param all_cpus true for all CPUs, false for current cpu. |
| 256 |
/// @param classes See `class mask constants` above. |
| 257 |
/// @param curcpu A pointer to receive current cpu id, can be NULL. |
| 258 |
/// @param buf Buffer to receive counter's value. |
| 259 |
/// @return 0 for success. |
| 260 |
/// @details sysctl get(hw.ncpu), get(kpc.counter_count), get(kpc.counters) |
| 261 |
static int (*kpc_get_cpu_counters)(bool all_cpus, u32 classes, int *curcpu, |
| 262 |
u64 *buf); |
| 263 |
|
| 264 |
/// Get counter accumulations for current thread. |
| 265 |
/// @param tid Thread id, should be 0. |
| 266 |
/// @param buf_count The number of buf's elements (not bytes), |
| 267 |
/// should not smaller than kpc_get_counter_count(). |
| 268 |
/// @param buf Buffer to receive counter's value. |
| 269 |
/// @return 0 for success. |
| 270 |
/// @details sysctl get(kpc.thread_counters) |
| 271 |
static int (*kpc_get_thread_counters)(u32 tid, u32 buf_count, u64 *buf); |
| 272 |
|
| 273 |
/// Acquire/release the counters used by the Power Manager. |
| 274 |
/// @param val 1:acquire, 0:release |
| 275 |
/// @return 0 for success. |
| 276 |
/// @details sysctl set(kpc.force_all_ctrs) |
| 277 |
static int (*kpc_force_all_ctrs_set)(int val); |
| 278 |
|
| 279 |
/// Get the state of all_ctrs. |
| 280 |
/// @return 0 for success. |
| 281 |
/// @details sysctl get(kpc.force_all_ctrs) |
| 282 |
static int (*kpc_force_all_ctrs_get)(int *val_out); |
| 283 |
|
| 284 |
/// Set number of actions, should be `KPERF_ACTION_MAX`. |
| 285 |
/// @details sysctl set(kperf.action.count) |
| 286 |
static int (*kperf_action_count_set)(u32 count); |
| 287 |
|
| 288 |
/// Get number of actions. |
| 289 |
/// @details sysctl get(kperf.action.count) |
| 290 |
static int (*kperf_action_count_get)(u32 *count); |
| 291 |
|
| 292 |
/// Set what to sample when a trigger fires an action, e.g. |
| 293 |
/// `KPERF_SAMPLER_PMC_CPU`. |
| 294 |
/// @details sysctl set(kperf.action.samplers) |
| 295 |
static int (*kperf_action_samplers_set)(u32 actionid, u32 sample); |
| 296 |
|
| 297 |
/// Get what to sample when a trigger fires an action. |
| 298 |
/// @details sysctl get(kperf.action.samplers) |
| 299 |
static int (*kperf_action_samplers_get)(u32 actionid, u32 *sample); |
| 300 |
|
| 301 |
/// Apply a task filter to the action, -1 to disable filter. |
| 302 |
/// @details sysctl set(kperf.action.filter_by_task) |
| 303 |
static int (*kperf_action_filter_set_by_task)(u32 actionid, i32 port); |
| 304 |
|
| 305 |
/// Apply a pid filter to the action, -1 to disable filter. |
| 306 |
/// @details sysctl set(kperf.action.filter_by_pid) |
| 307 |
static int (*kperf_action_filter_set_by_pid)(u32 actionid, i32 pid); |
| 308 |
|
| 309 |
/// Set number of time triggers, should be `KPERF_TIMER_MAX`. |
| 310 |
/// @details sysctl set(kperf.timer.count) |
| 311 |
static int (*kperf_timer_count_set)(u32 count); |
| 312 |
|
| 313 |
/// Get number of time triggers. |
| 314 |
/// @details sysctl get(kperf.timer.count) |
| 315 |
static int (*kperf_timer_count_get)(u32 *count); |
| 316 |
|
| 317 |
/// Set timer number and period. |
| 318 |
/// @details sysctl set(kperf.timer.period) |
| 319 |
static int (*kperf_timer_period_set)(u32 actionid, u64 tick); |
| 320 |
|
| 321 |
/// Get timer number and period. |
| 322 |
/// @details sysctl get(kperf.timer.period) |
| 323 |
static int (*kperf_timer_period_get)(u32 actionid, u64 *tick); |
| 324 |
|
| 325 |
/// Set timer number and actionid. |
| 326 |
/// @details sysctl set(kperf.timer.action) |
| 327 |
static int (*kperf_timer_action_set)(u32 actionid, u32 timerid); |
| 328 |
|
| 329 |
/// Get timer number and actionid. |
| 330 |
/// @details sysctl get(kperf.timer.action) |
| 331 |
static int (*kperf_timer_action_get)(u32 actionid, u32 *timerid); |
| 332 |
|
| 333 |
/// Set which timer ID does PET (Profile Every Thread). |
| 334 |
/// @details sysctl set(kperf.timer.pet_timer) |
| 335 |
static int (*kperf_timer_pet_set)(u32 timerid); |
| 336 |
|
| 337 |
/// Get which timer ID does PET (Profile Every Thread). |
| 338 |
/// @details sysctl get(kperf.timer.pet_timer) |
| 339 |
static int (*kperf_timer_pet_get)(u32 *timerid); |
| 340 |
|
| 341 |
/// Enable or disable sampling. |
| 342 |
/// @details sysctl set(kperf.sampling) |
| 343 |
static int (*kperf_sample_set)(u32 enabled); |
| 344 |
|
| 345 |
/// Get is currently sampling. |
| 346 |
/// @details sysctl get(kperf.sampling) |
| 347 |
static int (*kperf_sample_get)(u32 *enabled); |
| 348 |
|
| 349 |
/// Reset kperf: stop sampling, kdebug, timers and actions. |
| 350 |
/// @return 0 for success. |
| 351 |
static int (*kperf_reset)(void); |
| 352 |
|
| 353 |
/// Nanoseconds to CPU ticks. |
| 354 |
static u64 (*kperf_ns_to_ticks)(u64 ns); |
| 355 |
|
| 356 |
/// CPU ticks to nanoseconds. |
| 357 |
static u64 (*kperf_ticks_to_ns)(u64 ticks); |
| 358 |
|
| 359 |
/// CPU ticks frequency (mach_absolute_time). |
| 360 |
static u64 (*kperf_tick_frequency)(void); |
| 361 |
|
| 362 |
/// Get lightweight PET mode (not in kperf.framework). |
| 363 |
static int kperf_lightweight_pet_get(u32 *enabled) { |
| 364 |
if (!enabled) |
| 365 |
return -1; |
| 366 |
usize size = 4; |
| 367 |
return sysctlbyname("kperf.lightweight_pet", enabled, &size, NULL, 0); |
| 368 |
} |
| 369 |
|
| 370 |
/// Set lightweight PET mode (not in kperf.framework). |
| 371 |
static int kperf_lightweight_pet_set(u32 enabled) { |
| 372 |
return sysctlbyname("kperf.lightweight_pet", NULL, NULL, &enabled, 4); |
| 373 |
} |
| 374 |
|
| 375 |
// ----------------------------------------------------------------------------- |
| 376 |
// <kperfdata.framework> header (reverse engineered) |
| 377 |
// This framework provides some functions to access the local CPU database. |
| 378 |
// These functions do not require root privileges. |
| 379 |
// ----------------------------------------------------------------------------- |
| 380 |
|
| 381 |
// KPEP CPU archtecture constants. |
| 382 |
#define KPEP_ARCH_I386 0 |
| 383 |
#define KPEP_ARCH_X86_64 1 |
| 384 |
#define KPEP_ARCH_ARM 2 |
| 385 |
#define KPEP_ARCH_ARM64 3 |
| 386 |
|
| 387 |
/// KPEP event (size: 48/28 bytes on 64/32 bit OS) |
| 388 |
typedef struct kpep_event { |
| 389 |
const char *name; ///< Unique name of a event, such as "INST_RETIRED.ANY". |
| 390 |
const char *description; ///< Description for this event. |
| 391 |
const char *errata; ///< Errata, currently NULL. |
| 392 |
const char *alias; ///< Alias name, such as "Instructions", "Cycles". |
| 393 |
const char *fallback; ///< Fallback event name for fixed counter. |
| 394 |
u32 mask; |
| 395 |
u8 number; |
| 396 |
u8 umask; |
| 397 |
u8 reserved; |
| 398 |
u8 is_fixed; |
| 399 |
} kpep_event; |
| 400 |
|
| 401 |
/// KPEP database (size: 144/80 bytes on 64/32 bit OS) |
| 402 |
typedef struct kpep_db { |
| 403 |
const char *name; ///< Database name, such as "haswell". |
| 404 |
const char *cpu_id; ///< Plist name, such as "cpu_7_8_10b282dc". |
| 405 |
const char *marketing_name; ///< Marketing name, such as "Intel Haswell". |
| 406 |
void *plist_data; ///< Plist data (CFDataRef), currently NULL. |
| 407 |
void *event_map; ///< All events (CFDict<CFSTR(event_name), kpep_event *>). |
| 408 |
kpep_event |
| 409 |
*event_arr; ///< Event struct buffer (sizeof(kpep_event) * events_count). |
| 410 |
kpep_event **fixed_event_arr; ///< Fixed counter events (sizeof(kpep_event *) |
| 411 |
///< * fixed_counter_count) |
| 412 |
void *alias_map; ///< All aliases (CFDict<CFSTR(event_name), kpep_event *>). |
| 413 |
usize reserved_1; |
| 414 |
usize reserved_2; |
| 415 |
usize reserved_3; |
| 416 |
usize event_count; ///< All events count. |
| 417 |
usize alias_count; |
| 418 |
usize fixed_counter_count; |
| 419 |
usize config_counter_count; |
| 420 |
usize power_counter_count; |
| 421 |
u32 archtecture; ///< see `KPEP CPU archtecture constants` above. |
| 422 |
u32 fixed_counter_bits; |
| 423 |
u32 config_counter_bits; |
| 424 |
u32 power_counter_bits; |
| 425 |
} kpep_db; |
| 426 |
|
| 427 |
/// KPEP config (size: 80/44 bytes on 64/32 bit OS) |
| 428 |
typedef struct kpep_config { |
| 429 |
kpep_db *db; |
| 430 |
kpep_event **ev_arr; ///< (sizeof(kpep_event *) * counter_count), init NULL |
| 431 |
usize *ev_map; ///< (sizeof(usize *) * counter_count), init 0 |
| 432 |
usize *ev_idx; ///< (sizeof(usize *) * counter_count), init -1 |
| 433 |
u32 *flags; ///< (sizeof(u32 *) * counter_count), init 0 |
| 434 |
u64 *kpc_periods; ///< (sizeof(u64 *) * counter_count), init 0 |
| 435 |
usize event_count; /// kpep_config_events_count() |
| 436 |
usize counter_count; |
| 437 |
u32 classes; ///< See `class mask constants` above. |
| 438 |
u32 config_counter; |
| 439 |
u32 power_counter; |
| 440 |
u32 reserved; |
| 441 |
} kpep_config; |
| 442 |
|
| 443 |
/// Error code for kpep_config_xxx() and kpep_db_xxx() functions. |
| 444 |
typedef enum { |
| 445 |
KPEP_CONFIG_ERROR_NONE = 0, |
| 446 |
KPEP_CONFIG_ERROR_INVALID_ARGUMENT = 1, |
| 447 |
KPEP_CONFIG_ERROR_OUT_OF_MEMORY = 2, |
| 448 |
KPEP_CONFIG_ERROR_IO = 3, |
| 449 |
KPEP_CONFIG_ERROR_BUFFER_TOO_SMALL = 4, |
| 450 |
KPEP_CONFIG_ERROR_CUR_SYSTEM_UNKNOWN = 5, |
| 451 |
KPEP_CONFIG_ERROR_DB_PATH_INVALID = 6, |
| 452 |
KPEP_CONFIG_ERROR_DB_NOT_FOUND = 7, |
| 453 |
KPEP_CONFIG_ERROR_DB_ARCH_UNSUPPORTED = 8, |
| 454 |
KPEP_CONFIG_ERROR_DB_VERSION_UNSUPPORTED = 9, |
| 455 |
KPEP_CONFIG_ERROR_DB_CORRUPT = 10, |
| 456 |
KPEP_CONFIG_ERROR_EVENT_NOT_FOUND = 11, |
| 457 |
KPEP_CONFIG_ERROR_CONFLICTING_EVENTS = 12, |
| 458 |
KPEP_CONFIG_ERROR_COUNTERS_NOT_FORCED = 13, |
| 459 |
KPEP_CONFIG_ERROR_EVENT_UNAVAILABLE = 14, |
| 460 |
KPEP_CONFIG_ERROR_ERRNO = 15, |
| 461 |
KPEP_CONFIG_ERROR_MAX |
| 462 |
} kpep_config_error_code; |
| 463 |
|
| 464 |
/// Error description for kpep_config_error_code. |
| 465 |
static const char *kpep_config_error_names[KPEP_CONFIG_ERROR_MAX] = { |
| 466 |
"none", |
| 467 |
"invalid argument", |
| 468 |
"out of memory", |
| 469 |
"I/O", |
| 470 |
"buffer too small", |
| 471 |
"current system unknown", |
| 472 |
"database path invalid", |
| 473 |
"database not found", |
| 474 |
"database architecture unsupported", |
| 475 |
"database version unsupported", |
| 476 |
"database corrupt", |
| 477 |
"event not found", |
| 478 |
"conflicting events", |
| 479 |
"all counters must be forced", |
| 480 |
"event unavailable", |
| 481 |
"check errno"}; |
| 482 |
|
| 483 |
/// Error description. |
| 484 |
static const char *kpep_config_error_desc(int code) { |
| 485 |
if (0 <= code && code < KPEP_CONFIG_ERROR_MAX) { |
| 486 |
return kpep_config_error_names[code]; |
| 487 |
} |
| 488 |
return "unknown error"; |
| 489 |
} |
| 490 |
|
| 491 |
/// Create a config. |
| 492 |
/// @param db A kpep db, see kpep_db_create() |
| 493 |
/// @param cfg_ptr A pointer to receive the new config. |
| 494 |
/// @return kpep_config_error_code, 0 for success. |
| 495 |
static int (*kpep_config_create)(kpep_db *db, kpep_config **cfg_ptr); |
| 496 |
|
| 497 |
/// Free the config. |
| 498 |
static void (*kpep_config_free)(kpep_config *cfg); |
| 499 |
|
| 500 |
/// Add an event to config. |
| 501 |
/// @param cfg The config. |
| 502 |
/// @param ev_ptr A event pointer. |
| 503 |
/// @param flag 0: all, 1: user space only |
| 504 |
/// @param err Error bitmap pointer, can be NULL. |
| 505 |
/// If return value is `CONFLICTING_EVENTS`, this bitmap contains |
| 506 |
/// the conflicted event indices, e.g. "1 << 2" means index 2. |
| 507 |
/// @return kpep_config_error_code, 0 for success. |
| 508 |
static int (*kpep_config_add_event)(kpep_config *cfg, kpep_event **ev_ptr, |
| 509 |
u32 flag, u32 *err); |
| 510 |
|
| 511 |
/// Remove event at index. |
| 512 |
/// @return kpep_config_error_code, 0 for success. |
| 513 |
static int (*kpep_config_remove_event)(kpep_config *cfg, usize idx); |
| 514 |
|
| 515 |
/// Force all counters. |
| 516 |
/// @return kpep_config_error_code, 0 for success. |
| 517 |
static int (*kpep_config_force_counters)(kpep_config *cfg); |
| 518 |
|
| 519 |
/// Get events count. |
| 520 |
/// @return kpep_config_error_code, 0 for success. |
| 521 |
static int (*kpep_config_events_count)(kpep_config *cfg, usize *count_ptr); |
| 522 |
|
| 523 |
/// Get all event pointers. |
| 524 |
/// @param buf A buffer to receive event pointers. |
| 525 |
/// @param buf_size The buffer's size in bytes, should not smaller than |
| 526 |
/// kpep_config_events_count() * sizeof(void *). |
| 527 |
/// @return kpep_config_error_code, 0 for success. |
| 528 |
static int (*kpep_config_events)(kpep_config *cfg, kpep_event **buf, |
| 529 |
usize buf_size); |
| 530 |
|
| 531 |
/// Get kpc register configs. |
| 532 |
/// @param buf A buffer to receive kpc register configs. |
| 533 |
/// @param buf_size The buffer's size in bytes, should not smaller than |
| 534 |
/// kpep_config_kpc_count() * sizeof(kpc_config_t). |
| 535 |
/// @return kpep_config_error_code, 0 for success. |
| 536 |
static int (*kpep_config_kpc)(kpep_config *cfg, kpc_config_t *buf, |
| 537 |
usize buf_size); |
| 538 |
|
| 539 |
/// Get kpc register config count. |
| 540 |
/// @return kpep_config_error_code, 0 for success. |
| 541 |
static int (*kpep_config_kpc_count)(kpep_config *cfg, usize *count_ptr); |
| 542 |
|
| 543 |
/// Get kpc classes. |
| 544 |
/// @param classes See `class mask constants` above. |
| 545 |
/// @return kpep_config_error_code, 0 for success. |
| 546 |
static int (*kpep_config_kpc_classes)(kpep_config *cfg, u32 *classes_ptr); |
| 547 |
|
| 548 |
/// Get the index mapping from event to counter. |
| 549 |
/// @param buf A buffer to receive indexes. |
| 550 |
/// @param buf_size The buffer's size in bytes, should not smaller than |
| 551 |
/// kpep_config_events_count() * sizeof(kpc_config_t). |
| 552 |
/// @return kpep_config_error_code, 0 for success. |
| 553 |
static int (*kpep_config_kpc_map)(kpep_config *cfg, usize *buf, usize buf_size); |
| 554 |
|
| 555 |
/// Open a kpep database file in "/usr/share/kpep/" or "/usr/local/share/kpep/". |
| 556 |
/// @param name File name, for example "haswell", "cpu_100000c_1_92fb37c8". |
| 557 |
/// Pass NULL for current CPU. |
| 558 |
/// @return kpep_config_error_code, 0 for success. |
| 559 |
static int (*kpep_db_create)(const char *name, kpep_db **db_ptr); |
| 560 |
|
| 561 |
/// Free the kpep database. |
| 562 |
static void (*kpep_db_free)(kpep_db *db); |
| 563 |
|
| 564 |
/// Get the database's name. |
| 565 |
/// @return kpep_config_error_code, 0 for success. |
| 566 |
static int (*kpep_db_name)(kpep_db *db, const char **name); |
| 567 |
|
| 568 |
/// Get the event alias count. |
| 569 |
/// @return kpep_config_error_code, 0 for success. |
| 570 |
static int (*kpep_db_aliases_count)(kpep_db *db, usize *count); |
| 571 |
|
| 572 |
/// Get all alias. |
| 573 |
/// @param buf A buffer to receive all alias strings. |
| 574 |
/// @param buf_size The buffer's size in bytes, |
| 575 |
/// should not smaller than kpep_db_aliases_count() * sizeof(void *). |
| 576 |
/// @return kpep_config_error_code, 0 for success. |
| 577 |
static int (*kpep_db_aliases)(kpep_db *db, const char **buf, usize buf_size); |
| 578 |
|
| 579 |
/// Get counters count for given classes. |
| 580 |
/// @param classes 1: Fixed, 2: Configurable. |
| 581 |
/// @return kpep_config_error_code, 0 for success. |
| 582 |
static int (*kpep_db_counters_count)(kpep_db *db, u8 classes, usize *count); |
| 583 |
|
| 584 |
/// Get all event count. |
| 585 |
/// @return kpep_config_error_code, 0 for success. |
| 586 |
static int (*kpep_db_events_count)(kpep_db *db, usize *count); |
| 587 |
|
| 588 |
/// Get all events. |
| 589 |
/// @param buf A buffer to receive all event pointers. |
| 590 |
/// @param buf_size The buffer's size in bytes, |
| 591 |
/// should not smaller than kpep_db_events_count() * sizeof(void *). |
| 592 |
/// @return kpep_config_error_code, 0 for success. |
| 593 |
static int (*kpep_db_events)(kpep_db *db, kpep_event **buf, usize buf_size); |
| 594 |
|
| 595 |
/// Get one event by name. |
| 596 |
/// @return kpep_config_error_code, 0 for success. |
| 597 |
static int (*kpep_db_event)(kpep_db *db, const char *name, kpep_event **ev_ptr); |
| 598 |
|
| 599 |
/// Get event's name. |
| 600 |
/// @return kpep_config_error_code, 0 for success. |
| 601 |
static int (*kpep_event_name)(kpep_event *ev, const char **name_ptr); |
| 602 |
|
| 603 |
/// Get event's alias. |
| 604 |
/// @return kpep_config_error_code, 0 for success. |
| 605 |
static int (*kpep_event_alias)(kpep_event *ev, const char **alias_ptr); |
| 606 |
|
| 607 |
/// Get event's description. |
| 608 |
/// @return kpep_config_error_code, 0 for success. |
| 609 |
static int (*kpep_event_description)(kpep_event *ev, const char **str_ptr); |
| 610 |
|
| 611 |
// ----------------------------------------------------------------------------- |
| 612 |
// load kperf/kperfdata dynamic library |
| 613 |
// ----------------------------------------------------------------------------- |
| 614 |
|
| 615 |
typedef struct { |
| 616 |
const char *name; |
| 617 |
void **impl; |
| 618 |
} lib_symbol; |
| 619 |
|
| 620 |
#define lib_nelems(x) (sizeof(x) / sizeof((x)[0])) |
| 621 |
#define lib_symbol_def(name) \ |
| 622 |
{ #name, (void **)&name } |
| 623 |
|
| 624 |
static const lib_symbol lib_symbols_kperf[] = { |
| 625 |
lib_symbol_def(kpc_pmu_version), |
| 626 |
lib_symbol_def(kpc_cpu_string), |
| 627 |
lib_symbol_def(kpc_set_counting), |
| 628 |
lib_symbol_def(kpc_get_counting), |
| 629 |
lib_symbol_def(kpc_set_thread_counting), |
| 630 |
lib_symbol_def(kpc_get_thread_counting), |
| 631 |
lib_symbol_def(kpc_get_config_count), |
| 632 |
lib_symbol_def(kpc_get_counter_count), |
| 633 |
lib_symbol_def(kpc_set_config), |
| 634 |
lib_symbol_def(kpc_get_config), |
| 635 |
lib_symbol_def(kpc_get_cpu_counters), |
| 636 |
lib_symbol_def(kpc_get_thread_counters), |
| 637 |
lib_symbol_def(kpc_force_all_ctrs_set), |
| 638 |
lib_symbol_def(kpc_force_all_ctrs_get), |
| 639 |
lib_symbol_def(kperf_action_count_set), |
| 640 |
lib_symbol_def(kperf_action_count_get), |
| 641 |
lib_symbol_def(kperf_action_samplers_set), |
| 642 |
lib_symbol_def(kperf_action_samplers_get), |
| 643 |
lib_symbol_def(kperf_action_filter_set_by_task), |
| 644 |
lib_symbol_def(kperf_action_filter_set_by_pid), |
| 645 |
lib_symbol_def(kperf_timer_count_set), |
| 646 |
lib_symbol_def(kperf_timer_count_get), |
| 647 |
lib_symbol_def(kperf_timer_period_set), |
| 648 |
lib_symbol_def(kperf_timer_period_get), |
| 649 |
lib_symbol_def(kperf_timer_action_set), |
| 650 |
lib_symbol_def(kperf_timer_action_get), |
| 651 |
lib_symbol_def(kperf_sample_set), |
| 652 |
lib_symbol_def(kperf_sample_get), |
| 653 |
lib_symbol_def(kperf_reset), |
| 654 |
lib_symbol_def(kperf_timer_pet_set), |
| 655 |
lib_symbol_def(kperf_timer_pet_get), |
| 656 |
lib_symbol_def(kperf_ns_to_ticks), |
| 657 |
lib_symbol_def(kperf_ticks_to_ns), |
| 658 |
lib_symbol_def(kperf_tick_frequency), |
| 659 |
}; |
| 660 |
|
| 661 |
static const lib_symbol lib_symbols_kperfdata[] = { |
| 662 |
lib_symbol_def(kpep_config_create), |
| 663 |
lib_symbol_def(kpep_config_free), |
| 664 |
lib_symbol_def(kpep_config_add_event), |
| 665 |
lib_symbol_def(kpep_config_remove_event), |
| 666 |
lib_symbol_def(kpep_config_force_counters), |
| 667 |
lib_symbol_def(kpep_config_events_count), |
| 668 |
lib_symbol_def(kpep_config_events), |
| 669 |
lib_symbol_def(kpep_config_kpc), |
| 670 |
lib_symbol_def(kpep_config_kpc_count), |
| 671 |
lib_symbol_def(kpep_config_kpc_classes), |
| 672 |
lib_symbol_def(kpep_config_kpc_map), |
| 673 |
lib_symbol_def(kpep_db_create), |
| 674 |
lib_symbol_def(kpep_db_free), |
| 675 |
lib_symbol_def(kpep_db_name), |
| 676 |
lib_symbol_def(kpep_db_aliases_count), |
| 677 |
lib_symbol_def(kpep_db_aliases), |
| 678 |
lib_symbol_def(kpep_db_counters_count), |
| 679 |
lib_symbol_def(kpep_db_events_count), |
| 680 |
lib_symbol_def(kpep_db_events), |
| 681 |
lib_symbol_def(kpep_db_event), |
| 682 |
lib_symbol_def(kpep_event_name), |
| 683 |
lib_symbol_def(kpep_event_alias), |
| 684 |
lib_symbol_def(kpep_event_description), |
| 685 |
}; |
| 686 |
|
| 687 |
#define lib_path_kperf "/System/Library/PrivateFrameworks/kperf.framework/kperf" |
| 688 |
#define lib_path_kperfdata \ |
| 689 |
"/System/Library/PrivateFrameworks/kperfdata.framework/kperfdata" |
| 690 |
|
| 691 |
static bool lib_inited = false; |
| 692 |
static bool lib_has_err = false; |
| 693 |
static char lib_err_msg[256]; |
| 694 |
|
| 695 |
static void *lib_handle_kperf = NULL; |
| 696 |
static void *lib_handle_kperfdata = NULL; |
| 697 |
|
| 698 |
static void lib_deinit(void) { |
| 699 |
lib_inited = false; |
| 700 |
lib_has_err = false; |
| 701 |
if (lib_handle_kperf) |
| 702 |
dlclose(lib_handle_kperf); |
| 703 |
if (lib_handle_kperfdata) |
| 704 |
dlclose(lib_handle_kperfdata); |
| 705 |
lib_handle_kperf = NULL; |
| 706 |
lib_handle_kperfdata = NULL; |
| 707 |
for (usize i = 0; i < lib_nelems(lib_symbols_kperf); i++) { |
| 708 |
const lib_symbol *symbol = &lib_symbols_kperf[i]; |
| 709 |
*symbol->impl = NULL; |
| 710 |
} |
| 711 |
for (usize i = 0; i < lib_nelems(lib_symbols_kperfdata); i++) { |
| 712 |
const lib_symbol *symbol = &lib_symbols_kperfdata[i]; |
| 713 |
*symbol->impl = NULL; |
| 714 |
} |
| 715 |
} |
| 716 |
|
| 717 |
static bool lib_init(void) { |
| 718 |
#define return_err() \ |
| 719 |
do { \ |
| 720 |
lib_deinit(); \ |
| 721 |
lib_inited = true; \ |
| 722 |
lib_has_err = true; \ |
| 723 |
return false; \ |
| 724 |
} while (false) |
| 725 |
|
| 726 |
if (lib_inited) |
| 727 |
return !lib_has_err; |
| 728 |
|
| 729 |
// load dynamic library |
| 730 |
lib_handle_kperf = dlopen(lib_path_kperf, RTLD_LAZY); |
| 731 |
if (!lib_handle_kperf) { |
| 732 |
snprintf(lib_err_msg, sizeof(lib_err_msg), |
| 733 |
"Failed to load kperf.framework, message: %s.", dlerror()); |
| 734 |
return_err(); |
| 735 |
} |
| 736 |
lib_handle_kperfdata = dlopen(lib_path_kperfdata, RTLD_LAZY); |
| 737 |
if (!lib_handle_kperfdata) { |
| 738 |
snprintf(lib_err_msg, sizeof(lib_err_msg), |
| 739 |
"Failed to load kperfdata.framework, message: %s.", dlerror()); |
| 740 |
return_err(); |
| 741 |
} |
| 742 |
|
| 743 |
// load symbol address from dynamic library |
| 744 |
for (usize i = 0; i < lib_nelems(lib_symbols_kperf); i++) { |
| 745 |
const lib_symbol *symbol = &lib_symbols_kperf[i]; |
| 746 |
*symbol->impl = dlsym(lib_handle_kperf, symbol->name); |
| 747 |
if (!*symbol->impl) { |
| 748 |
snprintf(lib_err_msg, sizeof(lib_err_msg), |
| 749 |
"Failed to load kperf function: %s.", symbol->name); |
| 750 |
return_err(); |
| 751 |
} |
| 752 |
} |
| 753 |
for (usize i = 0; i < lib_nelems(lib_symbols_kperfdata); i++) { |
| 754 |
const lib_symbol *symbol = &lib_symbols_kperfdata[i]; |
| 755 |
*symbol->impl = dlsym(lib_handle_kperfdata, symbol->name); |
| 756 |
if (!*symbol->impl) { |
| 757 |
snprintf(lib_err_msg, sizeof(lib_err_msg), |
| 758 |
"Failed to load kperfdata function: %s.", symbol->name); |
| 759 |
return_err(); |
| 760 |
} |
| 761 |
} |
| 762 |
|
| 763 |
lib_inited = true; |
| 764 |
lib_has_err = false; |
| 765 |
return true; |
| 766 |
|
| 767 |
#undef return_err |
| 768 |
} |
| 769 |
|
| 770 |
// ----------------------------------------------------------------------------- |
| 771 |
// kdebug private structs |
| 772 |
// https://github.com/apple/darwin-xnu/blob/main/bsd/sys_private/kdebug_private.h |
| 773 |
// ----------------------------------------------------------------------------- |
| 774 |
|
| 775 |
/* |
| 776 |
* Ensure that both LP32 and LP64 variants of arm64 use the same kd_buf |
| 777 |
* structure. |
| 778 |
*/ |
| 779 |
#if defined(__arm64__) |
| 780 |
typedef uint64_t kd_buf_argtype; |
| 781 |
#else |
| 782 |
typedef uintptr_t kd_buf_argtype; |
| 783 |
#endif |
| 784 |
|
| 785 |
typedef struct { |
| 786 |
uint64_t timestamp; |
| 787 |
kd_buf_argtype arg1; |
| 788 |
kd_buf_argtype arg2; |
| 789 |
kd_buf_argtype arg3; |
| 790 |
kd_buf_argtype arg4; |
| 791 |
kd_buf_argtype arg5; /* the thread ID */ |
| 792 |
uint32_t debugid; /* see <sys/kdebug.h> */ |
| 793 |
|
| 794 |
/* |
| 795 |
* Ensure that both LP32 and LP64 variants of arm64 use the same kd_buf |
| 796 |
* structure. |
| 797 |
*/ |
| 798 |
#if defined(__LP64__) || defined(__arm64__) |
| 799 |
uint32_t cpuid; /* cpu index, from 0 */ |
| 800 |
kd_buf_argtype unused; |
| 801 |
#endif |
| 802 |
} kd_buf; |
| 803 |
|
| 804 |
/* bits for the type field of kd_regtype */ |
| 805 |
#define KDBG_CLASSTYPE 0x10000 |
| 806 |
#define KDBG_SUBCLSTYPE 0x20000 |
| 807 |
#define KDBG_RANGETYPE 0x40000 |
| 808 |
#define KDBG_TYPENONE 0x80000 |
| 809 |
#define KDBG_CKTYPES 0xF0000 |
| 810 |
|
| 811 |
/* only trace at most 4 types of events, at the code granularity */ |
| 812 |
#define KDBG_VALCHECK 0x00200000U |
| 813 |
|
| 814 |
typedef struct { |
| 815 |
unsigned int type; |
| 816 |
unsigned int value1; |
| 817 |
unsigned int value2; |
| 818 |
unsigned int value3; |
| 819 |
unsigned int value4; |
| 820 |
} kd_regtype; |
| 821 |
|
| 822 |
typedef struct { |
| 823 |
/* number of events that can fit in the buffers */ |
| 824 |
int nkdbufs; |
| 825 |
/* set if trace is disabled */ |
| 826 |
int nolog; |
| 827 |
/* kd_ctrl_page.flags */ |
| 828 |
unsigned int flags; |
| 829 |
/* number of threads in thread map */ |
| 830 |
int nkdthreads; |
| 831 |
/* the owning pid */ |
| 832 |
int bufid; |
| 833 |
} kbufinfo_t; |
| 834 |
|
| 835 |
// ----------------------------------------------------------------------------- |
| 836 |
// kdebug utils |
| 837 |
// ----------------------------------------------------------------------------- |
| 838 |
|
| 839 |
/// Clean up trace buffers and reset ktrace/kdebug/kperf. |
| 840 |
/// @return 0 on success. |
| 841 |
static int kdebug_reset(void) { |
| 842 |
int mib[3] = {CTL_KERN, KERN_KDEBUG, KERN_KDREMOVE}; |
| 843 |
return sysctl(mib, 3, NULL, NULL, NULL, 0); |
| 844 |
} |
| 845 |
|
| 846 |
/// Disable and reinitialize the trace buffers. |
| 847 |
/// @return 0 on success. |
| 848 |
static int kdebug_reinit(void) { |
| 849 |
int mib[3] = {CTL_KERN, KERN_KDEBUG, KERN_KDSETUP}; |
| 850 |
return sysctl(mib, 3, NULL, NULL, NULL, 0); |
| 851 |
} |
| 852 |
|
| 853 |
/// Set debug filter. |
| 854 |
static int kdebug_setreg(kd_regtype *kdr) { |
| 855 |
int mib[3] = {CTL_KERN, KERN_KDEBUG, KERN_KDSETREG}; |
| 856 |
usize size = sizeof(kd_regtype); |
| 857 |
return sysctl(mib, 3, kdr, &size, NULL, 0); |
| 858 |
} |
| 859 |
|
| 860 |
/// Set maximum number of trace entries (kd_buf). |
| 861 |
/// Only allow allocation up to half the available memory (sane_size). |
| 862 |
/// @return 0 on success. |
| 863 |
static int kdebug_trace_setbuf(int nbufs) { |
| 864 |
int mib[4] = {CTL_KERN, KERN_KDEBUG, KERN_KDSETBUF, nbufs}; |
| 865 |
return sysctl(mib, 4, NULL, NULL, NULL, 0); |
| 866 |
} |
| 867 |
|
| 868 |
/// Enable or disable kdebug trace. |
| 869 |
/// Trace buffer must already be initialized. |
| 870 |
/// @return 0 on success. |
| 871 |
static int kdebug_trace_enable(bool enable) { |
| 872 |
int mib[4] = {CTL_KERN, KERN_KDEBUG, KERN_KDENABLE, enable}; |
| 873 |
return sysctl(mib, 4, NULL, 0, NULL, 0); |
| 874 |
} |
| 875 |
|
| 876 |
/// Retrieve trace buffer information from kernel. |
| 877 |
/// @return 0 on success. |
| 878 |
static int kdebug_get_bufinfo(kbufinfo_t *info) { |
| 879 |
if (!info) |
| 880 |
return -1; |
| 881 |
int mib[3] = {CTL_KERN, KERN_KDEBUG, KERN_KDGETBUF}; |
| 882 |
size_t needed = sizeof(kbufinfo_t); |
| 883 |
return sysctl(mib, 3, info, &needed, NULL, 0); |
| 884 |
} |
| 885 |
|
| 886 |
/// Retrieve trace buffers from kernel. |
| 887 |
/// @param buf Memory to receive buffer data, array of `kd_buf`. |
| 888 |
/// @param len Length of `buf` in bytes. |
| 889 |
/// @param count Number of trace entries (kd_buf) obtained. |
| 890 |
/// @return 0 on success. |
| 891 |
static int kdebug_trace_read(void *buf, usize len, usize *count) { |
| 892 |
if (count) |
| 893 |
*count = 0; |
| 894 |
if (!buf || !len) |
| 895 |
return -1; |
| 896 |
|
| 897 |
// Note: the input and output units are not the same. |
| 898 |
// input: bytes |
| 899 |
// output: number of kd_buf |
| 900 |
int mib[3] = {CTL_KERN, KERN_KDEBUG, KERN_KDREADTR}; |
| 901 |
int ret = sysctl(mib, 3, buf, &len, NULL, 0); |
| 902 |
if (ret != 0) |
| 903 |
return ret; |
| 904 |
*count = len; |
| 905 |
return 0; |
| 906 |
} |
| 907 |
|
| 908 |
/// Block until there are new buffers filled or `timeout_ms` have passed. |
| 909 |
/// @param timeout_ms timeout milliseconds, 0 means wait forever. |
| 910 |
/// @param suc set true if new buffers filled. |
| 911 |
/// @return 0 on success. |
| 912 |
static int kdebug_wait(usize timeout_ms, bool *suc) { |
| 913 |
if (timeout_ms == 0) |
| 914 |
return -1; |
| 915 |
int mib[3] = {CTL_KERN, KERN_KDEBUG, KERN_KDBUFWAIT}; |
| 916 |
usize val = timeout_ms; |
| 917 |
int ret = sysctl(mib, 3, NULL, &val, NULL, 0); |
| 918 |
if (suc) |
| 919 |
*suc = !!val; |
| 920 |
return ret; |
| 921 |
} |
| 922 |
|
| 923 |
// ----------------------------------------------------------------------------- |
| 924 |
// Demo |
| 925 |
// ----------------------------------------------------------------------------- |
| 926 |
|
| 927 |
#define EVENT_NAME_MAX 8 |
| 928 |
|
| 929 |
typedef struct { |
| 930 |
const char *alias; /// name for print |
| 931 |
const char *names[EVENT_NAME_MAX]; /// name from pmc db |
| 932 |
} event_alias; |
| 933 |
|
| 934 |
/// Event names from /usr/share/kpep/<name>.plist |
| 935 |
static const event_alias profile_events[] = { |
| 936 |
{"cycles", |
| 937 |
{ |
| 938 |
"FIXED_CYCLES", // Apple A7-A15//CORE_ACTIVE_CYCLE |
| 939 |
"CPU_CLK_UNHALTED.THREAD", // Intel Core 1th-10th |
| 940 |
"CPU_CLK_UNHALTED.CORE", // Intel Yonah, Merom |
| 941 |
}}, |
| 942 |
{"instructions", |
| 943 |
{ |
| 944 |
"FIXED_INSTRUCTIONS", // Apple A7-A15 |
| 945 |
"INST_RETIRED.ANY" // Intel Yonah, Merom, Core 1th-10th |
| 946 |
}}, |
| 947 |
{"branches", |
| 948 |
{ |
| 949 |
"INST_BRANCH", // Apple A7-A15 |
| 950 |
"BR_INST_RETIRED.ALL_BRANCHES", // Intel Core 1th-10th |
| 951 |
"INST_RETIRED.ANY", // Intel Yonah, Merom |
| 952 |
}}, |
| 953 |
{"branch-misses", |
| 954 |
{ |
| 955 |
"BRANCH_MISPRED_NONSPEC", // Apple A7-A15, since iOS 15, macOS 12 |
| 956 |
"BRANCH_MISPREDICT", // Apple A7-A14 |
| 957 |
"BR_MISP_RETIRED.ALL_BRANCHES", // Intel Core 2th-10th |
| 958 |
"BR_INST_RETIRED.MISPRED", // Intel Yonah, Merom |
| 959 |
}}, |
| 960 |
}; |
| 961 |
|
| 962 |
static kpep_event *get_event(kpep_db *db, const event_alias *alias) { |
| 963 |
for (usize j = 0; j < EVENT_NAME_MAX; j++) { |
| 964 |
const char *name = alias->names[j]; |
| 965 |
if (!name) |
| 966 |
break; |
| 967 |
kpep_event *ev = NULL; |
| 968 |
if (kpep_db_event(db, name, &ev) == 0) { |
| 969 |
return ev; |
| 970 |
} |
| 971 |
} |
| 972 |
return NULL; |
| 973 |
} |
| 974 |
|
| 975 |
kpc_config_t regs[KPC_MAX_COUNTERS] = {0}; |
| 976 |
usize counter_map[KPC_MAX_COUNTERS] = {0}; |
| 977 |
u64 counters_0[KPC_MAX_COUNTERS] = {0}; |
| 978 |
u64 counters_1[KPC_MAX_COUNTERS] = {0}; |
| 979 |
const usize ev_count = sizeof(profile_events) / sizeof(profile_events[0]); |
| 980 |
|
| 981 |
bool setup_performance_counters() { |
| 982 |
static bool init = false; |
| 983 |
static bool worked = false; |
| 984 |
|
| 985 |
if (init) { |
| 986 |
return worked; |
| 987 |
} |
| 988 |
init = true; |
| 989 |
|
| 990 |
// load dylib |
| 991 |
if (!lib_init()) { |
| 992 |
printf("Error: %s\n", lib_err_msg); |
| 993 |
return (worked = false); |
| 994 |
} |
| 995 |
|
| 996 |
// check permission |
| 997 |
int force_ctrs = 0; |
| 998 |
if (kpc_force_all_ctrs_get(&force_ctrs)) { |
| 999 |
// printf("Permission denied, xnu/kpc requires root privileges.\n"); |
| 1000 |
return (worked = false); |
| 1001 |
} |
| 1002 |
int ret; |
| 1003 |
// load pmc db |
| 1004 |
kpep_db *db = NULL; |
| 1005 |
if ((ret = kpep_db_create(NULL, &db))) { |
| 1006 |
printf("Error: cannot load pmc database: %d.\n", ret); |
| 1007 |
return (worked = false); |
| 1008 |
} |
| 1009 |
printf("loaded db: %s (%s)\n", db->name, db->marketing_name); |
| 1010 |
|
| 1011 |
// create a config |
| 1012 |
kpep_config *cfg = NULL; |
| 1013 |
if ((ret = kpep_config_create(db, &cfg))) { |
| 1014 |
printf("Failed to create kpep config: %d (%s).\n", ret, |
| 1015 |
kpep_config_error_desc(ret)); |
| 1016 |
return (worked = false); |
| 1017 |
} |
| 1018 |
if ((ret = kpep_config_force_counters(cfg))) { |
| 1019 |
printf("Failed to force counters: %d (%s).\n", ret, |
| 1020 |
kpep_config_error_desc(ret)); |
| 1021 |
return (worked = false); |
| 1022 |
} |
| 1023 |
|
| 1024 |
// get events |
| 1025 |
kpep_event *ev_arr[ev_count] = {0}; |
| 1026 |
for (usize i = 0; i < ev_count; i++) { |
| 1027 |
const event_alias *alias = profile_events + i; |
| 1028 |
ev_arr[i] = get_event(db, alias); |
| 1029 |
if (!ev_arr[i]) { |
| 1030 |
printf("Cannot find event: %s.\n", alias->alias); |
| 1031 |
return (worked = false); |
| 1032 |
} |
| 1033 |
} |
| 1034 |
|
| 1035 |
// add event to config |
| 1036 |
for (usize i = 0; i < ev_count; i++) { |
| 1037 |
kpep_event *ev = ev_arr[i]; |
| 1038 |
if ((ret = kpep_config_add_event(cfg, &ev, 0, NULL))) { |
| 1039 |
printf("Failed to add event: %d (%s).\n", ret, |
| 1040 |
kpep_config_error_desc(ret)); |
| 1041 |
return (worked = false); |
| 1042 |
} |
| 1043 |
} |
| 1044 |
|
| 1045 |
// prepare buffer and config |
| 1046 |
u32 classes = 0; |
| 1047 |
usize reg_count = 0; |
| 1048 |
if ((ret = kpep_config_kpc_classes(cfg, &classes))) { |
| 1049 |
printf("Failed get kpc classes: %d (%s).\n", ret, |
| 1050 |
kpep_config_error_desc(ret)); |
| 1051 |
return (worked = false); |
| 1052 |
} |
| 1053 |
if ((ret = kpep_config_kpc_count(cfg, ®_count))) { |
| 1054 |
printf("Failed get kpc count: %d (%s).\n", ret, |
| 1055 |
kpep_config_error_desc(ret)); |
| 1056 |
return (worked = false); |
| 1057 |
} |
| 1058 |
if ((ret = kpep_config_kpc_map(cfg, counter_map, sizeof(counter_map)))) { |
| 1059 |
printf("Failed get kpc map: %d (%s).\n", ret, kpep_config_error_desc(ret)); |
| 1060 |
return (worked = false); |
| 1061 |
} |
| 1062 |
if ((ret = kpep_config_kpc(cfg, regs, sizeof(regs)))) { |
| 1063 |
printf("Failed get kpc registers: %d (%s).\n", ret, |
| 1064 |
kpep_config_error_desc(ret)); |
| 1065 |
return (worked = false); |
| 1066 |
} |
| 1067 |
|
| 1068 |
// set config to kernel |
| 1069 |
if ((ret = kpc_force_all_ctrs_set(1))) { |
| 1070 |
printf("Failed force all ctrs: %d.\n", ret); |
| 1071 |
return (worked = false); |
| 1072 |
} |
| 1073 |
if ((classes & KPC_CLASS_CONFIGURABLE_MASK) && reg_count) { |
| 1074 |
if ((ret = kpc_set_config(classes, regs))) { |
| 1075 |
printf("Failed set kpc config: %d.\n", ret); |
| 1076 |
return (worked = false); |
| 1077 |
} |
| 1078 |
} |
| 1079 |
|
| 1080 |
// start counting |
| 1081 |
if ((ret = kpc_set_counting(classes))) { |
| 1082 |
printf("Failed set counting: %d.\n", ret); |
| 1083 |
return (worked = false); |
| 1084 |
} |
| 1085 |
if ((ret = kpc_set_thread_counting(classes))) { |
| 1086 |
printf("Failed set thread counting: %d.\n", ret); |
| 1087 |
return (worked = false); |
| 1088 |
} |
| 1089 |
|
| 1090 |
return (worked = true); |
| 1091 |
} |
| 1092 |
|
| 1093 |
inline performance_counters get_counters() { |
| 1094 |
static bool warned = false; |
| 1095 |
int ret; |
| 1096 |
// get counters before |
| 1097 |
if ((ret = kpc_get_thread_counters(0, KPC_MAX_COUNTERS, counters_0))) { |
| 1098 |
if (!warned) { |
| 1099 |
|
| 1100 |
printf("Failed get thread counters before: %d.\n", ret); |
| 1101 |
warned = true; |
| 1102 |
} |
| 1103 |
return 1; |
| 1104 |
} |
| 1105 |
/*printf("counters value:\n"); |
| 1106 |
for (usize i = 0; i < ev_count; i++) { |
| 1107 |
const event_alias *alias = profile_events + i; |
| 1108 |
usize idx = counter_map[i]; |
| 1109 |
u64 val = counters_1[idx] - counters_0[idx]; |
| 1110 |
printf("%14s: %llu\n", alias->alias, val); |
| 1111 |
}*/ |
| 1112 |
return performance_counters{ |
| 1113 |
counters_0[counter_map[0]], counters_0[counter_map[2]], |
| 1114 |
counters_0[counter_map[3]], counters_0[counter_map[1]]}; |
| 1115 |
} |
| 1116 |
|
| 1117 |
#endif |