/*
 * kido-barrier.c — Kido SMP barrier.
 *
 * See kido-barrier.h for the primitive, the ordering chain,
 * the caller contract, the deadlock law, and the stated
 * divergences. This file is the real logic in two backends
 * for one operation only — the generation acquire load:
 * ARM64 LDAR inline asm (WRITTEN, NOT ASSEMBLED, NEVER
 * EXECUTED — toolchain absent, 18th data point), and a
 * hosted __atomic acquire load (real acquire semantics,
 * proving the generation logic exactly). Everything else
 * is shared portable C on top of kido-sync's public API.
 * No pthreads here: threads live in the TEST TU only.
 *
 * TESTING: gcc -std=c11 -Wall -Wextra -Werror -pthread
 *        -DKIDO_HOSTED_TEST -DKIDO_BARRIER_SELFTEST
 *        kido-barrier.c kido-sync.c -o barrier-selftest
 */
#include "kido-barrier.h"

#ifdef KIDO_BARRIER_SELFTEST
#ifndef KIDO_HOSTED_TEST
#error "KIDO_BARRIER_SELFTEST needs KIDO_HOSTED_TEST."
#endif
#include <stdio.h>
#include <pthread.h>
#endif /* KIDO_BARRIER_SELFTEST */

/* ------------------------------------------------------------------ */
/* Generation acquire load: the waiter's side of the ordering         */
/* chain (deliberation P2). ARM64 LDAR first, hosted acquire second.  */
/* ------------------------------------------------------------------ */
#if defined(__aarch64__) && !defined(KIDO_HOSTED_TEST)
static uint32_t kido_barrier_load_generation(volatile uint32_t *gen)
{
    uint32_t v = 0u;
    __asm__ volatile("ldar %w[v], [%[ptr]]"
                     : [v] "=r" (v)
                     : [ptr] "r" (gen)
                     : "memory");
    return v;
}
#else /* hosted: real acquire load, proving the logic exactly */
static uint32_t kido_barrier_load_generation(volatile uint32_t *gen)
{
    return __atomic_load_n(gen, __ATOMIC_ACQUIRE);
}
#endif /* backend */

/* A barrier is usable only after init() stamped its magic.
 * Zeroed BSS reads magic 0, which refuses — an
 * uninitialized barrier fails loud, never silently. */
static int kido_barrier_valid(const kido_barrier_t *bar)
{
    return bar != NULL && bar->magic == KIDO_BARRIER_MAGIC;
}

kido_status_t kido_barrier_init(kido_barrier_t *bar,
                                uint32_t participants)
{
    kido_status_t st;
    if (bar == NULL)
        return KIDO_ERR_EARLY_ENV;
    if (participants == 0u ||
        participants > KIDO_BARRIER_MAX_PARTICIPANTS)
        return KIDO_ERR_EARLY_ENV;
    /* A round in flight must never be silently freed under
     * arriving CPUs (deliberation C6). */
    if (bar->magic == KIDO_BARRIER_MAGIC && bar->arrived != 0u)
        return KIDO_ERR_EARLY_ENV;
    /* spin_init refuses a held lock, so a lock held by an
     * arriver mid-arrival refuses here too — a second
     * guard on the same rule. */
    st = kido_spin_init(&bar->lock);
    if (st != KIDO_OK)
        return st;
    bar->participants = participants;
    bar->arrived = 0u;
    /* Generation is monotonic, never reset (deliberation
     * C6): only a first init zeroes it. A stale waiter
     * from a previous life must never be released by a
     * reset to 0. */
    if (bar->magic != KIDO_BARRIER_MAGIC)
        bar->generation = 0u;
    bar->magic = KIDO_BARRIER_MAGIC;
    return KIDO_OK;
}

kido_status_t kido_barrier_wait(kido_barrier_t *bar)
{
    uint32_t gen;
    kido_status_t st;
    if (!kido_barrier_valid(bar))
        return KIDO_ERR_EARLY_ENV;
    st = kido_spin_lock(&bar->lock);
    if (st != KIDO_OK)
        return st;
    gen = bar->generation;
    bar->arrived++;
    if (bar->arrived == bar->participants) {
        /* Last arriver: reset BEFORE the bump, both under
         * the lock (deliberation C2). Waiters spin on
         * generation, never on arrived, so the reset can
         * never release a waiter early. The unlock's
         * release store orders the bump before any waiter
         * that observes it (ordering chain, header). */
        bar->arrived = 0u;
        bar->generation++;
        (void)kido_spin_unlock(&bar->lock);
        return KIDO_OK;
    }
    (void)kido_spin_unlock(&bar->lock);
    /* Spin WITHOUT the lock held: holding it would block
     * the last arriver from ever arriving. */
    while (kido_barrier_load_generation(&bar->generation) == gen)
        ;
    return KIDO_OK;
}

kido_status_t kido_barrier_arrived(kido_barrier_t *bar,
                                   uint32_t *count)
{
    if (!kido_barrier_valid(bar))
        return KIDO_ERR_EARLY_ENV;
    if (count == NULL)
        return KIDO_ERR_EARLY_ENV;
    /* Snapshot law: one read, no synchronization claim. */
    *count = bar->arrived;
    return KIDO_OK;
}

#ifdef KIDO_BARRIER_SELFTEST
#define BAR_CHECK(cond) do { \
    kido_barrier_checks++; \
    if (!(cond)) { \
        kido_barrier_failures++; \
        printf("[FAIL] line %d: %s\n", __LINE__, #cond); \
    } \
} while (0)

static int kido_barrier_checks = 0;
static int kido_barrier_failures = 0;

/* --- pthread rendezvous test (§3): 4 threads, 2 rounds. --- */
static int g_rv_post = 0; /* threads past round 2, test-only atomic */

typedef struct {
    kido_barrier_t *bar;
    int tid;
    int *slots;
    int *sums;
} rv_arg_t;

static void *rv_fn(void *a)
{
    rv_arg_t *arg = (rv_arg_t *)a;
    int sum = 0;
    int i;
    arg->slots[arg->tid] = arg->tid + 1; /* pre-barrier write */
    if (kido_barrier_wait(arg->bar) != KIDO_OK) {
        arg->sums[arg->tid] = -1;
        return NULL;
    }
    /* After the barrier every thread must see every
     * pre-barrier write: the sum is 1+2+3+4 = 10. A thread
     * released early would sum an incomplete set. */
    for (i = 0; i < 4; i++)
        sum += arg->slots[i];
    arg->sums[arg->tid] = sum;
    if (kido_barrier_wait(arg->bar) != KIDO_OK) {
        arg->sums[arg->tid] = -2;
        return NULL;
    }
    __atomic_add_fetch(&g_rv_post, 1, __ATOMIC_RELAXED);
    return NULL;
}

/* --- blocked-thread test (§4): one waiter, main inspects. --- */
typedef struct {
    kido_barrier_t *bar;
} w_arg_t;

static void *w_fn(void *a)
{
    (void)kido_barrier_wait(((w_arg_t *)a)->bar);
    return NULL;
}

int kido_barrier_selftest_main(void)
{
    kido_barrier_t raw; /* never init()ed */
    kido_barrier_t one;
    kido_barrier_t rb;
    kido_barrier_t tb;
    uint32_t cnt = 99u;
    int slots[4] = { 0, 0, 0, 0 };
    int sums[4] = { 0, 0, 0, 0 };
    rv_arg_t rv_args[4];
    pthread_t rv_th[4];
    int rv_created[4] = { 0, 0, 0, 0 };
    pthread_t th_a, th_b;
    w_arg_t warg;
    int i;
    int spun;

    /* §1: NULL + uninitialized + range guards — every call refuses. */
    BAR_CHECK(kido_barrier_init(NULL, 2u) == KIDO_ERR_EARLY_ENV);
    BAR_CHECK(kido_barrier_wait(NULL) == KIDO_ERR_EARLY_ENV);
    BAR_CHECK(kido_barrier_arrived(NULL, &cnt) == KIDO_ERR_EARLY_ENV);
    raw.lock.word = 0u;
    raw.lock.magic = 0u;
    raw.lock.owner = KIDO_SYNC_OWNER_FREE;
    raw.arrived = 0u;
    raw.generation = 0u;
    raw.participants = 0u;
    raw.magic = 0u; /* zeroed BSS shape: not initialized */
    BAR_CHECK(kido_barrier_init(&raw, 0u) == KIDO_ERR_EARLY_ENV);
    BAR_CHECK(kido_barrier_init(&raw, 9u) == KIDO_ERR_EARLY_ENV);
    BAR_CHECK(kido_barrier_wait(&raw) == KIDO_ERR_EARLY_ENV);
    BAR_CHECK(kido_barrier_arrived(&raw, &cnt) == KIDO_ERR_EARLY_ENV);
    BAR_CHECK(kido_barrier_arrived(&raw, NULL) == KIDO_ERR_EARLY_ENV);
    BAR_CHECK(cnt == 99u); /* refused arrived leaves out untouched */
    BAR_CHECK(raw.magic == 0u); /* refused inits left it unclaimed */

    /* §2: N=1 barrier releases immediately, generation counts
     * rounds, re-init preserves generation (deliberation C6). */
    BAR_CHECK(kido_barrier_init(&one, 1u) == KIDO_OK);
    BAR_CHECK(one.generation == 0u);
    BAR_CHECK(kido_barrier_arrived(&one, &cnt) == KIDO_OK &&
              cnt == 0u);
    BAR_CHECK(kido_barrier_wait(&one) == KIDO_OK);
    BAR_CHECK(one.generation == 1u);
    BAR_CHECK(kido_barrier_arrived(&one, &cnt) == KIDO_OK &&
              cnt == 0u);
    BAR_CHECK(kido_barrier_wait(&one) == KIDO_OK);
    BAR_CHECK(one.generation == 2u);
    BAR_CHECK(kido_barrier_init(&one, 1u) == KIDO_OK);
    BAR_CHECK(one.generation == 2u); /* preserved, not reset */
    BAR_CHECK(kido_barrier_wait(&one) == KIDO_OK);
    BAR_CHECK(one.generation == 3u);

    /* §3: 4-thread rendezvous, 2 rounds, visibility check. */
    BAR_CHECK(kido_barrier_init(&rb, 4u) == KIDO_OK);
    for (i = 0; i < 4; i++) {
        rv_args[i].bar = &rb;
        rv_args[i].tid = i;
        rv_args[i].slots = slots;
        rv_args[i].sums = sums;
        if (pthread_create(&rv_th[i], NULL, rv_fn, &rv_args[i]) == 0)
            rv_created[i] = 1;
    }
    for (i = 0; i < 4; i++)
        BAR_CHECK(rv_created[i] == 1);
    for (i = 0; i < 4; i++) {
        if (rv_created[i])
            BAR_CHECK(pthread_join(rv_th[i], NULL) == 0);
    }
    for (i = 0; i < 4; i++)
        BAR_CHECK(sums[i] == 10); /* every thread saw all writes */
    BAR_CHECK(g_rv_post == 4); /* all four passed round 2 */
    BAR_CHECK(rb.generation == 2u); /* exactly two releases */
    BAR_CHECK(kido_barrier_arrived(&rb, &cnt) == KIDO_OK &&
              cnt == 0u);

    /* §4: re-init refusal during a live round, proven with a
     * genuinely blocked thread (not a code review). */
    BAR_CHECK(kido_barrier_init(&tb, 2u) == KIDO_OK);
    warg.bar = &tb;
    BAR_CHECK(pthread_create(&th_a, NULL, w_fn, &warg) == 0);
    spun = 0;
    while (tb.arrived != 1u && spun < 100000000)
        spun++;
    BAR_CHECK(spun < 100000000); /* thread A arrived */
    BAR_CHECK(kido_barrier_arrived(&tb, &cnt) == KIDO_OK &&
              cnt == 1u);
    BAR_CHECK(tb.generation == 0u); /* not released yet */
    BAR_CHECK(kido_barrier_init(&tb, 2u) == KIDO_ERR_EARLY_ENV);
    BAR_CHECK(tb.arrived == 1u); /* refused init left the round */
    BAR_CHECK(tb.generation == 0u);
    BAR_CHECK(pthread_create(&th_b, NULL, w_fn, &warg) == 0);
    BAR_CHECK(pthread_join(th_a, NULL) == 0);
    BAR_CHECK(pthread_join(th_b, NULL) == 0);
    BAR_CHECK(tb.generation == 1u); /* B's arrival released both */
    BAR_CHECK(kido_barrier_arrived(&tb, &cnt) == KIDO_OK &&
              cnt == 0u);
    BAR_CHECK(kido_barrier_init(&tb, 2u) == KIDO_OK); /* idle: OK */
    BAR_CHECK(tb.generation == 1u); /* preserved across re-init */

    printf("[kido-barrier] %d checks, %d failures\n",
           kido_barrier_checks, kido_barrier_failures);
    return kido_barrier_failures;
}

int main(void)
{
    return kido_barrier_selftest_main() != 0;
}
#endif /* KIDO_BARRIER_SELFTEST */
