/*
 * Copyright (c) 2026, Chloe M.
 * Provided under the BSD-3 clause.
 *
 * Description:  Spinlock primitive
 * Author:       Chloe M.
 */

#include <ke/spinlock.h>
#include <hal/prim.h>

VOID KeSpinLockInit(SPINLOCK *Lock, const CHAR *Name)
{
    if (Lock == NULL) {
        return;
    }

    Lock->Data = 0;
}

VOID
KeSpinLockAcquire(SPINLOCK *Lock, BOOLEAN IrqMut)
{
    IRQL LastIrql;

    if (Lock == NULL) {
        return;
    }

    if (IrqMut) {
        LastIrql = HalRaiseIrql(IRQL_HIGH);
    }

    /* Acquire the lock */
    while (HalCpuAswap(&Lock->Data, 1)) {
        HalCpuSpinWait();
    }

    if (IrqMut) {
        HalLowerIrql(LastIrql);
    }
}

VOID
KeSpinLockRelease(SPINLOCK *Lock)
{
    if (Lock == NULL) {
        return;
    }

    HalCpuAswap(&Lock->Data, 0);
}
