Files
hakmem/core/hakmem_tiny_bg_spill.c
Moe Charm (CI) c9053a43ac Phase 6-2.3~6-2.5: Critical bug fixes + SuperSlab optimization (WIP)
## Phase 6-2.3: Fix 4T Larson crash (active counter bug) 
**Problem:** 4T Larson crashed with "free(): invalid pointer", OOM errors
**Root cause:** core/hakmem_tiny_refill_p0.inc.h:103
  - P0 batch refill moved freelist blocks to TLS cache
  - Active counter NOT incremented → double-decrement on free
  - Counter underflows → SuperSlab appears full → OOM → crash
**Fix:** Added ss_active_add(tls->ss, from_freelist);
**Result:** 4T stable at 838K ops/s 

## Phase 6-2.4: Fix SEGV in random_mixed/mid_large_mt benchmarks 
**Problem:** bench_random_mixed_hakmem, bench_mid_large_mt_hakmem → immediate SEGV
**Root cause #1:** core/box/hak_free_api.inc.h:92-95
  - "Guess loop" dereferenced unmapped memory when registry lookup failed
**Root cause #2:** core/box/hak_free_api.inc.h:115
  - Header magic check dereferenced unmapped memory
**Fix:**
  1. Removed dangerous guess loop (lines 92-95)
  2. Added hak_is_memory_readable() check before dereferencing header
     (core/hakmem_internal.h:277-294 - uses mincore() syscall)
**Result:**
  - random_mixed (2KB): SEGV → 2.22M ops/s 
  - random_mixed (4KB): SEGV → 2.58M ops/s 
  - Larson 4T: no regression (838K ops/s) 

## Phase 6-2.5: Performance investigation + SuperSlab fix (WIP) ⚠️
**Problem:** Severe performance gaps (19-26x slower than system malloc)
**Investigation:** Task agent identified root cause
  - hak_is_memory_readable() syscall overhead (100-300 cycles per free)
  - ALL frees hit unmapped_header_fallback path
  - SuperSlab lookup NEVER called
  - Why? g_use_superslab = 0 (disabled by diet mode)

**Root cause:** core/hakmem_tiny_init.inc:104-105
  - Diet mode (default ON) disables SuperSlab
  - SuperSlab defaults to 1 (hakmem_config.c:334)
  - BUT diet mode overrides it to 0 during init

**Fix:** Separate SuperSlab from diet mode
  - SuperSlab: Performance-critical (fast alloc/free)
  - Diet mode: Memory efficiency (magazine capacity limits only)
  - Both are independent features, should not interfere

**Status:** ⚠️ INCOMPLETE - New SEGV discovered after fix
  - SuperSlab lookup now works (confirmed via debug output)
  - But benchmark crashes (Exit 139) after ~20 lookups
  - Needs further investigation

**Files modified:**
- core/hakmem_tiny_init.inc:99-109 - Removed diet mode override
- PERFORMANCE_INVESTIGATION_REPORT.md - Task agent analysis (303x instruction gap)

**Next steps:**
- Investigate new SEGV (likely SuperSlab free path bug)
- OR: Revert Phase 6-2.5 changes if blocking progress

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-07 20:31:01 +09:00

99 lines
3.8 KiB
C

#include "hakmem_tiny_bg_spill.h"
#include "hakmem_tiny_superslab.h" // For SuperSlab, TinySlabMeta, ss_active_dec_one
#include "hakmem_super_registry.h" // For hak_super_lookup
#include "tiny_remote.h"
#include "hakmem_tiny.h"
#include <pthread.h>
static inline uint32_t tiny_self_u32_guard(void) {
return (uint32_t)(uintptr_t)pthread_self();
}
#include <stdlib.h> // For getenv, atoi
// Global variables
int g_bg_spill_enable = 0; // HAKMEM_TINY_BG_SPILL=1
int g_bg_spill_target = 128; // HAKMEM_TINY_BG_TARGET (per class)
int g_bg_spill_max_batch = 128; // HAKMEM_TINY_BG_MAX_BATCH
_Atomic uintptr_t g_bg_spill_head[TINY_NUM_CLASSES];
_Atomic uint32_t g_bg_spill_len[TINY_NUM_CLASSES];
void bg_spill_init(void) {
// Parse environment variables
char* bs = getenv("HAKMEM_TINY_BG_SPILL");
if (bs) g_bg_spill_enable = (atoi(bs) != 0) ? 1 : 0;
char* bt2 = getenv("HAKMEM_TINY_BG_TARGET");
if (bt2) { int v = atoi(bt2); if (v > 0 && v <= 8192) g_bg_spill_target = v; }
char* mb = getenv("HAKMEM_TINY_BG_MAX_BATCH");
if (mb) { int v = atoi(mb); if (v > 0 && v <= 4096) g_bg_spill_max_batch = v; }
// Initialize atomic queues
for (int k = 0; k < TINY_NUM_CLASSES; k++) {
atomic_store_explicit(&g_bg_spill_head[k], (uintptr_t)0, memory_order_relaxed);
atomic_store_explicit(&g_bg_spill_len[k], 0u, memory_order_relaxed);
}
}
void bg_spill_drain_class(int class_idx, pthread_mutex_t* lock) {
uint32_t approx = atomic_load_explicit(&g_bg_spill_len[class_idx], memory_order_relaxed);
if (approx == 0) return;
uintptr_t chain = atomic_exchange_explicit(&g_bg_spill_head[class_idx], (uintptr_t)0, memory_order_acq_rel);
if (chain == 0) return;
// Split chain up to max_batch
int processed = 0;
void* rest = NULL;
void* cur = (void*)chain;
void* prev = NULL;
while (cur && processed < g_bg_spill_max_batch) {
prev = cur;
cur = *(void**)cur;
processed++;
}
if (cur != NULL) { rest = cur; *(void**)prev = NULL; }
// Return processed nodes to SS freelists
pthread_mutex_lock(lock);
uint32_t self_tid = tiny_self_u32_guard();
void* node = (void*)chain;
while (node) {
void* next = *(void**)node;
SuperSlab* owner_ss = hak_super_lookup(node);
if (owner_ss && owner_ss->magic == SUPERSLAB_MAGIC) {
int slab_idx = slab_index_for(owner_ss, node);
TinySlabMeta* meta = &owner_ss->slabs[slab_idx];
if (!tiny_remote_guard_allow_local_push(owner_ss, slab_idx, meta, node, "bg_spill", self_tid)) {
(void)ss_remote_push(owner_ss, slab_idx, node);
if (meta->used > 0) meta->used--;
node = next;
continue;
}
void* prev = meta->freelist;
*(void**)node = prev;
meta->freelist = node;
tiny_failfast_log("bg_spill", owner_ss->size_class, owner_ss, meta, node, prev);
meta->used--;
// Active was decremented at free time
}
node = next;
}
pthread_mutex_unlock(lock);
if (processed > 0) {
atomic_fetch_sub_explicit(&g_bg_spill_len[class_idx], (uint32_t)processed, memory_order_relaxed);
}
if (rest) {
// Prepend remainder back to head
uintptr_t old_head;
void* tail = rest;
while (*(void**)tail) tail = *(void**)tail;
do {
old_head = atomic_load_explicit(&g_bg_spill_head[class_idx], memory_order_acquire);
*(void**)tail = (void*)old_head;
} while (!atomic_compare_exchange_weak_explicit(&g_bg_spill_head[class_idx], &old_head,
(uintptr_t)rest,
memory_order_release, memory_order_relaxed));
}
}