navid/haze / c0b95f8eeae4f6db6308cd4c9942340bde71175d389cc031539ebe88ded804fc / runtime/hazert.cpp

hazert.cpp

← runtime · 43077 bytes · raw · download

#include "hazert.h"

#include <atomic>
#include <cstdarg>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <new>

#if defined(_WIN32)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#else
#include <pthread.h>
#include <sched.h>
#include <sys/mman.h>
#include <unistd.h>
#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
#define MAP_ANONYMOUS MAP_ANON
#endif
#endif

namespace {

constexpr uint32_t GRANULE = 16;
constexpr uint32_t HEADER_SIZE = 8;
constexpr uint32_t LINE_SIZE = 128;
constexpr uint32_t BLOCK_SHIFT = 15;
constexpr uint32_t BLOCK_SIZE = 1u << BLOCK_SHIFT;
constexpr uint32_t LINES_PER_BLOCK = BLOCK_SIZE / LINE_SIZE;
constexpr uint32_t LARGE_THRESHOLD = 8192;
constexpr uint32_t NO_BLOCK = 0xffffffffu;
constexpr uint32_t MAX_TYPES = 1024;
constexpr uint32_t MAX_GLOBAL_ROOTS = 8192;
constexpr uint32_t MAX_PINNED = 8192;
constexpr uint32_t MAX_LARGE = 65536;
constexpr uint32_t MAX_MUTATORS = 256;
constexpr uint32_t MAX_WORKERS = 8;
constexpr uint32_t MARK_STACK = 1u << 20;
constexpr uint64_t DEFAULT_HEAP = 64ull << 30;
constexpr uint64_t MIN_HEAP = 16ull << 20;

struct alignas(8) Header {
    uint32_t type_id;
    uint8_t mark;
    uint8_t flags;
    uint16_t aux;
};
static_assert(sizeof(Header) == 8, "Header must be 8 bytes");

enum HeaderFlags : uint8_t {
    PINNED = 1u << 0,
    REMEMBERED = 1u << 1,
    LARGE = 1u << 2,
};

enum MutatorFlags : uint32_t {
    IN_NATIVE = 1u << 0,
};

enum class BlockState : uint8_t {
    FREE = 0,
    ALLOCATING,
    RECYCLABLE,
    FULL,
    EVAC_SOURCE,
    EVAC_TARGET,
    LOS_RESERVED,
};

struct BlockMeta {
    uint32_t next;
    uint16_t holes;
    uint16_t marked_lines;
    uint8_t state;
    uint8_t generation;
    uint8_t flags;
    uint8_t age;
    uint32_t owner;
};
static_assert(sizeof(BlockMeta) == 16, "BlockMeta must be 16 bytes");

struct TypeDesc {
    uint32_t size;
    uint16_t pointer_count;
    uint16_t flags;
    const uint32_t* pointer_offsets;
};

struct RootMap {
    uint32_t count;
    uint32_t frame_size;
    const uint32_t* offsets;
};

struct alignas(64) Mutator {
    void* cursor;
    void* limit;
    void* ocursor;
    void* olimit;
    void* nursery_cursor;
    void* nursery_limit;
    HazeRootFrame* root_frame;
    uint32_t thread_id;
    uint32_t flags;
    uint8_t poll;
    uint8_t reserved[7];
    uint32_t current_block;
    uint32_t overflow_block;
    uint32_t safepoint_state;
    uint32_t registered;
};

struct LargeObj {
    void* base;
    size_t size;
};

inline uint32_t align_up(uint32_t n, uint32_t a) {
    return (n + a - 1) & ~(a - 1);
}

inline uint64_t align_down64(uint64_t n, uint64_t a) {
    return n & ~(a - 1);
}

inline bool env_on(const char* name) {
    const char* v = std::getenv(name);
    return v && *v && std::strcmp(v, "0") != 0;
}

uint64_t env_u64(const char* name, uint64_t fallback) {
    const char* v = std::getenv(name);
    if (!v || !*v)
        return fallback;
    char* end = nullptr;
    unsigned long long n = std::strtoull(v, &end, 0);
    if (end == v)
        return fallback;
    if (*end == 'k' || *end == 'K')
        n <<= 10;
    else if (*end == 'm' || *end == 'M')
        n <<= 20;
    else if (*end == 'g' || *end == 'G')
        n <<= 30;
    return n;
}

#if defined(_WIN32)
void* os_reserve(size_t n) {
    return VirtualAlloc(nullptr, n, MEM_RESERVE, PAGE_NOACCESS);
}
bool os_commit(void* p, size_t n) {
    return VirtualAlloc(p, n, MEM_COMMIT, PAGE_READWRITE) != nullptr;
}
void* os_alloc_zeroed(size_t n) {
    return VirtualAlloc(nullptr, n, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
}
void os_free(void* p, size_t) {
    if (p)
        VirtualFree(p, 0, MEM_RELEASE);
}
#else
void* os_reserve(size_t n) {
    int flags = MAP_PRIVATE | MAP_ANONYMOUS;
#ifdef MAP_NORESERVE
    flags |= MAP_NORESERVE;
#endif
    void* p = mmap(nullptr, n, PROT_NONE, flags, -1, 0);
    return p == MAP_FAILED ? nullptr : p;
}
bool os_commit(void* p, size_t n) {
    return mprotect(p, n, PROT_READ | PROT_WRITE) == 0;
}
void* os_alloc_zeroed(size_t n) {
    int flags = MAP_PRIVATE | MAP_ANONYMOUS;
#ifdef MAP_NORESERVE
    flags |= MAP_NORESERVE;
#endif
    void* p = mmap(nullptr, n, PROT_READ | PROT_WRITE, flags, -1, 0);
    return p == MAP_FAILED ? nullptr : p;
}
void os_free(void* p, size_t n) {
    if (p)
        munmap(p, n);
}
#endif

struct ThreadStart {
    void (*fn)(void*);
    void* arg;
};

#if defined(_WIN32)
using OsThread = HANDLE;
DWORD WINAPI os_thread_trampoline(LPVOID p) {
    ThreadStart* start = static_cast<ThreadStart*>(p);
    start->fn(start->arg);
    return 0;
}
bool os_thread_start(OsThread& thread, ThreadStart* start) {
    thread = CreateThread(nullptr, 0, os_thread_trampoline, start, 0, nullptr);
    return thread != nullptr;
}
void os_thread_join(OsThread thread) {
    if (thread) {
        WaitForSingleObject(thread, INFINITE);
        CloseHandle(thread);
    }
}
void os_yield() {
    SwitchToThread();
}
#else
using OsThread = pthread_t;
void* os_thread_trampoline(void* p) {
    ThreadStart* start = static_cast<ThreadStart*>(p);
    start->fn(start->arg);
    return nullptr;
}
bool os_thread_start(OsThread& thread, ThreadStart* start) {
    return pthread_create(&thread, nullptr, os_thread_trampoline, start) == 0;
}
void os_thread_join(OsThread thread) {
    pthread_join(thread, nullptr);
}
void os_yield() {
    sched_yield();
}
#endif

uint32_t detect_workers() {
    uint64_t configured = env_u64("HAZE_GC_WORKERS", 0);
    if (configured)
        return static_cast<uint32_t>(configured > MAX_WORKERS ? MAX_WORKERS : configured);
#if defined(_WIN32)
    uint32_t cpus = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
#else
    long cpus = sysconf(_SC_NPROCESSORS_ONLN);
#endif
    if (cpus < 1)
        cpus = 1;
    return static_cast<uint32_t>(cpus > MAX_WORKERS ? MAX_WORKERS : cpus);
}

void spin_lock(std::atomic_flag& lock);
void spin_unlock(std::atomic_flag& lock);

struct Heap;

struct MarkWork {
    void** items = nullptr;
    uint32_t capacity = 0;
    uint32_t top = 0;
    uint32_t bottom = 0;
    std::atomic_flag lock = ATOMIC_FLAG_INIT;

    bool push(void* item) {
        spin_lock(lock);
        if (bottom >= capacity) {
            spin_unlock(lock);
            return false;
        }
        items[bottom++] = item;
        spin_unlock(lock);
        return true;
    }

    bool pop(void*& item) {
        spin_lock(lock);
        if (bottom <= top) {
            spin_unlock(lock);
            return false;
        }
        item = items[--bottom];
        spin_unlock(lock);
        return true;
    }

    bool steal(void*& item) {
        spin_lock(lock);
        if (bottom <= top) {
            spin_unlock(lock);
            return false;
        }
        item = items[top++];
        spin_unlock(lock);
        return true;
    }
};

struct MarkWorkerCtx {
    Heap* heap = nullptr;
    MarkWork* work = nullptr;
    MarkWork* all = nullptr;
    uint32_t count = 0;
    uint32_t index = 0;
    std::atomic<uint32_t>* busy = nullptr;
};

struct SweepCtx {
    Heap* heap = nullptr;
    std::atomic<uint32_t>* next = nullptr;
    std::atomic<uint64_t>* live_total = nullptr;
};

void* g_mark_items[MARK_STACK] = {};

struct Heap {
    uint8_t* base = nullptr;
    size_t size = 0;
    uint32_t nblocks = 0;
    BlockMeta* meta = nullptr;
    uint8_t* line_marks = nullptr;
    uint32_t free_head = NO_BLOCK;
    uint32_t recyclable_head = NO_BLOCK;

    TypeDesc types[MAX_TYPES] = {};
    uint32_t ntypes = 1;

    uint8_t epoch = 1;
    std::atomic<bool> initialized{false};
    bool log = false;
    bool verify_mode = false;
    bool poison = false;
    uint32_t stress_n = 0;
    uint32_t stress_counter = 0;
    uint64_t collections = 0;
    uint64_t allocations = 0;
    uint64_t live_lines_last = 0;

    Mutator main_mutator = {};
    Mutator* mutator = nullptr;

    LargeObj large[MAX_LARGE] = {};
    uint32_t nlarge = 0;

    void** global_roots[MAX_GLOBAL_ROOTS] = {};
    uint32_t nroots = 0;

    void* pinned[MAX_PINNED] = {};
    uint32_t npinned = 0;

    std::atomic<bool> gc_requested{false};
    std::atomic<uint32_t> safepoint_request{0};
    std::atomic<uint32_t> safepoint_arrived{0};
    std::atomic_flag init_lock = ATOMIC_FLAG_INIT;
    std::atomic_flag collector_lock = ATOMIC_FLAG_INIT;
    std::atomic_flag mutator_lock = ATOMIC_FLAG_INIT;
    std::atomic_flag block_lock = ATOMIC_FLAG_INIT;
    std::atomic_flag type_lock = ATOMIC_FLAG_INIT;
    std::atomic_flag root_lock = ATOMIC_FLAG_INIT;
    std::atomic_flag pinned_lock = ATOMIC_FLAG_INIT;

    uint32_t workers = 1;

    Mutator* mutators[MAX_MUTATORS] = {};
    uint32_t nmutators = 0;

    bool init();
    bool reserve_heap(size_t wanted);
    bool init_metadata();

    Mutator* current();
    Mutator* attach_current();
    void register_mutator(Mutator* m);
    void unregister_mutator(Mutator* m);
    void enter_safepoint();
    void leave_safepoint();
    void collect_locked();
    uint32_t block_index(const void* p) const {
        return static_cast<uint32_t>((static_cast<const uint8_t*>(p) - base) >> BLOCK_SHIFT);
    }
    bool in_heap(const void* p) const {
        uintptr_t a = reinterpret_cast<uintptr_t>(p);
        uintptr_t b = reinterpret_cast<uintptr_t>(base);
        return p && a >= b && a < b + size;
    }
    bool is_large_object(const void* p) const {
        for (uint32_t i = 0; i < nlarge; i++)
            if (large[i].base == p)
                return true;
        return false;
    }

    uint32_t type_for_size(uint32_t total);
    uint32_t register_type(uint32_t total, uint32_t ptr_count, const uint32_t* offsets);

    void* allocate(uint32_t payload, uint32_t type_id);
    void* allocate_ordinary(uint32_t total, uint32_t type_id);
    void* allocate_large(uint32_t total, uint32_t type_id);
    uint32_t acquire_block();
    void push_free(uint32_t b);
    void push_recyclable(uint32_t b);
    bool try_alloc(Mutator* m, uint32_t total, uint32_t type_id, void** out);
    bool find_hole(Mutator* m, uint32_t total);

    void collect();
    void parallel_mark();
    void scan_object(void* obj, MarkWorkerCtx& ctx);
    void mark_worker(MarkWorkerCtx& ctx);
    static void mark_worker_entry(void* arg);
    void parallel_sweep();
    void sweep_block(uint32_t block, std::atomic<uint64_t>& live_total);
    void sweep_worker(SweepCtx& ctx);
    static void sweep_worker_entry(void* arg);
    void reset_mutator(Mutator* m);
    void verify(bool after);

    void report(const char* fmt, ...);
};

Heap g_heap;
thread_local Mutator* tls_mutator = nullptr;

void spin_lock(std::atomic_flag& lock) {
    while (lock.test_and_set(std::memory_order_acquire))
        os_yield();
}

void spin_unlock(std::atomic_flag& lock) {
    lock.clear(std::memory_order_release);
}

bool Heap::reserve_heap(size_t wanted) {
    size_t n = wanted;
    for (;;) {
        base = static_cast<uint8_t*>(os_reserve(n));
        if (base) {
            size = n;
            nblocks = static_cast<uint32_t>(n / BLOCK_SIZE);
            return true;
        }
        if (n <= MIN_HEAP)
            return false;
        n /= 2;
    }
}

bool Heap::init_metadata() {
    size_t line_bytes = static_cast<size_t>(nblocks) * LINES_PER_BLOCK;
    line_marks = static_cast<uint8_t*>(os_alloc_zeroed(line_bytes));
    meta =
        static_cast<BlockMeta*>(os_alloc_zeroed(static_cast<size_t>(nblocks) * sizeof(BlockMeta)));
    if (!line_marks || !meta)
        return false;

    for (uint32_t i = 0; i < nblocks; i++) {
        meta[i].next = (i + 1 < nblocks) ? i + 1 : NO_BLOCK;
        meta[i].state = static_cast<uint8_t>(BlockState::FREE);
        meta[i].owner = 0xffffffffu;
    }
    free_head = nblocks ? 0 : NO_BLOCK;
    recyclable_head = NO_BLOCK;

    types[0].size = 0;
    types[0].pointer_count = 0;
    types[0].flags = 0;
    types[0].pointer_offsets = nullptr;
    ntypes = 1;
    return true;
}

bool Heap::init() {
    if (initialized)
        return true;

    spin_lock(init_lock);
    if (initialized) {
        spin_unlock(init_lock);
        return true;
    }

    log = env_on("HAZE_GC_LOG");
    verify_mode = env_on("HAZE_GC_VERIFY");
    poison = env_on("HAZE_GC_POISON");
    stress_n = static_cast<uint32_t>(env_u64("HAZE_GC_STRESS", 0));
    workers = detect_workers();
    if (workers < 1)
        workers = 1;

    uint64_t wanted = env_u64("HAZE_HEAP_SIZE", DEFAULT_HEAP);
    if (wanted < MIN_HEAP)
        wanted = MIN_HEAP;
    wanted = align_down64(wanted, BLOCK_SIZE);

    for (;;) {
        if (!reserve_heap(static_cast<size_t>(wanted))) {
            report("could not reserve a %llu-byte heap", static_cast<unsigned long long>(wanted));
            spin_unlock(init_lock);
            return false;
        }
        if (init_metadata())
            break;
        os_free(line_marks, static_cast<size_t>(nblocks) * LINES_PER_BLOCK);
        os_free(meta, static_cast<size_t>(nblocks) * sizeof(BlockMeta));
        line_marks = nullptr;
        meta = nullptr;
        os_free(base, size);
        base = nullptr;
        if (wanted <= MIN_HEAP) {
            report("could not allocate collector side metadata");
            spin_unlock(init_lock);
            return false;
        }
        wanted /= 2;
        wanted = align_down64(wanted, BLOCK_SIZE);
    }

    std::memset(&main_mutator, 0, sizeof(main_mutator));
    main_mutator.current_block = NO_BLOCK;
    main_mutator.overflow_block = NO_BLOCK;
    mutator = &main_mutator;
    tls_mutator = &main_mutator;
    register_mutator(&main_mutator);
    initialized = true;
    spin_unlock(init_lock);

    if (log)
        report("heap: %llu bytes, %u blocks, %u lines/block", static_cast<unsigned long long>(size),
               nblocks, LINES_PER_BLOCK);
    return true;
}

void Heap::register_mutator(Mutator* m) {
    spin_lock(mutator_lock);
    if (nmutators < MAX_MUTATORS) {
        mutators[nmutators++] = m;
        m->registered = 1;
    }
    spin_unlock(mutator_lock);
}

void Heap::unregister_mutator(Mutator* m) {
    spin_lock(mutator_lock);
    for (uint32_t i = 0; i < nmutators; i++) {
        if (mutators[i] == m) {
            mutators[i] = mutators[--nmutators];
            m->registered = 0;
            break;
        }
    }
    spin_unlock(mutator_lock);
}

void Heap::enter_safepoint() {
    Mutator* m = current();
    if (!m || m->safepoint_state)
        return;
    m->safepoint_state = 1;
    safepoint_arrived.fetch_add(1, std::memory_order_acq_rel);
}

void Heap::leave_safepoint() {
    Mutator* m = tls_mutator;
    if (!m || !m->safepoint_state)
        return;
    while (safepoint_request.load(std::memory_order_acquire))
        os_yield();
    m->safepoint_state = 0;
    safepoint_arrived.fetch_sub(1, std::memory_order_acq_rel);
}

Mutator* Heap::attach_current() {
    if (tls_mutator)
        return tls_mutator;

    Mutator* m = static_cast<Mutator*>(os_alloc_zeroed(sizeof(Mutator)));
    if (!m) {
        haze_panic("could not allocate mutator");
        return &main_mutator;
    }
    m->current_block = NO_BLOCK;
    m->overflow_block = NO_BLOCK;
    tls_mutator = m;
    register_mutator(m);

    if (safepoint_request.load(std::memory_order_acquire)) {
        enter_safepoint();
        leave_safepoint();
    }
    return m;
}

Mutator* Heap::current() {
    if (!initialized)
        init();
    if (!tls_mutator)
        return attach_current();
    return tls_mutator;
}

uint32_t Heap::type_for_size(uint32_t total) {
    total = align_up(total, GRANULE);
    spin_lock(type_lock);
    for (uint32_t i = 1; i < ntypes; i++) {
        if (types[i].size == total && types[i].pointer_count == 0) {
            spin_unlock(type_lock);
            return i;
        }
    }
    if (ntypes >= MAX_TYPES) {
        spin_unlock(type_lock);
        report("type table exhausted");
        std::abort();
    }
    uint32_t id = ntypes++;
    types[id].size = total;
    types[id].pointer_count = 0;
    types[id].flags = 0;
    types[id].pointer_offsets = nullptr;
    spin_unlock(type_lock);
    return id;
}

uint32_t Heap::register_type(uint32_t total, uint32_t ptr_count, const uint32_t* offsets) {
    total = align_up(total, GRANULE);
    spin_lock(type_lock);
    for (uint32_t i = 1; i < ntypes; i++) {
        if (types[i].size == total && types[i].pointer_count == ptr_count &&
            types[i].pointer_offsets == offsets) {
            spin_unlock(type_lock);
            return i;
        }
    }
    if (ntypes >= MAX_TYPES) {
        spin_unlock(type_lock);
        report("type table exhausted");
        std::abort();
    }
    uint32_t id = ntypes++;
    types[id].size = total;
    types[id].pointer_count = static_cast<uint16_t>(ptr_count);
    types[id].flags = 0;
    types[id].pointer_offsets = offsets;
    spin_unlock(type_lock);
    return id;
}

void Heap::push_free(uint32_t b) {
    spin_lock(block_lock);
    meta[b].next = free_head;
    meta[b].state = static_cast<uint8_t>(BlockState::FREE);
    meta[b].holes = LINES_PER_BLOCK;
    meta[b].marked_lines = 0;
    free_head = b;
    spin_unlock(block_lock);
}

void Heap::push_recyclable(uint32_t b) {
    spin_lock(block_lock);
    meta[b].next = recyclable_head;
    meta[b].state = static_cast<uint8_t>(BlockState::RECYCLABLE);
    recyclable_head = b;
    spin_unlock(block_lock);
}

uint32_t Heap::acquire_block() {
    Mutator* m = current();
    for (;;) {
        uint32_t b = NO_BLOCK;
        bool from_free = false;
        spin_lock(block_lock);
        if (recyclable_head != NO_BLOCK) {
            b = recyclable_head;
            recyclable_head = meta[b].next;
            meta[b].next = NO_BLOCK;
        } else if (free_head != NO_BLOCK) {
            b = free_head;
            free_head = meta[b].next;
            meta[b].next = NO_BLOCK;
            from_free = true;
        }
        if (b == NO_BLOCK) {
            spin_unlock(block_lock);
            return NO_BLOCK;
        }
        meta[b].state = static_cast<uint8_t>(BlockState::ALLOCATING);
        meta[b].owner = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(m) & 0xffffffffu);
        meta[b].age = 0;
        spin_unlock(block_lock);

        if (from_free) {
            uint8_t* block = base + static_cast<size_t>(b) * BLOCK_SIZE;
            if (!os_commit(block, BLOCK_SIZE)) {
                report("could not commit block %u", b);
                std::abort();
            }
            std::memset(block, 0, BLOCK_SIZE);
            std::memset(line_marks + static_cast<size_t>(b) * LINES_PER_BLOCK, 0, LINES_PER_BLOCK);
            meta[b].holes = LINES_PER_BLOCK;
            meta[b].marked_lines = 0;
        }

        uint8_t* block = base + static_cast<size_t>(b) * BLOCK_SIZE;
        m->current_block = b;
        m->cursor = block;
        m->limit = block + BLOCK_SIZE;

        if (meta[b].marked_lines == 0) {
            std::memset(line_marks + static_cast<size_t>(b) * LINES_PER_BLOCK, 0, LINES_PER_BLOCK);
            return b;
        }

        return b;
    }
}

bool Heap::find_hole(Mutator* m, uint32_t total) {
    uint32_t b = m->current_block;
    if (b == NO_BLOCK)
        return false;
    uint8_t* block = base + static_cast<size_t>(b) * BLOCK_SIZE;
    size_t off = static_cast<uint8_t*>(m->cursor) - block;
    if (off >= BLOCK_SIZE)
        return false;
    uint32_t line = static_cast<uint32_t>(off) / LINE_SIZE;
    uint32_t base_line = b * LINES_PER_BLOCK;

    while (line < LINES_PER_BLOCK) {
        if (line_marks[base_line + line] == epoch) {
            line++;
            continue;
        }
        uint32_t end = line;
        while (end < LINES_PER_BLOCK && line_marks[base_line + end] != epoch)
            end++;
        uint32_t bytes = (end - line) * LINE_SIZE;
        if (bytes >= total) {
            m->cursor = block + static_cast<size_t>(line) * LINE_SIZE;
            m->limit = block + static_cast<size_t>(end) * LINE_SIZE;
            return true;
        }
        line = end;
    }
    return false;
}

bool Heap::try_alloc(Mutator* m, uint32_t total, uint32_t type_id, void** out) {
    uint8_t* p = static_cast<uint8_t*>(m->cursor);
    if (!p || p + total > static_cast<uint8_t*>(m->limit))
        return false;

    uint32_t b = m->current_block;
    if (b == NO_BLOCK)
        return false;

    uint8_t* block = base + static_cast<size_t>(b) * BLOCK_SIZE;
    uint32_t first_line = static_cast<uint32_t>(p - block) / LINE_SIZE;
    uint32_t last_line = static_cast<uint32_t>((p + total - 1) - block) / LINE_SIZE;
    uint32_t base_line = b * LINES_PER_BLOCK;

    m->cursor = p + total;

    Header* h = reinterpret_cast<Header*>(p);
    h->type_id = type_id;
    h->mark = 0;
    h->flags = 0;
    h->aux = 0;
    std::memset(p + HEADER_SIZE, 0, total - HEADER_SIZE);

    for (uint32_t line = first_line; line <= last_line; line++)
        line_marks[base_line + line] = epoch;

    meta[b].state = static_cast<uint8_t>(BlockState::ALLOCATING);
    allocations++;
    *out = p;
    return true;
}

void* Heap::allocate_large(uint32_t total, uint32_t type_id) {
    if (nlarge >= MAX_LARGE) {
        report("large object table exhausted");
        std::abort();
    }
    void* p = os_alloc_zeroed(total);
    if (!p)
        return nullptr;
    Header* h = static_cast<Header*>(p);
    h->type_id = type_id;
    h->mark = 0;
    h->flags = LARGE;
    h->aux = 0;
    large[nlarge].base = p;
    large[nlarge].size = total;
    nlarge++;
    allocations++;
    return p;
}

void* Heap::allocate_ordinary(uint32_t total, uint32_t type_id) {
    Mutator* m = current();

    for (uint32_t attempt = 0; attempt < 2; attempt++) {
        for (;;) {
            if (m->current_block != NO_BLOCK) {
                void* p = nullptr;
                if (try_alloc(m, total, type_id, &p))
                    return p;
                if (find_hole(m, total) && try_alloc(m, total, type_id, &p))
                    return p;
                meta[m->current_block].state = static_cast<uint8_t>(BlockState::FULL);
                m->current_block = NO_BLOCK;
                m->cursor = m->limit = nullptr;
            }

            uint32_t b = acquire_block();
            if (b == NO_BLOCK)
                break;
            m->current_block = b;
            uint8_t* block = base + static_cast<size_t>(b) * BLOCK_SIZE;
            m->cursor = block;
            m->limit = block + BLOCK_SIZE;

            if (meta[b].marked_lines != 0) {
                void* p = nullptr;
                if (find_hole(m, total) && try_alloc(m, total, type_id, &p))
                    return p;
                meta[b].state = static_cast<uint8_t>(BlockState::FULL);
                m->current_block = NO_BLOCK;
                m->cursor = m->limit = nullptr;
                continue;
            }

            void* p = nullptr;
            if (try_alloc(m, total, type_id, &p))
                return p;
            meta[b].state = static_cast<uint8_t>(BlockState::FULL);
            m->current_block = NO_BLOCK;
            m->cursor = m->limit = nullptr;
        }
        collect();
    }
    return nullptr;
}

void* Heap::allocate(uint32_t payload, uint32_t type_id) {
    init();

    if (stress_n) {
        if (++stress_counter >= stress_n) {
            stress_counter = 0;
            collect();
        }
    }

    uint32_t total;
    if (type_id == 0) {
        total = align_up(HEADER_SIZE + payload, GRANULE);
        type_id = type_for_size(total);
    } else {
        total = types[type_id].size;
        if (total < align_up(HEADER_SIZE + payload, GRANULE))
            total = align_up(HEADER_SIZE + payload, GRANULE);
    }

    if (total > LARGE_THRESHOLD) {
        void* p = allocate_large(total, type_id);
        if (!p) {
            collect();
            p = allocate_large(total, type_id);
        }
        return p;
    }

    void* p = allocate_ordinary(total, type_id);
    if (!p) {
        collect();
        p = allocate_ordinary(total, type_id);
    }
    if (!p) {
        report("out of heap after collection");
        std::abort();
    }
    return p;
}

void Heap::scan_object(void* obj, MarkWorkerCtx& ctx) {
    if (!obj)
        return;
    bool large_object = is_large_object(obj);
    if (!in_heap(obj) && !large_object)
        return;
    if (reinterpret_cast<uintptr_t>(obj) & (GRANULE - 1))
        return;

    Header* h = reinterpret_cast<Header*>(obj);
    uint8_t previous = h->mark;
    if (previous == epoch)
        return;
    std::atomic_ref<uint8_t> mark(h->mark);
    uint8_t expected = previous;
    if (!mark.compare_exchange_strong(expected, epoch, std::memory_order_acq_rel,
                                      std::memory_order_acquire))
        return;

    uint8_t header_flags =
        std::atomic_ref<uint8_t>(h->flags).load(std::memory_order_acquire);
    if (!(header_flags & LARGE) && !large_object) {
        uint32_t b = block_index(obj);
        uint8_t* block = base + static_cast<size_t>(b) * BLOCK_SIZE;
        uint32_t first = static_cast<uint32_t>(static_cast<uint8_t*>(obj) - block) / LINE_SIZE;
        uint32_t total = types[h->type_id].size;
        if (total == 0)
            return;
        uint32_t last =
            static_cast<uint32_t>((static_cast<uint8_t*>(obj) + total - 1) - block) / LINE_SIZE;
        uint32_t base_line = b * LINES_PER_BLOCK;
        for (uint32_t line = first; line <= last; line++)
            std::atomic_ref<uint8_t>(line_marks[base_line + line])
                .store(epoch, std::memory_order_relaxed);
    }

    const TypeDesc& td = types[h->type_id];
    if (td.pointer_count && td.pointer_offsets) {
        for (uint32_t i = 0; i < td.pointer_count; i++) {
            uint32_t off = td.pointer_offsets[i];
            void* child = nullptr;
            std::memcpy(&child, static_cast<uint8_t*>(obj) + off, sizeof(child));
            if (child && !ctx.work->push(child)) {
                report("mark work queue exhausted");
                std::abort();
            }
        }
    }
}

void Heap::mark_worker(MarkWorkerCtx& ctx) {
    for (;;) {
        void* obj = nullptr;
        bool got = ctx.work->pop(obj);
        if (!got) {
            for (uint32_t i = 1; i < ctx.count; i++) {
                MarkWork& victim = ctx.all[(ctx.index + i) % ctx.count];
                if (victim.steal(obj)) {
                    got = true;
                    break;
                }
            }
        }
        if (got) {
            ctx.busy->fetch_add(1, std::memory_order_acq_rel);
            scan_object(obj, ctx);
            ctx.busy->fetch_sub(1, std::memory_order_acq_rel);
            continue;
        }
        if (ctx.busy->load(std::memory_order_acquire) == 0)
            break;
        os_yield();
    }
}

void Heap::mark_worker_entry(void* arg) {
    MarkWorkerCtx* ctx = static_cast<MarkWorkerCtx*>(arg);
    ctx->heap->mark_worker(*ctx);
}

void Heap::parallel_mark() {
    uint32_t count = workers;
    if (count < 1)
        count = 1;
    if (count > MAX_WORKERS)
        count = MAX_WORKERS;

    MarkWork works[MAX_WORKERS];
    MarkWorkerCtx contexts[MAX_WORKERS];
    std::atomic<uint32_t> busy{0};
    const uint32_t chunk = MARK_STACK / MAX_WORKERS;
    for (uint32_t i = 0; i < count; i++) {
        works[i].items = g_mark_items + i * chunk;
        works[i].capacity = chunk;
        works[i].top = 0;
        works[i].bottom = 0;
        contexts[i].heap = this;
        contexts[i].work = &works[i];
        contexts[i].all = works;
        contexts[i].count = count;
        contexts[i].index = i;
        contexts[i].busy = &busy;
    }

    uint32_t seed_index = 0;
    auto seed = [&](void* obj) {
        if (!obj)
            return;
        scan_object(obj, contexts[seed_index]);
        seed_index = (seed_index + 1) % count;
    };

    spin_lock(mutator_lock);
    for (uint32_t mi = 0; mi < nmutators; mi++) {
        Mutator* m = mutators[mi];
        for (HazeRootFrame* f = m->root_frame; f; f = f->previous) {
            if (!f->descriptor || !f->slots)
                continue;
            const RootMap* map = reinterpret_cast<const RootMap*>(f->descriptor);
            for (uint32_t i = 0; i < map->count; i++)
                seed(f->slots[i]);
        }
    }
    spin_unlock(mutator_lock);

    spin_lock(root_lock);
    for (uint32_t i = 0; i < nroots; i++)
        if (global_roots[i])
            seed(*global_roots[i]);
    spin_unlock(root_lock);

    spin_lock(pinned_lock);
    for (uint32_t i = 0; i < npinned; i++)
        seed(pinned[i]);
    spin_unlock(pinned_lock);

    if (count == 1) {
        mark_worker(contexts[0]);
        return;
    }

    ThreadStart starts[MAX_WORKERS];
    OsThread threads[MAX_WORKERS];
    bool started[MAX_WORKERS] = {};
    for (uint32_t i = 1; i < count; i++) {
        starts[i].fn = &Heap::mark_worker_entry;
        starts[i].arg = &contexts[i];
        started[i] = os_thread_start(threads[i], &starts[i]);
    }

    mark_worker(contexts[0]);

    for (uint32_t i = 1; i < count; i++)
        if (started[i])
            os_thread_join(threads[i]);
}

static uint32_t count_live_lines(const uint8_t* marks, uint8_t epoch) {
    uint32_t live = 0;
    uint32_t i = 0;
    const uint64_t target = 0x0101010101010101ull * epoch;
    const uint64_t high_bits = 0x8080808080808080ull;
    for (; i + 8 <= LINES_PER_BLOCK; i += 8) {
        uint64_t word = 0;
        std::memcpy(&word, marks + i, sizeof(word));
        uint64_t equal = ~(word ^ target) & high_bits;
#if defined(__GNUC__) || defined(__clang__)
        live += static_cast<uint32_t>(__builtin_popcountll(equal));
#else
        while (equal) {
            live += static_cast<uint32_t>(equal & 1);
            equal >>= 1;
        }
#endif
    }
    for (; i < LINES_PER_BLOCK; i++)
        if (marks[i] == epoch)
            live++;
    return live;
}

void Heap::sweep_block(uint32_t b, std::atomic<uint64_t>& live_total) {
    uint8_t state = meta[b].state;
    if (state == static_cast<uint8_t>(BlockState::FREE) ||
        state == static_cast<uint8_t>(BlockState::LOS_RESERVED))
        return;

    uint32_t base_line = b * LINES_PER_BLOCK;
    uint32_t live = count_live_lines(line_marks + base_line, epoch);
    live_total.fetch_add(live, std::memory_order_relaxed);

    if (live == 0) {
        if (poison) {
            uint8_t* block = base + static_cast<size_t>(b) * BLOCK_SIZE;
            std::memset(block, 0xDD, BLOCK_SIZE);
        }
        push_free(b);
    } else if (live == LINES_PER_BLOCK) {
        meta[b].state = static_cast<uint8_t>(BlockState::FULL);
        meta[b].marked_lines = LINES_PER_BLOCK;
        meta[b].holes = 0;
    } else {
        uint32_t holes = 0;
        bool in_hole = false;
        for (uint32_t i = 0; i < LINES_PER_BLOCK; i++) {
            bool dead = line_marks[base_line + i] != epoch;
            if (dead && !in_hole) {
                holes++;
                in_hole = true;
            } else if (!dead) {
                in_hole = false;
            }
        }
        meta[b].marked_lines = static_cast<uint16_t>(live);
        meta[b].holes = static_cast<uint16_t>(holes);
        push_recyclable(b);
    }
}

void Heap::sweep_worker(SweepCtx& ctx) {
    for (;;) {
        uint32_t b = ctx.next->fetch_add(1, std::memory_order_relaxed);
        if (b >= nblocks)
            break;
        sweep_block(b, *ctx.live_total);
    }
}

void Heap::sweep_worker_entry(void* arg) {
    SweepCtx* ctx = static_cast<SweepCtx*>(arg);
    ctx->heap->sweep_worker(*ctx);
}

void Heap::parallel_sweep() {
    uint32_t count = workers;
    if (count < 1)
        count = 1;
    if (count > MAX_WORKERS)
        count = MAX_WORKERS;

    std::atomic<uint32_t> next{0};
    std::atomic<uint64_t> live_total{0};
    SweepCtx contexts[MAX_WORKERS];
    for (uint32_t i = 0; i < count; i++) {
        contexts[i].heap = this;
        contexts[i].next = &next;
        contexts[i].live_total = &live_total;
    }

    ThreadStart starts[MAX_WORKERS];
    OsThread threads[MAX_WORKERS];
    bool started[MAX_WORKERS] = {};
    for (uint32_t i = 1; i < count; i++) {
        starts[i].fn = &Heap::sweep_worker_entry;
        starts[i].arg = &contexts[i];
        started[i] = os_thread_start(threads[i], &starts[i]);
    }

    sweep_worker(contexts[0]);

    for (uint32_t i = 1; i < count; i++)
        if (started[i])
            os_thread_join(threads[i]);

    for (uint32_t i = 0; i < nlarge;) {
        Header* h = static_cast<Header*>(large[i].base);
        if (h->mark != epoch) {
            os_free(large[i].base, large[i].size);
            large[i] = large[--nlarge];
        } else {
            i++;
        }
    }

    live_lines_last = live_total.load(std::memory_order_relaxed);
}

void Heap::reset_mutator(Mutator* m) {
    m->cursor = nullptr;
    m->limit = nullptr;
    m->ocursor = nullptr;
    m->olimit = nullptr;
    m->current_block = NO_BLOCK;
    m->overflow_block = NO_BLOCK;
}

void Heap::collect_locked() {
    if (verify_mode)
        verify(false);

    collections++;

    if (epoch == 255) {
        std::memset(line_marks, 0, static_cast<size_t>(nblocks) * LINES_PER_BLOCK);
        epoch = 1;
    } else {
        epoch++;
    }

    for (uint32_t i = 0; i < nlarge; i++) {
        Header* h = static_cast<Header*>(large[i].base);
        h->mark = 0;
    }

    spin_lock(mutator_lock);
    for (uint32_t i = 0; i < nmutators; i++)
        reset_mutator(mutators[i]);
    spin_unlock(mutator_lock);

    spin_lock(block_lock);
    recyclable_head = NO_BLOCK;
    spin_unlock(block_lock);

    parallel_mark();
    parallel_sweep();

    gc_requested.store(false, std::memory_order_release);

    if (verify_mode)
        verify(true);

    if (log)
        report("gc #%llu epoch=%u live_lines=%llu large=%u free_head=%u",
               static_cast<unsigned long long>(collections), epoch,
               static_cast<unsigned long long>(live_lines_last), nlarge, free_head);
}

void Heap::collect() {
    if (!init())
        return;

    Mutator* self = current();
    while (collector_lock.test_and_set(std::memory_order_acquire)) {
        if (safepoint_request.load(std::memory_order_acquire)) {
            enter_safepoint();
            leave_safepoint();
        }
        os_yield();
    }

    safepoint_request.store(1, std::memory_order_release);
    enter_safepoint();

    for (;;) {
        spin_lock(mutator_lock);
        uint32_t need = 0;
        for (uint32_t i = 0; i < nmutators; i++)
            if (!(std::atomic_ref<uint32_t>(mutators[i]->flags)
                      .load(std::memory_order_acquire) &
                  IN_NATIVE))
                need++;
        spin_unlock(mutator_lock);
        if (safepoint_arrived.load(std::memory_order_acquire) >= need)
            break;
        os_yield();
    }

    collect_locked();

    safepoint_request.store(0, std::memory_order_release);
    if (self && self->safepoint_state)
        leave_safepoint();
    collector_lock.clear(std::memory_order_release);
}

void Heap::verify(bool after) {
    if (!initialized)
        return;

    auto fail = [](const char* what) {
        std::fprintf(stderr, "hazert: heap verification failed: %s\n", what);
        std::abort();
    };

    spin_lock(mutator_lock);
    for (uint32_t mi = 0; mi < nmutators; mi++) {
        Mutator* m = mutators[mi];
        for (HazeRootFrame* f = m->root_frame; f; f = f->previous) {
            if (!f->descriptor || !f->slots)
                fail("root frame has no descriptor or slots");
            const RootMap* map = reinterpret_cast<const RootMap*>(f->descriptor);
            for (uint32_t i = 0; i < map->count; i++) {
                void* p = f->slots[i];
                if (!p)
                    continue;
                if (!in_heap(p) && !is_large_object(p))
                    fail("root slot points outside the heap");
                if (reinterpret_cast<uintptr_t>(p) & (GRANULE - 1))
                    fail("root slot is not granule aligned");
                Header* h = static_cast<Header*>(p);
                if (h->type_id == 0)
                    fail("root slot has no type descriptor");
                if (after && h->mark != epoch)
                    fail("live root was not marked");
            }
        }
    }
    spin_unlock(mutator_lock);

    spin_lock(root_lock);
    for (uint32_t i = 0; i < nroots; i++) {
        if (!global_roots[i] || !*global_roots[i])
            continue;
        void* p = *global_roots[i];
        if (!in_heap(p) && !is_large_object(p))
            fail("global root points outside the heap");
    }
    spin_unlock(root_lock);

    for (uint32_t i = 0; i < nlarge; i++)
        if (reinterpret_cast<uintptr_t>(large[i].base) & (GRANULE - 1))
            fail("large object is not granule aligned");

    for (uint32_t b = 0; b < nblocks; b++) {
        uint8_t state = meta[b].state;
        if (state > static_cast<uint8_t>(BlockState::LOS_RESERVED))
            fail("invalid block state");
        if (state != static_cast<uint8_t>(BlockState::FREE) &&
            state != static_cast<uint8_t>(BlockState::LOS_RESERVED) && after &&
            meta[b].marked_lines == 0 && meta[b].holes == LINES_PER_BLOCK)
            fail("allocated block has no marked lines");
    }
}

void Heap::report(const char* fmt, ...) {
    va_list ap;
    va_start(ap, fmt);
    std::vfprintf(stderr, fmt, ap);
    va_end(ap);
    std::fputc('\n', stderr);
}

} // namespace

extern "C" {

void haze_runtime_init(void) {
    g_heap.init();
}

void* haze_alloc_slow(uint32_t payload_size, uint32_t type_id) {
    return g_heap.allocate(payload_size, type_id);
}

void* haze_alloc_large(uint32_t payload_size, uint32_t type_id) {
    g_heap.init();
    uint32_t total = align_up(HEADER_SIZE + payload_size, GRANULE);
    if (type_id == 0)
        type_id = g_heap.type_for_size(total);
    return g_heap.allocate_large(total, type_id);
}

uint32_t haze_type_for_size(uint32_t total_size) {
    g_heap.init();
    return g_heap.type_for_size(total_size);
}

uint32_t haze_register_type(uint32_t total_size, uint32_t pointer_count,
                           const uint32_t* pointer_offsets) {
    g_heap.init();
    return g_heap.register_type(total_size, pointer_count, pointer_offsets);
}

void haze_gc_request(void) {
    g_heap.gc_requested.store(true, std::memory_order_release);
}

void haze_gc_poll(void) {
    if (!g_heap.initialized)
        g_heap.init();
    if (g_heap.safepoint_request.load(std::memory_order_acquire)) {
        g_heap.enter_safepoint();
        g_heap.leave_safepoint();
    }
    if (g_heap.gc_requested.load(std::memory_order_acquire))
        g_heap.collect();
}

void haze_gc_collect(void) {
    g_heap.collect();
}

void haze_gc_verify(void) {
    g_heap.verify(true);
}

int haze_gc_object_alive(void* object) {
    if (!g_heap.initialized || !object)
        return 0;
    if (!g_heap.in_heap(object) && !g_heap.is_large_object(object))
        return 0;
    Header* h = static_cast<Header*>(object);
    return h->mark == g_heap.epoch;
}

void haze_thread_attach(void) {
    g_heap.init();
    if (!tls_mutator)
        g_heap.attach_current();
}

void haze_thread_detach(void) {
    Mutator* m = tls_mutator;
    if (!m)
        return;
    if (g_heap.safepoint_request.load(std::memory_order_acquire)) {
        g_heap.enter_safepoint();
        g_heap.leave_safepoint();
    }
    g_heap.unregister_mutator(m);
    tls_mutator = nullptr;
    if (m != &g_heap.main_mutator)
        os_free(m, sizeof(Mutator));
}

void haze_root_enter(HazeRootFrame* frame) {
    if (!frame)
        return;
    Mutator* m = g_heap.current();
    frame->previous = m->root_frame;
    m->root_frame = frame;
}

void haze_root_leave(HazeRootFrame* frame) {
    if (!frame)
        return;
    Mutator* m = g_heap.current();
    if (m->root_frame == frame) {
        m->root_frame = frame->previous;
        return;
    }
    for (HazeRootFrame* f = m->root_frame; f; f = f->previous) {
        if (f->previous == frame) {
            f->previous = frame->previous;
            return;
        }
    }
}

void haze_root_add(void** slot) {
    g_heap.init();
    spin_lock(g_heap.root_lock);
    if (g_heap.nroots < MAX_GLOBAL_ROOTS)
        g_heap.global_roots[g_heap.nroots++] = slot;
    spin_unlock(g_heap.root_lock);
}

void haze_root_remove(void** slot) {
    spin_lock(g_heap.root_lock);
    for (uint32_t i = 0; i < g_heap.nroots; i++) {
        if (g_heap.global_roots[i] == slot) {
            g_heap.global_roots[i] = g_heap.global_roots[--g_heap.nroots];
            break;
        }
    }
    spin_unlock(g_heap.root_lock);
}

void haze_native_enter(void) {
    Mutator* m = g_heap.current();
    if (!m)
        return;
    std::atomic_ref<uint32_t>(m->flags).fetch_or(IN_NATIVE, std::memory_order_acq_rel);
}

void haze_native_exit(void) {
    Mutator* m = g_heap.current();
    if (!m)
        return;
    std::atomic_ref<uint32_t>(m->flags).fetch_and(~IN_NATIVE, std::memory_order_acq_rel);
    if (g_heap.safepoint_request.load(std::memory_order_acquire)) {
        g_heap.enter_safepoint();
        g_heap.leave_safepoint();
    }
}

void haze_pin(void* object) {
    if (!object || (!g_heap.in_heap(object) && !g_heap.is_large_object(object)))
        return;
    Header* h = static_cast<Header*>(object);
    spin_lock(g_heap.pinned_lock);
    uint8_t flags = std::atomic_ref<uint8_t>(h->flags).load(std::memory_order_acquire);
    if (!(flags & PINNED)) {
        std::atomic_ref<uint8_t>(h->flags).fetch_or(PINNED, std::memory_order_acq_rel);
        if (g_heap.npinned < MAX_PINNED)
            g_heap.pinned[g_heap.npinned++] = object;
    }
    spin_unlock(g_heap.pinned_lock);
}

void haze_unpin(void* object) {
    if (!object)
        return;
    Header* h = static_cast<Header*>(object);
    spin_lock(g_heap.pinned_lock);
    std::atomic_ref<uint8_t>(h->flags).fetch_and(~PINNED, std::memory_order_acq_rel);
    for (uint32_t i = 0; i < g_heap.npinned; i++) {
        if (g_heap.pinned[i] == object) {
            g_heap.pinned[i] = g_heap.pinned[--g_heap.npinned];
            break;
        }
    }
    spin_unlock(g_heap.pinned_lock);
}

void haze_wb(void* object, void** slot, void* value) {
    if (!object || !slot)
        return;
    *slot = value;
    Header* h = static_cast<Header*>(object);
    std::atomic_ref<uint8_t>(h->flags).fetch_or(REMEMBERED, std::memory_order_acq_rel);
}

void haze_print_i32(int32_t value) {
    std::printf("%d\n", value);
}

void haze_print_i64(int64_t value) {
    std::printf("%lld\n", static_cast<long long>(value));
}

void haze_print_bool(int32_t value) {
    std::fputs(value ? "true\n" : "false\n", stdout);
}

void haze_print_str(const char* value) {
    std::fputs(value ? value : "", stdout);
    std::fputc('\n', stdout);
}

void haze_panic(const char* message) {
    std::fprintf(stderr, "haze: %s\n", message ? message : "panic");
    std::fflush(stderr);
    std::exit(1);
}

} // extern "C"