Files
hakmem/core/tiny_debug_ring.c
Moe Charm (CI) 984cca41ef P0 Optimization: Shared Pool fast path with O(1) metadata lookup
Performance Results:
- Throughput: 2.66M ops/s → 3.8M ops/s (+43% improvement)
- sp_meta_find_or_create: O(N) linear scan → O(1) direct pointer
- Stage 2 metadata scan: 100% → 10-20% (80-90% reduction via hints)

Core Optimizations:

1. O(1) Metadata Lookup (superslab_types.h)
   - Added `shared_meta` pointer field to SuperSlab struct
   - Eliminates O(N) linear search through ss_metadata[] array
   - First access: O(N) scan + cache | Subsequent: O(1) direct return

2. sp_meta_find_or_create Fast Path (hakmem_shared_pool.c)
   - Check cached ss->shared_meta first before linear scan
   - Cache pointer after successful linear scan for future lookups
   - Reduces 7.8% CPU hotspot to near-zero for hot paths

3. Stage 2 Class Hints Fast Path (hakmem_shared_pool_acquire.c)
   - Try class_hints[class_idx] FIRST before full metadata scan
   - Uses O(1) ss->shared_meta lookup for hint validation
   - __builtin_expect() for branch prediction optimization
   - 80-90% of acquire calls now skip full metadata scan

4. Proper Initialization (ss_allocation_box.c)
   - Initialize shared_meta = NULL in superslab_allocate()
   - Ensures correct NULL-check semantics for new SuperSlabs

Additional Improvements:
- Updated ptr_trace and debug ring for release build efficiency
- Enhanced ENV variable documentation and analysis
- Added learner_env_box.h for configuration management
- Various Box optimizations for reduced overhead

Thread Safety:
- All atomic operations use correct memory ordering
- shared_meta cached under mutex protection
- Lock-free Stage 2 uses proper CAS with acquire/release semantics

Testing:
- Benchmark: 1M iterations, 3.8M ops/s stable
- Build: Clean compile RELEASE=0 and RELEASE=1
- No crashes, memory leaks, or correctness issues

Next Optimization Candidates:
- P1: Per-SuperSlab free slot bitmap for O(1) slot claiming
- P2: Reduce Stage 2 critical section size
- P3: Page pre-faulting (MAP_POPULATE)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-04 16:21:54 +09:00

245 lines
9.1 KiB
C

#include "tiny_debug_ring.h"
#include "hakmem_build_flags.h"
#include "hakmem_tiny.h"
#include "hakmem_trace_master.h" // Phase 4c: Master trace control
#include "hakmem_stats_master.h" // Phase 4d: Master stats control
#include <signal.h>
#include <stdatomic.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <ucontext.h>
#if HAKMEM_BUILD_RELEASE && !HAKMEM_DEBUG_VERBOSE
// In release builds without verbose debug, provide no-op stubs.
// These are needed for LTO builds where inline stubs may not be visible.
void tiny_debug_ring_init(void) {
// No-op in release builds
}
void tiny_debug_ring_record(uint16_t event, uint16_t class_idx, void* ptr, uintptr_t aux) {
(void)event;
(void)class_idx;
(void)ptr;
(void)aux;
// No-op in release builds
}
#else
#define TINY_RING_IGNORE(expr) do { ssize_t _tw_ret = (expr); (void)_tw_ret; } while(0)
#define TINY_RING_CAP 4096u
typedef struct {
uintptr_t ptr;
uintptr_t aux;
uint16_t event;
uint16_t class_idx;
} TinyRingEntry;
static TinyRingEntry g_tiny_ring[TINY_RING_CAP];
static _Atomic uint32_t g_tiny_ring_head = 0;
static int g_tiny_ring_enabled = 0;
typedef struct {
const char* name;
size_t len;
} TinyRingName;
static TinyRingName tiny_ring_event_name(uint16_t event) {
switch (event) {
case TINY_RING_EVENT_ALLOC_ENTER: return (TinyRingName){"alloc_enter", 11};
case TINY_RING_EVENT_ALLOC_SUCCESS: return (TinyRingName){"alloc_ok", 8};
case TINY_RING_EVENT_ALLOC_NULL: return (TinyRingName){"alloc_null", 10};
case TINY_RING_EVENT_ALLOC_REFILL_START: return (TinyRingName){"refill_start", 12};
case TINY_RING_EVENT_ALLOC_REFILL_NULL: return (TinyRingName){"refill_null", 11};
case TINY_RING_EVENT_ALLOC_BIND: return (TinyRingName){"bind", 4};
case TINY_RING_EVENT_FREE_ENTER: return (TinyRingName){"free_enter", 10};
case TINY_RING_EVENT_FREE_FAST: return (TinyRingName){"free_fast", 8};
case TINY_RING_EVENT_FREE_REMOTE: return (TinyRingName){"free_remote", 11};
case TINY_RING_EVENT_FREE_LOCAL: return (TinyRingName){"free_local", 10};
case TINY_RING_EVENT_FREE_RETURN_MAG: return (TinyRingName){"free_mag", 7};
case TINY_RING_EVENT_SUPERSLAB_ADOPT: return (TinyRingName){"ss_adopt", 8};
case TINY_RING_EVENT_SUPERSLAB_ALLOC: return (TinyRingName){"ss_alloc", 8};
case TINY_RING_EVENT_SUPERSLAB_PUBLISH: return (TinyRingName){"ss_publish", 10};
case TINY_RING_EVENT_SUPERSLAB_ADOPT_FAIL: return (TinyRingName){"ss_adopt_fail", 13};
case TINY_RING_EVENT_REMOTE_PUSH: return (TinyRingName){"remote_push", 11};
case TINY_RING_EVENT_REMOTE_INVALID: return (TinyRingName){"remote_invalid", 14};
case TINY_RING_EVENT_REMOTE_DRAIN: return (TinyRingName){"remote_drain", 12};
case TINY_RING_EVENT_OWNER_ACQUIRE: return (TinyRingName){"owner_acq", 9};
case TINY_RING_EVENT_OWNER_RELEASE: return (TinyRingName){"owner_rel", 9};
case TINY_RING_EVENT_FRONT_BYPASS: return (TinyRingName){"front_bypass", 12};
case TINY_RING_EVENT_MAILBOX_PUBLISH: return (TinyRingName){"mailbox_publish", 15};
case TINY_RING_EVENT_MAILBOX_FETCH: return (TinyRingName){"mailbox_fetch", 13};
case TINY_RING_EVENT_MAILBOX_FETCH_NULL: return (TinyRingName){"mailbox_fetch_null", 18};
case TINY_RING_EVENT_ROUTE: return (TinyRingName){"route", 5};
case TINY_RING_EVENT_TLS_SLL_REJECT: return (TinyRingName){"tls_sll_reject", 14};
case TINY_RING_EVENT_TLS_SLL_SENTINEL: return (TinyRingName){"tls_sll_sentinel", 16};
case TINY_RING_EVENT_TLS_SLL_HDR_CORRUPT: return (TinyRingName){"tls_sll_hdr_corrupt", 20};
default: return (TinyRingName){"unknown", 7};
}
}
static void tiny_ring_write_dec(int fd, uint64_t value) {
char buf[32];
int pos = 31;
if (value == 0) {
buf[pos--] = '0';
} else {
while (value > 0 && pos >= 0) {
buf[pos--] = (char)('0' + (value % 10));
value /= 10;
}
}
int len = 31 - pos;
TINY_RING_IGNORE(write(fd, buf + pos + 1, len));
}
static void tiny_ring_write_hex(int fd, uintptr_t value) {
static const char* hex = "0123456789abcdef";
char buf[2 + sizeof(uintptr_t) * 2 + 1];
buf[0] = '0';
buf[1] = 'x';
for (int i = (int)(sizeof(uintptr_t) * 2) - 1; i >= 0; --i) {
buf[2 + i] = hex[value & 0xFu];
value >>= 4;
}
buf[2 + sizeof(uintptr_t) * 2] = '\0';
TINY_RING_IGNORE(write(fd, buf, 2 + sizeof(uintptr_t) * 2));
}
static void tiny_debug_ring_dump(int fd, uintptr_t fault_addr) {
const char hdr[] = "\n[Tiny Debug Ring Dump]\n";
TINY_RING_IGNORE(write(fd, hdr, sizeof(hdr) - 1));
const char addr_prefix[] = "fault_addr=";
TINY_RING_IGNORE(write(fd, addr_prefix, sizeof(addr_prefix) - 1));
tiny_ring_write_hex(fd, fault_addr);
TINY_RING_IGNORE(write(fd, "\n", 1));
uint32_t head = atomic_load_explicit(&g_tiny_ring_head, memory_order_relaxed);
uint32_t count = head < TINY_RING_CAP ? head : TINY_RING_CAP;
for (uint32_t i = 0; i < count; i++) {
uint32_t idx = (head - count + i) & (TINY_RING_CAP - 1u);
TinyRingEntry ent = g_tiny_ring[idx];
TINY_RING_IGNORE(write(fd, "[", 1));
tiny_ring_write_dec(fd, idx);
const char mid[] = "] event=";
TINY_RING_IGNORE(write(fd, mid, sizeof(mid) - 1));
TinyRingName name = tiny_ring_event_name(ent.event);
TINY_RING_IGNORE(write(fd, name.name, name.len));
const char cls[] = " class=";
TINY_RING_IGNORE(write(fd, cls, sizeof(cls) - 1));
tiny_ring_write_dec(fd, ent.class_idx);
const char ptr_prefix[] = " ptr=";
TINY_RING_IGNORE(write(fd, ptr_prefix, sizeof(ptr_prefix) - 1));
tiny_ring_write_hex(fd, ent.ptr);
const char aux_prefix[] = " aux=";
TINY_RING_IGNORE(write(fd, aux_prefix, sizeof(aux_prefix) - 1));
tiny_ring_write_hex(fd, ent.aux);
TINY_RING_IGNORE(write(fd, "\n", 1));
}
}
static void tiny_debug_ring_sigsegv(int signo, siginfo_t* info, void* uctx) {
uintptr_t ip = 0;
#if defined(__x86_64__)
if (uctx) {
ucontext_t* uc = (ucontext_t*)uctx;
#ifdef REG_RIP
ip = (uintptr_t)uc->uc_mcontext.gregs[REG_RIP];
#else
(void)uc; // REG_RIP not available on this platform
#endif
}
#endif
if (g_tiny_ring_enabled) {
uintptr_t fault = info ? (uintptr_t)info->si_addr : 0;
#if defined(__x86_64__)
#ifdef REG_RIP
if (ip != 0) {
const char rip_prefix[] = "rip=";
TINY_RING_IGNORE(write(STDERR_FILENO, rip_prefix, sizeof(rip_prefix) - 1));
tiny_ring_write_hex(STDERR_FILENO, ip);
TINY_RING_IGNORE(write(STDERR_FILENO, "\n", 1));
}
#endif
#endif
tiny_debug_ring_dump(STDERR_FILENO, fault);
}
const char msg[] = "[Tiny Debug Ring] captured SIGSEGV\n";
TINY_RING_IGNORE(write(STDERR_FILENO, msg, sizeof(msg) - 1));
#if defined(__x86_64__)
#ifdef REG_RIP
if (ip != 0) {
const char rip_prefix[] = "rip=";
TINY_RING_IGNORE(write(STDERR_FILENO, rip_prefix, sizeof(rip_prefix) - 1));
tiny_ring_write_hex(STDERR_FILENO, ip);
TINY_RING_IGNORE(write(STDERR_FILENO, "\n", 1));
}
#endif
#endif
_exit(128 + signo);
}
static void tiny_debug_ring_sigusr(int signo, siginfo_t* info, void* uctx) {
(void)signo;
(void)info;
(void)uctx;
if (g_tiny_ring_enabled) {
tiny_debug_ring_dump(STDERR_FILENO, 0);
const char msg[] = "[Tiny Debug Ring] SIGUSR2 dump\n";
TINY_RING_IGNORE(write(STDERR_FILENO, msg, sizeof(msg) - 1));
}
}
void tiny_debug_ring_init(void) {
#if HAKMEM_BUILD_RELEASE
return; // No env reads or hooks in release builds
#endif
if (g_tiny_ring_enabled) return;
// Unified trace: HAKMEM_TINY_TRACE_RING or HAKMEM_TRACE=ring
if (!hak_trace_check("HAKMEM_TINY_TRACE_RING", "ring")) {
return;
}
g_tiny_ring_enabled = 1;
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_SIGINFO | SA_RESETHAND;
sa.sa_sigaction = tiny_debug_ring_sigsegv;
sigaction(SIGSEGV, &sa, NULL);
struct sigaction su;
sigemptyset(&su.sa_mask);
su.sa_flags = SA_SIGINFO | SA_RESTART;
su.sa_sigaction = tiny_debug_ring_sigusr;
sigaction(SIGUSR2, &su, NULL);
}
void tiny_debug_ring_record(uint16_t event, uint16_t class_idx, void* ptr, uintptr_t aux) {
if (!g_tiny_ring_enabled) return;
uint32_t idx = atomic_fetch_add_explicit(&g_tiny_ring_head, 1u, memory_order_relaxed);
TinyRingEntry entry;
entry.ptr = (uintptr_t)ptr;
entry.aux = aux;
entry.event = event;
entry.class_idx = class_idx;
g_tiny_ring[idx & (TINY_RING_CAP - 1u)] = entry;
}
__attribute__((constructor))
static void tiny_debug_ring_ctor(void) {
tiny_debug_ring_init();
}
__attribute__((destructor))
static void tiny_debug_ring_dtor(void) {
#if HAKMEM_BUILD_RELEASE
return; // Skip env access in release builds
#endif
if (hak_stats_check("HAKMEM_TINY_DUMP_RING_ATEXIT", "ring")) {
tiny_debug_ring_dump(STDERR_FILENO, 0);
}
}
#endif // HAKMEM_BUILD_RELEASE && !HAKMEM_DEBUG_VERBOSE