/**
 * @file UsbOcUpdateDxeLightningRidgeEXRP.c
 *
 * @brief UsbOcUpdateDxeLightningRidgeEXRP - UEFI DXE driver for USB over-current
 *        (OC) protection configuration on the LightningRidgeEXRP platform.
 *
 * MODULE TYPE: DXE Driver (Index 0003 in BIOS FFS)
 * UEFI PHASE:  DXE
 *
 * FLOW SUMMARY:
 *   1. _ModuleEntryPoint() (0x390) initializes UEFI globals, locates the HOB
 *      list via GetHobList(), prints a debug banner, locates the UBA
 *      board-type protocol, and registers the USB OC configuration.
 *   2. GetHobList() (0x5F8) scans SystemTable->ConfigurationTable[] for
 *      EFI_HOB_LIST_GUID using IsHobListGuid().
 *   3. DebugPrint() (0x530) checks CMOS debug level and calls the DebugLib
 *      protocol output function.
 *   4. DebugAssert() (0x5B8) calls the DebugLib protocol's assertion handler
 *      (or the UBA protocol's assert handler at offset 0x08).
 *   5. ReadUnaligned64() (0x740) reads a 64-bit value from potentially
 *      unaligned memory with a NULL check.
 *
 * GUIDs:
 *   - EFI_HOB_LIST_GUID: {7739F24C-93D7-11D4-9A3A-0090273FC14D}
 *   - UBA Board-Type Protocol (shared): {E03E0D46-5263-4845-B0A4-58D57B3177E2}
 *   - UBA LightningRidgeEXRP USB OC Config: {2638009E-3850-4E4B-B05D-042A32DBB9D1}
 *
 * HARDWARE:
 *   - CMOS RTC ports 0x70/0x71: Debug level register at index 0x4B
 *   - MMIO 0xFDAF0490: Board configuration register (fallback for debug level)
 */

#include "UsbOcUpdateDxeLightningRidgeEXRP.h"

// ============================================================================
// Static (Module-Level) Global Variables
// ===========================================================================/

///
/// Cached pointer to the DebugLib protocol interface.
/// Initialized lazily by GetDebugProtocol(). Located via gBS->LocateProtocol()
/// against the DebugLib protocol GUID. Stored at address 0xC70.
///
STATIC VOID  *mDebugProtocol;     // qword_C70 at 0xC70

///
/// Cached pointer to the HOB list.
/// Initialized lazily by GetHobList() by searching the system configuration
/// table for the EFI_HOB_LIST_GUID entry. Stored at address 0xC78.
///
STATIC VOID  *mHobList;           // qword_C78 at 0xC78

///
/// Cached CMOS debug level byte (at 0xC80).
/// Read from CMOS register 0x4B during debug output filtering.
///
STATIC UINT8  mCmosDebugLevel;    // n3 at 0xC80

// ============================================================================
// Constant Data (in .data section)
// ===========================================================================/

//
// These are located in the .data section of the binary. They are referenced
// by absolute address in the compiled code and are provided here for reference.
//
// Padding/random data @ 0xB60 (16 bytes) - non-GUID, used at runtime
//
// EFI_GUID mUbaProtocolGuid         @ 0xB70 = E03E0D46-5263-4845-B0A4-58D57B3177E2
//   (Same GUID as RomLayoutDxe's UBA board-type protocol)
//
// EFI_GUID mUsbOcConfigGuid         @ 0xB80 = 2638009E-3850-4E4B-B05D-042A32DBB9D1
//   (USB OC config protocol GUID for LightningRidgeEXRP)
//
// EFI_GUID mEfiHobListGuid          @ 0xB90 = 7739F24C-93D7-11D4-9A3A-0090273FC14D
//
// UBA_USBOC_PORT_MAP_ENTRY mUsbOcPortMap[4] @ 0xBA0
//   [0]: {0x00000000, 0x00000001, 0x00000008, 0x00000008}
//   [1]: {0x00000008, 0x00000002, 0x00000001, 0x00000002}
//   [2]: {0x00000008, 0x00000008, 0x00000008, 0x00000004}
//   [3]: {0x00000008, 0x00000004, 0x00000000, 0x00000000}
//
// UBA_USBOC_CONFIG_DATA mUsbOcConfigHdr @ 0xBE0
//   Signature: "PUSB"
//   Version: 2
//   Size: 0x48c
//
// Additional USB OC config data @ 0xBF0:
//   {0x00000000, 0x00000001, 0x00000001, 0x00000002}
//
// Additional USB OC config data @ 0xC00:
//   {0x00000003, 0x00000003, 0x00000008, 0x00000008}
//
// USB OC port descriptor array @ 0xC18:
//   Repeated bytes: 07 00 02 01 (USB port descriptors)
//   Interpretation: {0x07, 0x00, 0x02, 0x01} repeated =
//   Type=7(USB), SubType=0, Length[0]=2, Length[1]=1

// ============================================================================
// Local (Forward) Function Declarations
// ===========================================================================/

/**
 * Retrieves the DebugLib protocol interface from gBS, caching the result.
 *
 * Allocates a pool buffer (EfiBootServicesData = 31), then calls
 * gBS->LocateProtocol() with the DebugLib protocol GUID. If the buffer address
 * exceeds 16 bytes, the protocol is not obtained (UEFI environment validation).
 * The result is cached in mDebugProtocol (0xC70).
 *
 * @return Pointer to the DebugLib protocol interface, or NULL if unavailable.
 */
STATIC
VOID *
GetDebugProtocol (
  VOID
  );

// ============================================================================
// Function Implementations
// ===========================================================================/

/**
 * Module entry point for UsbOcUpdateDxeLightningRidgeEXRP.
 *
 * Initializes UEFI global variables (gImageHandle, gST, gBS, gRT), locates the
 * HOB list via GetHobList(), prints a debug banner via DebugPrint(), locates
 * the UBA board-type protocol, and registers the USB OC configuration data
 * by calling the protocol's RegisterUsbOcConfig function.
 *
 * Calling sequence:
 *   1. gImageHandle = ImageHandle  (if NULL, assertion fires)
 *   2. gST = SystemTable            (if NULL, assertion fires)
 *   3. gBS = SystemTable->BootServices (if NULL, assertion fires)
 *   4. gRT = SystemTable->RuntimeServices (if NULL, assertion fires)
 *   5. GetHobList(ImageHandle)      (caches HobList pointer)
 *   6. Interface = NULL
 *   7. DebugPrint(DEBUG_INFO, "UBA:UsbOcUpdate-TypeLightningRidgeEXRP\n")
 *   8. gBS->LocateProtocol(&mUbaProtocolGuid, NULL, &Interface)
 *   9. Interface->RegisterUsbOcConfig(Interface, &mUsbOcConfigGuid,
 *                                     &mUsbOcConfigHdr, 16)
 *
 * @param[in] ImageHandle  The firmware-allocated handle for this driver image.
 * @param[in] SystemTable  A pointer to the EFI System Table.
 *
 * @return EFI_SUCCESS     The USB OC config protocol was registered.
 * @return Other           Returned directly from LocateProtocol if the UBA
 *                         board-type protocol is not available.
 *
 * @note 0x396: Stores ImageHandle in gImageHandle (qword_C60).
 * @note 0x3bb: Stores SystemTable in gST (qword_C50).
 * @note 0x3e1: Reads BootServices from SystemTable + 0x60 (offset of BootServices in EFI_SYSTEM_TABLE).
 * @note 0x407: Reads RuntimeServices from SystemTable + 0x58 (offset of RuntimeServices).
 * @note 0x42e: Zero-initializes local Interface variable on stack.
 * @note 0x434: rdx = debug banner string, 0x43b: ecx = 0x80000000 (DEBUG_INFO).
 * @note 0x440: Call to DebugPrint.
 * @note 0x45a: call [gBS + 0x140] = gBS->LocateProtocol.
 * @note 0x481: call [Interface + 0x10] = Interface->RegisterUsbOcConfig.
 *       The function takes 4 args: This, ConfigGuid, ConfigData, Size.
 */
EFI_STATUS
EFIAPI
_ModuleEntryPoint (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  EFI_STATUS  Status;
  VOID        *Interface;

  //
  // Cache ImageHandle with assertion check.
  // @note 0x3a0: test rcx, rcx; jnz .continue
  //
  gImageHandle = ImageHandle;
  if (ImageHandle == NULL) {
    DebugAssert (
      "e:\\hs\\MdePkg\\Library\\UefiBootServicesTableLib\\UefiBootServicesTableLib.c",
      51,
      "gImageHandle != ((void *) 0)"
      );
  }

  //
  // Cache SystemTable with assertion check.
  // @note 0x3c2: test rbx, rbx; jnz .continue
  //
  gST = SystemTable;
  if (SystemTable == NULL) {
    DebugAssert (
      "e:\\hs\\MdePkg\\Library\\UefiBootServicesTableLib\\UefiBootServicesTableLib.c",
      57,
      "gST != ((void *) 0)"
      );
  }

  //
  // Cache BootServices from SystemTable with assertion check.
  // @note 0x3dd: mov rax, [rbx + 0x60]  (SystemTable->BootServices)
  // @note 0x3e8: test rax, rax; jnz .continue
  //
  gBS = SystemTable->BootServices;
  if (gBS == NULL) {
    DebugAssert (
      "e:\\hs\\MdePkg\\Library\\UefiBootServicesTableLib\\UefiBootServicesTableLib.c",
      63,
      "gBS != ((void *) 0)"
      );
  }

  //
  // Cache RuntimeServices from SystemTable with assertion check.
  // @note 0x403: mov rax, [rbx + 0x58]  (SystemTable->RuntimeServices)
  // @note 0x40e: test rax, rax; jnz .continue
  //
  gRT = SystemTable->RuntimeServices;
  if (gRT == NULL) {
    DebugAssert (
      "e:\\hs\\MdePkg\\Library\\UefiRuntimeServicesTableLib\\UefiRuntimeServicesTableLib.c",
      47,
      "gRT != ((void *) 0)"
      );
  }

  //
  // Locate the HOB list from the system configuration table.
  // This is required for HOB-based drivers that follow.
  // @note 0x429: call sub_5F8 (GetHobList)
  //
  GetHobList (ImageHandle);

  //
  // Print debug banner indicating this driver is executing.
  // @note 0x434: lea rdx, "UBA:UsbOcUpdate-TypeLightningRidgeEXRP\n"
  // @note 0x43b: mov ecx, 0x80000000 (DEBUG_INFO error level)
  // @note 0x440: call sub_530 (DebugPrint)
  //
  Interface = NULL;
  DebugPrint (DEBUG_INFO, "UBA:UsbOcUpdate-TypeLightningRidgeEXRP\n");

  //
  // Locate the UBA board-type protocol.
  // @note 0x453: lea rcx, unk_B70  (&mUbaProtocolGuid)
  // @note 0x451: xor edx, edx      (NULL registration key)
  // @note 0x44c: lea r8, [rsp+0x28+arg_0]  (&Interface = output)
  // @note 0x45a: call [rax + 0x140]  (gBS->LocateProtocol)
  //
  Status = gBS->LocateProtocol (
                  &mUbaProtocolGuid,
                  NULL,
                  &Interface
                  );
  if (EFI_ERROR (Status)) {
    return Status;
  }

  //
  // Call the board-type protocol's RegisterUsbOcConfig function at offset 0x10.
  // This registers the USB OC configuration protocol for LightningRidgeEXRP.
  //
  // @note 0x46a: lea r8, unk_BE0  (&mUsbOcConfigHdr = "PUSB" structure)
  // @note 0x471: mov r9d, 0x10    (size = 16 = sizeof(UBA_USBOC_CONFIG_DATA))
  // @note 0x477: lea rdx, unk_B80 (&mUsbOcConfigGuid)
  // @note 0x47e: mov rcx, rax    (Interface)
  // @note 0x481: call [rax + 0x10]  (Interface->RegisterUsbOcConfig)
  //
  return ((UBA_BOARD_TYPE_PROTOCOL *)Interface)->RegisterUsbOcConfig (
           Interface,
           &mUsbOcConfigGuid,
           &mUsbOcConfigHdr,
           sizeof (UBA_USBOC_CONFIG_DATA)
           );
}

/**
 * Provides USB OC configuration data pointer set.
 *
 * NOTE: This function has ZERO callers in the current module.
 * It is dead code, but is included for completeness. It may be referenced
 * by a function pointer table or intended for external consumption.
 *
 * Returns pointers to the three USB OC configuration data blocks:
 *   - *a1 = &mUsbOcPortMap (USB OC port mapping table at 0xBA0)
 *   - *a2 = &mUsbOcConfigData (additional USB OC config at 0xBF0)
 *   - *a3 = &mUsbOcPortDesc (USB OC port descriptor array at 0xC18)
 *
 * The mapping table at 0xBA0 defines how USB ports map to over-current
 * sense pins. The data at 0xBF0 contains additional configuration parameters.
 * The descriptor array at 0xC18 contains USB device path-like descriptors
 * (repeated pattern 0x07, 0x00, 0x02, 0x01 = USB Type 7, SubType 0).
 *
 * @param[out] a1  Receives address of USB OC port mapping table.
 * @param[out] a2  Receives address of USB OC config data.
 * @param[out] a3  Receives address of USB OC descriptor array.
 *
 * @return 0 (EFI_SUCCESS equivalent).
 *
 * @note 0x493: *a1 = &unk_BA0 (mUsbOcPortMap)
 * @note 0x49d: *a2 = &unk_BF0 (mUsbOcConfigData)
 * @note 0x4a7: *a3 = &unk_C18 (mUsbOcPortDesc)
 */
UINTN
UsbOcGetConfig (
  OUT VOID  **a1,
  OUT VOID  **a2,
  OUT VOID  **a3
  )
{
  *a1 = &mUsbOcPortMap;
  *a2 = &mUsbOcConfigData;
  *a3 = &mUsbOcPortDesc;
  return 0;
}

/**
 * Locates the HOB (Hand-Off Block) list from the UEFI System Table's
 * configuration table array.
 *
 * Iterates through SystemTable->ConfigurationTable[] looking for an entry
 * whose VendorGuid matches EFI_HOB_LIST_GUID. The comparison is done by
 * comparing the first 8 bytes and second 8 bytes of the GUID as 64-bit
 * integers via ReadUnaligned64().
 *
 * Results are cached in mHobList (0xC78). If the HOB list GUID is not found,
 * an ASSERT_EFI_ERROR is raised via DebugPrint and DebugAssert.
 *
 * @param[in] ImageHandle  Passed through from entry but unused in the loop.
 *
 * @return Pointer to the HOB list, or 0 if not found.
 *
 * @note 0x5ff: rdi = gST (SystemTable pointer from global at 0xC50)
 * @note 0x60f: [rdi + 0x68] = SystemTable->NumberOfTableEntries
 * @note 0x61b: [rdi + 0x70] = SystemTable->ConfigurationTable
 *              Each entry is 0x18 (24) bytes:
 *                +0x00: EFI_GUID VendorGuid (16 bytes)
 *                +0x10: VOID *VendorTable   (8 bytes)
 * @note 0x634: If not found, calls DebugPrint with EFI_NOT_FOUND status
 *              and DebugAssert at HobLib.c line 54.
 * @note 0x671: If mHobList is still NULL after search, asserts at line 55.
 */
VOID *
GetHobList (
  IN EFI_HANDLE  ImageHandle
  )
{
  UINTN Index;
  UINTN TableCount;
  EFI_CONFIGURATION_TABLE  *ConfigTable;

  //
  // Return cached value if already resolved.
  //
  if (mHobList != NULL) {
    return mHobList;
  }

  //
  // Initialize HOB list pointer to NULL.
  //
  mHobList = NULL;

  //
  // Get the number of configuration table entries.
  // gST + 0x68 = SystemTable->NumberOfTableEntries
  //
  TableCount = gST->NumberOfTableEntries;

  //
  // If there are entries, scan them for EFI_HOB_LIST_GUID.
  //
  if (TableCount > 0) {
    //
    // Get pointer to the configuration table array.
    // gST + 0x70 = SystemTable->ConfigurationTable
    //
    ConfigTable = gST->ConfigurationTable;

    for (Index = 0; Index < TableCount; Index++) {
      //
      // Compare current entry's VendorGuid against EFI_HOB_LIST_GUID.
      // The comparison splits the 16-byte GUID into two 8-byte halves:
      //   - First 8 bytes  (GUID.Data1 + GUID.Data2 + GUID.Data3 high)
      //   - Second 8 bytes (GUID.Data3 low + GUID.Data4)
      // This matches the EFI_HOB_LIST_GUID: 7739F24C-93D7-11D4-9A3A-0090273FC14D
      //   - First 8 bytes at unk_B90: 4C F2 39 77 D7 93 D4 11
      //   - Second 8 bytes at unk_B98: 9A 3A 00 90 27 3F C1 4D
      //
      // @note 0x63d: call sub_6D0(ImageHandle, &ConfigTable[Index].VendorGuid)
      //
      if (IsHobListGuid (ImageHandle, &ConfigTable[Index].VendorGuid)) {
        //
        // Found the HOB list entry. Extract the VendorTable pointer.
        // Each configuration table entry is 0x18 bytes:
        //   +0x00: EFI_GUID VendorGuid  (16 bytes)
        //   +0x10: VOID *VendorTable    (8 bytes)
        //
        // @note 0x6c0: rax = ConfigTable[Index] + 16 = VendorTable pointer
        //
        mHobList = ConfigTable[Index].VendorTable;
        return mHobList;
      }
    }
  }

  //
  // HOB list GUID not found in configuration table.
  // Raise ASSERT_EFI_ERROR with EFI_NOT_FOUND (0x800000000000000E).
  //
  // @note 0x64c: DebugPrint(EFI_NOT_FOUND, "\nASSERT_EFI_ERROR (Status = %r)\n")
  //
  DebugPrint (EFI_NOT_FOUND, "\nASSERT_EFI_ERROR (Status = %r)\n");
  DebugAssert (
    "e:\\hs\\MdePkg\\Library\\DxeHobLib\\HobLib.c",
    54,
    "!EFI_ERROR (Status)"
    );

  //
  // If mHobList is still NULL after the search, raise another assertion.
  //
  if (mHobList == NULL) {
    DebugAssert (
      "e:\\hs\\MdePkg\\Library\\DxeHobLib\\HobLib.c",
      55,
      "mHobList != ((void *) 0)"
      );
  }

  return mHobList;
}

/**
 * Compares a GUID against the EFI_HOB_LIST_GUID by comparing its first 8 bytes
 * and second 8 bytes independently.
 *
 * Instead of a full 16-byte EFI_GUID comparison, this function uses two
 * 8-byte unaligned reads (ReadUnaligned64) to compare the GUID halves against
 * the pre-cached values at mUsbOcHobListFirstHalf (unk_B90) and
 * mUsbOcHobListSecondHalf (unk_B98).
 *
 * The GUID halves are derived from EFI_HOB_LIST_GUID:
 *   {7739F24C-93D7-11D4-9A3A-0090273FC14D}
 *   First 8 bytes (little-endian): 0x11D493D77739F24C
 *   Second 8 bytes:                0x4DC13F2700903A9A
 *
 * @param[in] ImageHandle  Unused parameter passed through from GetHobList().
 * @param[in] GuidPtr      Pointer to the EFI_GUID to compare.
 *
 * @retval TRUE   The GUID at GuidPtr matches EFI_HOB_LIST_GUID.
 * @retval FALSE  The GUID does not match.
 *
 * @note This function implements an optimized GUID comparison that avoids
 *       calling the full CompareGuid() function from BaseLib.
 * @note 0x6f6: First call to ReadUnaligned64(&unk_B90) - first half of EFI_HOB_LIST_GUID
 * @note 0x705: Second call to ReadUnaligned64(GuidPtr) - first half of candidate GUID
 * @note 0x711: Third call to ReadUnaligned64(&unk_B98) - second half of EFI_HOB_LIST_GUID
 * @note 0x714: Fourth call to ReadUnaligned64(GuidPtr + 8) - second half of candidate
 */
BOOLEAN
IsHobListGuid (
  IN EFI_HANDLE  ImageHandle,
  IN EFI_GUID    *GuidPtr
  )
{
  //
  // Compare first 8 bytes of the GUID.
  // These are at unk_B90 in the .data section (offset 0xB90).
  //
  // @note 0x6f6: call sub_740(&unk_B90) -- read first half of stored GUID
  // @note 0x705: call sub_740(a2) -- read first half of candidate GUID
  // @note 0x738: cmp rdi, rbx -- compare first halves
  //
  if (ReadUnaligned64 (&mUsbOcHobListFirstHalf) != ReadUnaligned64 (GuidPtr)) {
    return FALSE;
  }

  //
  // Compare second 8 bytes of the GUID.
  // These are at unk_B98 in the .data section (offset 0xB98).
  //
  // Note: &GuidPtr + 8 is the second half of the 16-byte GUID structure.
  // In the context of the SystemTable configuration table array, each entry
  // is 24 bytes: 16 for GUID + 8 for pointer.
  //
  // @note 0x711: call sub_740(&unk_B98) -- read second half of stored GUID
  // @note 0x714: call sub_740(a2 + 8) -- read second half of candidate GUID
  // @note 0x738: cmp rbp, rax -- compare second halves
  //
  return ReadUnaligned64 (&mUsbOcHobListSecondHalf) == ReadUnaligned64 ((UINT8 *)GuidPtr + 8);
}

/**
 * Debug print function.
 *
 * Resolves the DebugLib protocol interface via GetDebugProtocol(), checks the
 * CMOS debug level to determine if the requested error level is enabled, and
 * if so, calls the DebugLib protocol's output function (first function pointer,
 * at offset 0x00 of the protocol interface).
 *
 * The CMOS debug level is read from RTC CMOS register 0x4B:
 *   - Bit 7 is masked off (preserves top bit for RTC NMI enable)
 *   - Register index is set to 0x4B (ORed with 0x80 to preserve NMI bit)
 *   - Values 0-3 mean level 4 (DEBUG_INFO) for the mask
 *   - Value 0 with a special board config at MMIO 0xFDAF0490 uses
 *     (register & 2) | 1 instead.
 *   - Otherwise the raw value - 1 determines the level:
 *       level 1 -> mask 0x80000004 (DEBUG_INIT | DEBUG_INFO)
 *       level >1 -> mask 0x80000046 (various debug bits)
 *
 * @param[in] ErrorLevel  The debug error level mask to check.
 * @param[in] Format      A format string for the debug message.
 * @param[in] ...         Variable arguments for the format string.
 *
 * @return The return value from the DebugLib protocol's output function,
 *         or 0 if the protocol is not available or the error level is
 *         not enabled.
 *
 * @note 0x55b: in al, dx  -- read from CMOS port 0x70
 * @note 0x560: and al, 0xCB -- mask: clear bits 2, 4, 5 (preserve NMI and other flags)
 * @note 0x560: or al, 0x4B  -- select CMOS register 0x4B
 * @note 0x565: out 0x70, al -- write CMOS index
 * @note 0x565: in al, 0x71  -- read value from CMOS data port
 * @note 0x576-0x582: Fallback read from MMIO 0xFDAF0490 if CMOS value is 0
 * @note 0x5af: call [r9]  -- call DebugLib protocol output function
 */
UINTN
EFIAPI
DebugPrint (
  IN UINTN       ErrorLevel,
  IN CONST CHAR8 *Format,
  ...
  )
{
  UINTN   ReturnValue;
  UINT64  DebugLevel;
  UINT8   CmosValue;
  UINT32  DebugMask;
  VOID    *DebugProtocol;
  VA_LIST VaList;

  VA_START (VaList, Format);

  //
  // Get the DebugLib protocol interface (cached).
  //
  DebugProtocol = GetDebugProtocol ();
  ReturnValue = 0;

  if (DebugProtocol != NULL) {
    //
    // Read debug level from CMOS register 0x4B.
    // Access RTC CMOS ports 0x70/0x71:
    //   Port 0x70 = CMOS index/address register
    //   Port 0x71 = CMOS data register
    //
    // Step 1: Read current CMOS index register value.
    // Step 2: Mask off bits to preserve NMI enable (bit 7 = 0x80)
    //         and set the register address to 0x4B.
    //         and al, 0xCB means:
    //           - Keep bits 7, 3, 1, 0 (0xCB inverted = 0x34 = bits 2,4,5 cleared)
    //           - Then OR with 0x4B to set bits 0, 1, 3, 6
    //           - Result: register index = 0x4B | (0x80 if NMI enabled)
    //
    // @note 0x55b: in al, 0x70 -- read current CMOS index
    // @note 0x560: and al, 0xCB -- preserve NMI and select bits
    // @note 0x560: or al, 0x4B -- set register address to 0x4B
    // @note 0x565: out 0x70, al -- write to CMOS index port
    //
    CmosValue = IoRead8 (RTC_INDEX_PORT);
    CmosValue = (CmosValue & 0xCB) | CMOS_DEBUG_LEVEL_REGISTER;
    IoWrite8 (RTC_INDEX_PORT, CmosValue);

    //
    // Read the debug level value from CMOS data port.
    //
    // @note 0x565: in al, 0x71 -- read from CMOS data port
    //
    DebugLevel = IoRead8 (RTC_DATA_PORT);

    //
    // Determine the debug mask based on the CMOS value.
    //
    if (DebugLevel > 3) {
      //
      // For values > 3, check the cached CMOS debug level.
      // If the cached level is 0, fall through to the board config check.
      //
      DebugLevel = mCmosDebugLevel;
      if (DebugLevel == 0) {
        //
        // Read board configuration from MMIO register 0xFDAF0490.
        // This is a platform-specific register that indicates the board type
        // or configuration variant.
        //
        // The low byte is read: bit 1 indicates some board variant,
        // and bit 0 is always set. Result = (register & 2) | 1.
        //
        // @note 0x576-0x582: Read from 0xFDAF0490 if CMOS debug level is 0
        //
        DebugLevel = (*(volatile UINT32 *)BOARD_CONFIG_MMIO_ADDR & 2) | 1;
      }
    }

    //
    // Calculate the debug mask from the debug level.
    // level - 1 must be <= 0xFD (i.e., level >= 1 and level < 0xFF)
    // to enter the mask calculation block.
    //
    // @note 0x586: n3_1 - 1
    // @note 0x58a: cmp (n3_1 - 1), 0xFD; ja .skip
    //
    if ((DebugLevel > 0) && ((DebugLevel - 1) <= 0xFD)) {
      //
      // Level 1 -> mask = 0x80000004 (DEBUG_INIT | DEBUG_INFO)
      // Level >1 -> mask = 0x80000046 (multiple debug flags)
      //
      // @note 0x593: v4 = 0x80000046 (for level > 1)
      // @note 0x599: v4 = 0x80000004 (if level == 1)
      // @note 0x58e: LOBYTE(v3) = 4 (return value placeholder)
      //
      if (DebugLevel == 1) {
        DebugMask = 0x80000004;
      } else {
        DebugMask = 0x80000046;
      }

      //
      // Check if the requested ErrorLevel is enabled by the mask.
      //
      // @note 0x5a0: test (v4 & a1); jz .skip
      //
      if ((DebugMask & ErrorLevel) != 0) {
        //
        // Call the DebugLib protocol's output function.
        // Protocol interface layout:
        //   [v5 + 0x00] = Output function pointer
        //   [v5 + 0x08] = Assert function pointer
        //
        // The output function takes:
        //   rcx = ErrorLevel
        //   rdx = Format string
        //   r8  = VA_LIST (variable arguments)
        //
        // @note 0x5af: call [r9] -- call DebugLib protocol output function
        //
        ReturnValue = ((DEBUGLIB_PROTOCOL *)DebugProtocol)->DebugPrint (
                       ErrorLevel,
                       Format,
                       VaList
                       );
      }
    }
  }

  return ReturnValue;
}

/**
 * ASSERT assertion failure handler.
 *
 * Resolves the DebugLib protocol via GetDebugProtocol() and calls its
 * assertion failure handler function at offset 0x08 in the protocol interface.
 *
 * The assertion handler takes:
 *   rcx = FileName (source file name)
 *   rdx = LineNumber (line in source file)
 *   r8  = Description (assertion description string)
 *
 * @param[in] FileName     Source file name where the assertion occurred.
 * @param[in] LineNumber   Line number of the assertion.
 * @param[in] Description  Description of the failed assertion.
 *
 * @return 0 if the DebugLib protocol is not available, or the return value
 *         from the assertion handler otherwise.
 *
 * @note 0x5cb: call [result + 8] -- call DebugLib protocol's Assert function
 *              at offset 0x08 of the protocol interface.
 */
UINTN
DebugAssert (
  IN CONST CHAR8  *FileName,
  IN UINTN        LineNumber,
  IN CONST CHAR8  *Description
  )
{
  VOID   *DebugProtocol;
  UINTN  Result;

  DebugProtocol = GetDebugProtocol ();
  Result = 0;

  if (DebugProtocol != NULL) {
    //
    // Call the DebugLib protocol's assertion handler at offset 0x08.
    //
    Result = ((DEBUGLIB_PROTOCOL *)DebugProtocol)->DebugAssert (
              FileName,
              LineNumber,
              Description
              );
  }

  return Result;
}

/**
 * Retrieves the DebugLib protocol interface from gBS, caching the result.
 *
 * Allocates a boot services data buffer (pool type = 31 = EfiBootServicesData)
 * using gBS->AllocatePool (BootServices + 0x18 = 24) and immediately frees it
 * with gBS->FreePool (BootServices + 0x20 = 32).
 *
 * This pool allocation/free cycle serves as a size check: if the allocation
 * succeeds and the returned buffer is <= 16 bytes, it indicates a valid UEFI
 * environment. Otherwise (size > 16), NULL is returned as a guard.
 *
 * Then calls gBS->LocateProtocol() (BootServices + 0x140 = 320) to obtain the
 * DebugLib protocol interface. The result is cached in mDebugProtocol (0xC70).
 *
 * The DebugLib protocol GUID is stored at address 0xB60 in the .data section,
 * but differs between modules. In this module, bytes at 0xB60 are non-GUID
 * runtime data (not a standard GUID like in RomLayoutDxe).
 *
 * @return Pointer to the DebugLib protocol interface, or NULL if unavailable
 *         or if the pool check indicates an invalid UEFI environment.
 *
 * @note 0x4c7: call [BootServices + 0x18] = gBS->AllocatePool(31, 0, &Buffer)
 *              Note: the original decompilation shows AllocatePool with 2 args,
 *              but UEFI spec defines 3 args. This suggests a custom wrapper or
 *              simplified calling convention.
 * @note 0x4ca: call [BootServices + 0x20] = gBS->FreePool(Buffer)
 * @note 0x4e2: if (Buffer <= 0x10) -- environment validation guard
 * @note 0x4ee: call [BootServices + 0x140] = gBS->LocateProtocol(&ProtocolGuid, NULL, &mDebugProtocol)
 *              The protocol GUID for LocateProtocol is passed as the first argument,
 *              but it's NOT at 0xB60 in this module (unlike RomLayoutDxe).
 *              The actual DebugLib GUID location differs between modules.
 */
STATIC
VOID *
GetDebugProtocol (
  VOID
  )
{
  VOID   *Buffer;
  EFI_STATUS  Status;

  //
  // Return cached value if already resolved.
  //
  if (mDebugProtocol != NULL) {
    return mDebugProtocol;
  }

  //
  // Allocate a small pool buffer (EfiBootServicesData = 31) and free it.
  // This is a UEFI environment validation check: if the allocation succeeds
  // and the buffer address is within a reasonable range (<= 0x10), proceed.
  // On minimal or non-UEFI environments, the allocation may behave differently.
  //
  // @note 0x4df: mov ecx, 31  (EfiBootServicesData pool type)
  // @note 0x4df: call [BootServices + 0x18]  (AllocatePool)
  // @note 0x4e2: call [BootServices + 0x20]  (FreePool)
  //
  Buffer = NULL;
  gBS->AllocatePool (EfiBootServicesData, 0, &Buffer);
  gBS->FreePool (Buffer);

  if ((UINTN)Buffer <= 0x10) {
    //
    // The buffer size check suggests we are in a valid UEFI environment with
    // properly functioning boot services.
    // Locate the DebugLib protocol.
    //
    // @note 0x4ee: call [BootServices + 0x140]  (LocateProtocol)
    // @note 0x4f2: Protocol GUID at unk_B60 is used here -- but in this module,
    //              the data at 0xB60 is NOT a standard DebugLib GUID.
    //              This may be handled differently or the GUID is encoded
    //              at a different offset.
    //
    Status = gBS->LocateProtocol (
                  &mDebugProtocolGuid,   // Encoded differently in this module
                  NULL,
                  &mDebugProtocol
                  );
    if (EFI_ERROR (Status)) {
      mDebugProtocol = NULL;
    }
  } else {
    mDebugProtocol = NULL;
  }

  return mDebugProtocol;
}

/**
 * Reads an unaligned 64-bit value from memory.
 *
 * Wraps the BaseLib ReadUnaligned64() function with a NULL pointer check.
 * If the Buffer pointer is NULL, raises an assertion.
 *
 * @param[in] Buffer  Pointer to the memory to read. Must not be NULL.
 *
 * @return The 64-bit value read from the given address.
 *
 * @note This function is referenced from the HOB GUID comparison.
 * @note 0x74c: if Buffer is NULL, calls DebugAssert at BaseLib\Unaligned.c:192
 * @note 0x769: return *(_QWORD *)Buffer (simple unaligned read)
 */
UINT64
ReadUnaligned64 (
  IN CONST VOID  *Buffer
  )
{
  if (Buffer == NULL) {
    DebugAssert (
      "e:\\hs\\MdePkg\\Library\\BaseLib\\Unaligned.c",
      192,
      "Buffer != ((void *) 0)"
      );
  }

  return *(volatile UINT64 *)Buffer;
}