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

#include <mm/vad.h>

VOID
MmVadListAppend(MM_VAD_LIST *List, MM_VAD *Vad)
{
    MM_VAD *Last;

    if (List == NULL || Vad == NULL) {
        return;
    }

    Vad->Next = NULL;
    Vad->Prev = NULL;
    KeSpinLockAcquire(&List->Lock, true);

    if (List->Last == NULL || List->First == NULL) {
        List->Last = Vad;
        List->First = Vad;
    } else {
        Last = List->Last;
        Vad->Prev = Last;
        Last->Next = Vad;
        List->Last = Vad;
    }

    KeSpinLockRelease(&List->Lock);
}

MM_VAD *
MmVadListPop(MM_VAD_LIST *List)
{
    MM_VAD *Last;

    if (List == NULL) {
        return NULL;
    }

    if (List->Last == NULL) {
        return NULL;
    }

    KeSpinLockAcquire(&List->Lock, true);
    Last = List->Last;
    if (Last->Prev != NULL) {
        Last->Prev->Next = NULL;
    }

    List->Last = Last->Prev;
    KeSpinLockRelease(&List->Lock);
    return Last;
}
