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

#ifndef _MACHINE_TLB_H_
#define _MACHINE_TLB_H_ 1

#include <ptdef.h>
#include <hal/page.h>

/*
 * Flush a single virtual address from the translation
 * lookaside buffer.
 *
 * @VirtualBase:  Virtual address to flush
 */
ALWAYS_INLINE static inline VOID
MdTlbFlushSingle(UPTR VirtualBase)
{
    VirtualBase = ALIGN_DOWN(VirtualBase, PAGESIZE);
    ASMV(
        "invlpg %0"
        :
        : "m" (VirtualBase)
        : "memory"
    );
}

/*
 * Flush all entries from the translation lookaside buffer.
 *
 * XXX: This should be used quite judiciously due to the
 *      collateral damage caused by this operation which
 *      incurs a large performance penalty.
 */
ALWAYS_INLINE static inline VOID
MdTlbFlushAll(VOID)
{
    ASMV(
        "mov %%cr3, %%rax\n"
        "mov %%rax, %%cr3"
        :
        :
        : "memory", "rax"
    );
}

#endif  /* !_MACHINE_TLB_H_ */
