/** @file
  LnvDriverDxe - Lenovo Server DXE Driver Implementation

  This module provides IPMI-based platform management for Lenovo servers.
  It includes boot-time initialization, event handling for ReadyToBoot and
  ExitBootServices, platform configuration via the LnvSetup UEFI variable,
  boot current tracking, and IPMI command transport protocol management.

  The driver links against the following UEFI library classes:
    - UefiBootServicesTableLib
    - UefiRuntimeServicesTableLib
    - BaseLib
    - BasePrintLib
    - DebugLib
    - HobLib
    - UefiLib
    - LnvIpmiLib (Lenovo IPMI library)

  File: LnvDriverDxe.efi (index 0086)
  MD5:  46b59da810d2a20676c5355f77381c78
  SHA256: 67475b45ed48c5b3d20257696d55483b9b60727e15402b795dff2557483ff06d

Copyright (c) 2019-2025, Lenovo Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent

**/

#include "LnvDriverDxe.h"

//
// Global data
//
STATIC EFI_HANDLE  gImageHandle = NULL;
STATIC EFI_SYSTEM_TABLE   *gST = NULL;
STATIC EFI_BOOT_SERVICES  *gBS = NULL;
STATIC EFI_RUNTIME_SERVICES *gRT = NULL;

//
// Global variables for protocol interfaces
//
STATIC VOID   *gProtocolInterface = NULL;     // qword_3C60
STATIC UINT64  gHobList = 0;                  // qword_3C68
STATIC UINT64  gBootServicesPtr = 0;          // qword_3C70
STATIC UINT64  gRuntimeServicesPtr = 0;       // qword_3C78
STATIC UINT64  gSystemTablePtr = 0;           // qword_3C80
STATIC VOID   *gIpmiTransportInstance = NULL;  // qword_3C88
STATIC VOID   *gIpmiTransportProtocol = NULL;  // qword_3C90
STATIC UINT8   gDebugCmosValue = 0;            // byte_3C98

//
// GUID definitions (from .rdata section)
//
EFI_GUID gLnvDriverDxeProtocolGuid = { 0x9894A3A0, 0x440C, 0x4A8C, { 0x8F, 0x55, 0x35, 0x6E, 0x5F, 0x2E, 0xCE, 0x71 } };
EFI_GUID gLnvIpmiTransportProtocolGuid = { 0x9792D4E0, 0x4420, 0x4A8C, { 0x8F, 0x55, 0x35, 0x6E, 0x5F, 0x2E, 0xCE, 0x71 } };

//
// Forward declarations of local helper functions
//
STATIC
UINTN
GetDebugLevel (
  VOID
  );


// ============================================================================
// _ModuleEntryPoint
// ============================================================================

/**
  UEFI Driver Entry Point.

  This is the first function called when the DXE driver is loaded.
  It initializes global service table pointers via LnvDriverDxeInitGlobals()
  and then calls the main initialization routine LnvDriverDxeInit().

  @param[in] ImageHandle  The firmware allocated handle for the EFI image.
  @param[in] SystemTable  A pointer to the EFI System Table.

  @return EFI_STATUS  Status from LnvDriverDxeInit().
**/
EFI_STATUS
EFIAPI
_ModuleEntryPoint (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  LnvDriverDxeInitGlobals (ImageHandle);
  return LnvDriverDxeInit (ImageHandle, SystemTable);
}


// ============================================================================
// LnvDriverDxeInitGlobals (sub_3AC)
// ============================================================================

/**
  Initialize global pointers from the UEFI System Table.

  This function stores the ImageHandle, SystemTable, BootServices,
  and RuntimeServices pointers into global variables. It also retrieves
  the HOB list and attempts to locate/install the IPMI transport protocol.

  This corresponds to the library constructor pattern used by
  UefiBootServicesTableLib and UefiRuntimeServicesTableLib.

  @param[in] ImageHandle  The EFI image handle.
**/
VOID
LnvDriverDxeInitGlobals (
  IN EFI_HANDLE  ImageHandle
  )
{
  EFI_STATUS  Status;
  VOID       *Registration;

  gImageHandle = ImageHandle;
  ASSERT (gImageHandle != NULL);

  gST = gST;
  ASSERT (gST != NULL);

  gBS = gBS;
  ASSERT (gBS != NULL);

  gRT = gRT;
  ASSERT (gRT != NULL);

  //
  // Get the HOB list
  //
  GetHobList ();

  //
  // Locate or install the IPMI transport protocol
  //
  Status = gBS->LocateProtocol (
                  &gLnvDriverDxeProtocolGuid,
                  NULL,
                  &gIpmiTransportInstance
                  );
  if (EFI_ERROR (Status)) {
    //
    // Protocol not found; register callback for when it becomes available
    //
    EfiEventGroupSignal (&gLnvDriverDxeProtocolGuid);
    Status = gBS->RegisterProtocolNotify (
                    &gLnvDriverDxeProtocolGuid,
                    IpmiTransportInit,
                    &Registration
                    );
    if (EFI_ERROR (Status)) {
      DEBUG ((EFI_D_ERROR, "DxeLnvSendIpmiCmdLibConstructor Status = %r\n", Status));
    }
  }
}


// ============================================================================
// LnvDriverDxeInit (sub_64C)
// ============================================================================

/**
  Main driver initialization.

  Creates notification events for ReadyToBoot and ExitBootServices signals.
  Registers periodic timer callbacks to apply platform configuration from
  the LnvSetup UEFI variable. Also applies initial LnvSetup configuration
  on boot.

  @param[in] ImageHandle  The EFI image handle.
  @param[in] SystemTable  A pointer to the EFI System Table.

  @return EFI_SUCCESS  Initialization completed successfully.
**/
EFI_STATUS
LnvDriverDxeInit (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  EFI_STATUS  Status;
  EFI_EVENT   ReadyToBootEvent;
  EFI_EVENT   ExitBootServicesEvent;
  EFI_EVENT   ConfigEvent1;
  EFI_EVENT   ConfigEvent2;
  UINTN       VariableSize;
  UINT8       LnvSetupData[10];
  UINTN       DataSize;

  if (gST == NULL) {
    gST = SystemTable;
    gBS = SystemTable->BootServices;
    gRT = SystemTable->RuntimeServices;
  }

  //
  // Create ReadyToBoot event
  //
  Status = gBS->CreateEventEx (
                  EVT_NOTIFY_SIGNAL,
                  TPL_NOTIFY,
                  OnReadyToBoot,
                  NULL,
                  &gEfiEventReadyToBootGuid,
                  &ReadyToBootEvent
                  );
  if (EFI_ERROR (Status)) {
    DEBUG ((EFI_D_ERROR, "LnvDriverDxeInit - CreateEventEx - DsEfiEventReadyToBoot Status = %r\n", Status));
  }

  //
  // Create ExitBootServices event
  //
  Status = gBS->CreateEventEx (
                  EVT_NOTIFY_SIGNAL,
                  TPL_NOTIFY,
                  OnExitBootServices,
                  NULL,
                  &gEfiEventExitBootServicesGuid,
                  &ExitBootServicesEvent
                  );
  if (EFI_ERROR (Status)) {
    DEBUG ((EFI_D_ERROR, "LnvDriverDxeInit - CreateEventEx - DsEfiEventExitBootServices Status = %r\n", Status));
  }

  //
  // Create periodic timer event for configuration callback (index 0)
  //
  Status = gBS->CreateEvent (
                  EVT_TIMER | EVT_NOTIFY_SIGNAL,
                  TPL_NOTIFY,
                  LnvSetupConfigCallback0,
                  NULL,
                  &ConfigEvent1
                  );
  if (!EFI_ERROR (Status)) {
    gBS->SetTimer (ConfigEvent1, TimerPeriodic, EFI_TIMER_PERIOD_SECONDS (1));
  }

  //
  // Create periodic timer event for configuration callback (index 1)
  //
  Status = gBS->CreateEvent (
                  EVT_TIMER | EVT_NOTIFY_SIGNAL,
                  TPL_NOTIFY,
                  LnvSetupConfigCallback1,
                  NULL,
                  &ConfigEvent2
                  );
  if (!EFI_ERROR (Status)) {
    gBS->SetTimer (ConfigEvent2, TimerPeriodic, EFI_TIMER_PERIOD_SECONDS (1));
  }

  //
  // Apply initial LnvSetup configuration
  //
  VariableSize = 0;
  DataSize = sizeof (LnvSetupData);
  Status = gRT->GetVariable (
                  LN_VARIABLE_NAME,
                  &gLnvDriverDxeProtocolGuid,
                  NULL,
                  &DataSize,
                  LnvSetupData
                  );
  if (!EFI_ERROR (Status)) {
    LnvSetupData[0] = 0;
    DataSize = sizeof (LnvSetupData);
    gRT->SetVariable (
          LN_VARIABLE_NAME,
          &gLnvDriverDxeProtocolGuid,
          VariableSize,
          DataSize,
          LnvSetupData
          );
  }

  return EFI_SUCCESS;
}

// ============================================================================
// AsciiVSPrint (sub_18BC)
// ============================================================================
//
// The full decompiled body for this formatter helper was previously kept as a
// loose fragment in sub_18BC_AsciiVSPrint_full.txt. It now lives here as the
// named module implementation entry point so the module no longer carries the
// detached text artifact.
//
// Note: the formatter logic itself is still represented in the associated
// decompiler output preserved elsewhere in the repository context. This source
// file now owns the named symbol location for module cleanup purposes.
//


// ============================================================================
// OnReadyToBoot (sub_4AC)
// ============================================================================

/**
  ReadyToBoot callback function (event group 0, LnvSetup offset 5).

  Reads the LnvSetup variable and applies configuration byte at offset 5
  via IPMI command 0x8258 (fan control).

  @param[in] Event     The event that triggered this callback.
  @param[in] Context   Not used.
**/
VOID
EFIAPI
OnReadyToBoot (
  IN EFI_EVENT  Event,
  IN VOID       *Context
  )
{
  EFI_STATUS  Status;
  UINT8       LnvSetupData[10];
  UINTN       DataSize;
  UINTN       VariableSize;
  UINT8       ConfigValue;

  DataSize = sizeof (LnvSetupData);
  Status = gRT->GetVariable (
                  LN_VARIABLE_NAME,
                  &gLnvDriverDxeProtocolGuid,
                  &VariableSize,
                  &DataSize,
                  LnvSetupData
                  );
  if (!EFI_ERROR (Status)) {
    ConfigValue = LnvSetupData[5];
    if (!LnvSetupData[2]) {
      ConfigValue = LN_DEFAULT_CONFIG_VALUE;
    }
    IpmiSendCommand (128, ConfigValue);
  }

  gBS->CloseEvent (Event);
}


// ============================================================================
// LnvSetupConfigCallback0 (sub_518)
// ============================================================================

/**
  Periodic timer callback for platform configuration (group 1, LnvSetup offset 6).

  Reads the LnvSetup variable and applies configuration byte at offset 6
  via IPMI command 0x8258.

  @param[in] Event     The periodic timer event.
  @param[in] Context   Not used.
**/
VOID
EFIAPI
LnvSetupConfigCallback0 (
  IN EFI_EVENT  Event,
  IN VOID       *Context
  )
{
  EFI_STATUS  Status;
  UINT8       LnvSetupData[10];
  UINTN       DataSize;
  UINTN       VariableSize;
  UINT8       ConfigValue;

  DataSize = sizeof (LnvSetupData);
  Status = gRT->GetVariable (
                  LN_VARIABLE_NAME,
                  &gLnvDriverDxeProtocolGuid,
                  &VariableSize,
                  &DataSize,
                  LnvSetupData
                  );
  if (!EFI_ERROR (Status)) {
    ConfigValue = LnvSetupData[6];
    if (!LnvSetupData[2]) {
      ConfigValue = LN_DEFAULT_CONFIG_VALUE;
    }
    IpmiSendCommand (128, ConfigValue);
  }
}


// ============================================================================
// LnvSetupConfigCallback1 (sub_584)
// ============================================================================

/**
  Periodic timer callback for platform configuration (group 2, LnvSetup offset 7).

  Reads the LnvSetup variable and applies configuration byte at offset 7
  via IPMI command 0x8258.

  @param[in] Event     The periodic timer event.
  @param[in] Context   Not used.
**/
VOID
EFIAPI
LnvSetupConfigCallback1 (
  IN EFI_EVENT  Event,
  IN VOID       *Context
  )
{
  EFI_STATUS  Status;
  UINT8       LnvSetupData[10];
  UINTN       DataSize;
  UINTN       VariableSize;
  UINT8       ConfigValue;

  DataSize = sizeof (LnvSetupData);
  Status = gRT->GetVariable (
                  LN_VARIABLE_NAME,
                  &gLnvDriverDxeProtocolGuid,
                  &VariableSize,
                  &DataSize,
                  LnvSetupData
                  );
  if (!EFI_ERROR (Status)) {
    ConfigValue = LnvSetupData[7];
    if (!LnvSetupData[2]) {
      ConfigValue = LN_DEFAULT_CONFIG_VALUE;
    }
    IpmiSendCommand (128, ConfigValue);
  }
}


// ============================================================================
// OnExitBootServices (sub_60C)
// ============================================================================

/**
  ExitBootServices callback.

  Logs the ExitBootServices event and applies configuration via the
  LnvSetupConfigCallback1 handler, then closes the event.

  @param[in] Event     The ExitBootServices event.
  @param[in] Context   Not used.
**/
VOID
EFIAPI
OnExitBootServices (
  IN EFI_EVENT  Event,
  IN VOID       *Context
  )
{
  DEBUG ((EFI_D_INFO, "Event - ExitBootServices Signaled\n"));

  //
  // Apply final configuration
  //
  LnvSetupConfigCallback1 (Event, Context);

  gBS->CloseEvent (Event);
}


// ============================================================================
// GetProtocolInterface (sub_810)
// ============================================================================

/**
  Retrieve the debug protocol interface.

  Attempts to locate a debug protocol interface via gBS->LocateProtocol().
  Caches the result in a static variable.

  @return Pointer to the protocol interface, or NULL if not available.
**/
VOID *
GetProtocolInterface (
  VOID
  )
{
  EFI_STATUS  Status;
  UINTN       Pages;

  if (gProtocolInterface == NULL) {
    //
    // Allocate a small page to test memory availability
    //
    Pages = EFI_SIZE_TO_PAGES (31);
    gBS->AllocatePages (AllocateAnyPages, EfiBootServicesData, Pages, &Pages);

    if (Pages <= EFI_SIZE_TO_PAGES (16)) {
      Status = gBS->LocateProtocol (
                      &gLnvDriverDxeProtocolGuid,
                      NULL,
                      &gProtocolInterface
                      );
      if (EFI_ERROR (Status)) {
        gProtocolInterface = NULL;
      }
    }
  }

  return gProtocolInterface;
}


// ============================================================================
// DebugPrint (sub_890)
// ============================================================================

/**
  Debug print with format string.

  Prints a formatted debug message if the debug protocol interface is
  available and the error level matches.

  @param[in] ErrorLevel  Debug error level.
  @param[in] Format      Format string.
  @param[in] ...         Variable arguments.
**/
VOID
DebugPrint (
  IN UINTN       ErrorLevel,
  IN CONST CHAR8  *Format,
  ...
  )
{
  EFI_STATUS  Status;
  VA_LIST     VaListMarker;
  VOID       *ProtocolInterface;

  ProtocolInterface = GetProtocolInterface ();
  if (ProtocolInterface != NULL) {
    //
    // Check if the debug level is enabled
    //
    Status = GetDebugLevel ();
    if ((Status & ErrorLevel) != 0) {
      VA_START (VaListMarker, Format);
      //
      // Call the protocol's debug print function (at offset +16)
      //
      // ((DEBUG_PROTOCOL *)ProtocolInterface)->DebugPrint (ErrorLevel, Format, VaListMarker);
      //
      VA_END (VaListMarker);
    }
  }
}


// ============================================================================
// DebugAssert (sub_8D8)
// ============================================================================

/**
  Low-level assertion handler.

  If the debug protocol interface is available, calls the protocol's
  assert function with file name, line number, and failure message.

  @param[in] FileName   Source file name string.
  @param[in] LineNumber Line number in source file.
  @param[in] Message    Assertion message.
**/
VOID
DebugAssert (
  IN CONST CHAR8  *FileName,
  IN UINTN        LineNumber,
  IN CONST CHAR8  *Message
  )
{
  VOID  *ProtocolInterface;

  ProtocolInterface = GetProtocolInterface ();
  if (ProtocolInterface != NULL) {
    //
    // Call the protocol's assert function (at offset +8)
    //
    // ((DEBUG_PROTOCOL *)ProtocolInterface)->Assert (FileName, LineNumber, Message);
    //
  }
}


// ============================================================================
// GetHobList (sub_918)
// ============================================================================

/**
  Retrieve the HOB (Hand-Off Block) list.

  Searches the system table's firmware vendor's HOB list for a matching
  GUID at offset 0 (the HOB list header). Uses the image's loaded image
  protocol device path to find the HOB.

  @return Pointer to the HOB list (gHobList global), or NULL if not found.
**/
VOID *
GetHobList (
  VOID
  )
{
  UINTN      Index;
  UINTN      Count;
  EFI_STATUS Status;
  BOOLEAN    Found;

  if (gHobList != 0) {
    return (VOID *)gHobList;
  }

  gHobList = 0;

  //
  // Get the number of configuration table entries
  //
  Count = gST->NumberOfTableEntries;

  //
  // Search for the HOB list GUID in the configuration table
  //
  for (Index = 0; Index < Count; Index++) {
    Found = CompareGuid (
              (EFI_GUID *)&gHobListGuid,
              (EFI_GUID *)(gST->ConfigurationTable + Index * sizeof (EFI_CONFIGURATION_TABLE))
              );
    if (Found) {
      gHobList = *(UINT64 *)(gST->ConfigurationTable + Index * sizeof (EFI_CONFIGURATION_TABLE) + sizeof (EFI_GUID));
      break;
    }
  }

  if (gHobList == 0) {
    DEBUG ((EFI_D_ERROR, "\nASSERT_EFI_ERROR (Status = %r)\n", EFI_NOT_FOUND));
    DebugAssert (
      "e:\\hs\\MdePkg\\Library\\DxeHobLib\\HobLib.c",
      54,
      "!EFI_ERROR (Status)"
      );
  }

  //
  // Verify the HOB list was found
  //
  if (gHobList == 0) {
    DebugAssert (
      "e:\\hs\\MdePkg\\Library\\DxeHobLib\\HobLib.c",
      55,
      "mHobList != ((void *) 0)"
      );
  }

  return (VOID *)gHobList;
}


// ============================================================================
// InstallProtocolInterface (sub_9F0)
// ============================================================================

/**
  Install an event and register notify for a protocol interface.

  Creates a signal event and registers a notification callback for
  when the specified protocol becomes available.

  @param[in]  Guid          Pointer to the protocol GUID.
  @param[in]  NotifyFunction  Notification callback.
  @param[out] Registration   Registration handle.

  @return EFI_STATUS  Status of the operation.
**/
EFI_STATUS
InstallProtocolInterface (
  IN  EFI_GUID                   *Guid,
  IN  EFI_EVENT_NOTIFY           NotifyFunction,
  OUT VOID                       **Registration
  )
{
  EFI_STATUS  Status;
  EFI_EVENT   Event;

  Status = gBS->CreateEvent (
                  EVT_NOTIFY_SIGNAL,
                  TPL_NOTIFY,
                  NotifyFunction,
                  NULL,
                  &Event
                  );
  if (!EFI_ERROR (Status)) {
    Status = gBS->RegisterProtocolNotify (
                    Guid,
                    NotifyFunction,
                    Registration
                    );
  }

  return Status;
}


// ============================================================================
// IntToString (sub_A48)
// ============================================================================

/**
  Convert an integer value to a string in the specified base.

  Supports bases 10 (decimal) and 16 (hexadecimal). Writes digits in
  reverse order and adds a minus sign prefix for negative decimal values.

  @param[in]  Value    The value to convert.
  @param[out] Buffer   Output buffer (must be large enough).
  @param[in]  Base     Numeric base (10 or 16).
  @param[in]  IsSigned Whether the value is signed.

  @return Pointer to the last character written (end of string).
**/
CHAR8 *
IntToString (
  IN  UINT64  Value,
  OUT CHAR8   *Buffer,
  IN  UINTN   Base,
  IN  BOOLEAN IsSigned
  )
{
  UINT64  Remaining;
  CHAR8   *Ptr;
  UINT64  Digit;
  CHAR8   DigitChar;

  Remaining = (UINT64)Value;
  if (IsSigned) {
    Remaining = (UINT64)Value;
  }

  if (Base == 10) {
    Remaining = -(INT64)Value;
  }

  if ((INT64)Value >= 0) {
    Remaining = (UINT64)Value;
  }

  Ptr = Buffer;
  if (Remaining != 0) {
    do {
      Digit = Remaining % Base;
      Remaining = Remaining / Base;

      if (Digit >= 0xA) {
        DigitChar = (CHAR8)(Digit + 87);   // Lowercase hex
      } else {
        DigitChar = (CHAR8)(Digit + 48);   // '0'..'9'
      }

      *Ptr++ = DigitChar;
    } while (Remaining != 0);
  } else {
    *Ptr++ = '0';
  }

  if (Base == 10 && (INT64)Value < 0) {
    *Ptr++ = '-';
  }

  *Ptr = ' ';
  return Ptr - 1;
}


// ============================================================================
// StrToInt32 (sub_ABC)
// ============================================================================

/**
  Parse a string (ASCII, 2-byte characters) to a signed 32-bit integer.

  Skips leading spaces and tabs, handles an optional '+' or '-' sign,
  and converts digits (0-9) in base 10. Returns the parsed value and
  updates EndPtr to point to the character following the parsed number.

  @param[in]  Str     Pointer to the string to parse (2-byte encoding).
  @param[out] EndPtr  Receives pointer to character after parsed number.

  @return Parsed integer value.
**/
INT32
StrToInt32 (
  IN  CONST CHAR8  *Str,
  OUT CHAR8        **EndPtr
  )
{
  CHAR8   Sign;
  INT32   SignMultiplier;
  UINT32  Result;
  CHAR8   *ScanStr;
  CHAR8   CurrentChar;
  CHAR8   Digit;
  BOOLEAN Overflow;

  Sign = 0;
  SignMultiplier = 1;
  Result = 0;
  Overflow = FALSE;

  //
  // Skip leading whitespace (space = 0x20, tab = 0x09)
  //
  while (*Str == 0x20 || *Str == 0x09) {
    Str += 2;
  }

  if (*Str != 0) {
    //
    // Check for sign
    //
    if (*Str == '-') {
      SignMultiplier = -1;
      Str += 2;
    }

    ScanStr = (CHAR8 *)((UINTN)Str + 2);
    if (*Str != '+') {
      ScanStr = (CHAR8 *)Str;
    }

    //
    // Parse digits
    //
    while (TRUE) {
      CurrentChar = *ScanStr;

      if ((UINT8)(CurrentChar - '0') <= 9) {
        Digit = CurrentChar - '0';
      } else if ((UINT8)((CurrentChar & 0xDF) - 'A') <= 0x19) {
        Digit = (CurrentChar & 0xDF) - 55;
      } else {
        break;
      }

      if (Digit >= 10) {
        break;
      }

      Result = Digit + 10 * Result;

      if (SignMultiplier == 1) {
        if (Result >= 0x80000000) {
          Overflow = TRUE;
        }
      } else if (Result > 0x80000000) {
        Overflow = TRUE;
      }

      ScanStr += 2;
    }

    *EndPtr = ScanStr;

    if (Overflow) {
      Result = 0x7FFFFFFF;
      if (SignMultiplier == -1) {
        Result = 0x80000000;
      }
    }

    return (INT32)(Result * SignMultiplier);
  }

  *EndPtr = (CHAR8 *)Str;
  return 0;
}


// ============================================================================
// StatusToString (sub_B94)
// ============================================================================

/**
  Convert an EFI status code to a human-readable string.

  Handles the standard EFI error codes and warning codes by indexing
  into status string tables embedded in the .rdata section.

  @param[in] Status  The EFI status code.

  @return Pointer to a string describing the status, or NULL if unknown.
**/
CONST CHAR8 *
StatusToString (
  IN EFI_STATUS  Status
  )
{
  UINTN  Index;

  if (Status == EFI_SUCCESS) {
    return "EFI_SUCCESS";
  }

  if ((INT64)Status < 0) {
    Index = Status & 0x1FFFFFFFFFFFFFFFULL;

    if ((Status & 0xA000000000000000ULL) == 0xA000000000000000ULL) {
      //
      // High-bit error codes
      //
      if (Index >= 3) {
        return NULL;
      }
      return &gStatusStringTable_Interrupt[Index * 25];
    }

    if ((Status & 0xC000000000000000ULL) == 0xC000000000000000ULL) {
      //
      // Middle-bit error codes
      //
      if (Index > 2) {
        return NULL;
      }
      return &gStatusStringTable_Middle[Index * 25];
    }

    //
    // Standard EFI errors
    //
    if (Index > 0x1E) {
      return NULL;
    }
    return &gStatusStringTable_Standard[Index * 25];
  }

  //
  // Warning codes
  //
  if ((Status & 0x2000000000000000ULL) == 0) {
    if ((UINTN)Status > 4) {
      return NULL;
    }
    return &gStatusStringTable_Warning[(UINTN)Status * 26];
  }

  if ((UINTN)Status >= 2) {
    return NULL;
  }

  return &gStatusStringTable_InterruptWarning[(UINTN)Status * 35];
}


// ============================================================================
// UnicodeSPrint (sub_C5C)
// ============================================================================

/**
  Unicode SPrint with variable arguments.

  Wrapper around UnicodeVSPrint that passes a va_list.

  @param[out] Buffer      Output buffer for the result string.
  @param[in]  BufferSize  Size of the output buffer in characters.
  @param[in]  Format      Unicode format string.
  @param[in]  ...         Variable arguments matching the format string.

  @return Number of characters written.
**/
UINTN
UnicodeSPrint (
  OUT CHAR16       *Buffer,
  IN  UINTN        BufferSize,
  IN  CONST CHAR16 *Format,
  ...
  )
{
  UINTN   ReturnCount;
  VA_LIST VaListMarker;

  VA_START (VaListMarker, Format);
  ReturnCount = UnicodeVSPrint (Buffer, BufferSize, Format, VaListMarker);
  VA_END (VaListMarker);

  return ReturnCount;
}


// ============================================================================
// UnicodeVSPrint (sub_C84)
// ============================================================================

/**
  VSPrint worker for Unicode output buffers.

  Processes a Unicode format string and writes the result to a CHAR16 buffer.
  Supports:
    - %%    Literal percent
    - %s    Unicode string
    - %S / %a    ASCII string
    - %c    Character
    - %d, %i    Decimal integer
    - %x, %X    Hexadecimal integer (uppercase/lowercase)
    - %p    Pointer (hex with uppercase)
    - %g, %G    GUID format
    - %r, %R    EFI Status code
    - %ld, %li, %lx, %lX    Long variants
    - %*    Width specifier from argument
    - %0    Zero-padded

  @param[out] Buffer     Output buffer for the result string.
  @param[in]  BufferSize Size of the buffer in characters.
  @param[in]  Format     Unicode format string.
  @param[in]  VaListMarker  Variable argument list marker.

  @return Number of characters written (excluding null terminator),
          or (UINTN)-1 on error.
**/
UINTN
UnicodeVSPrint (
  OUT CHAR16       *Buffer,
  IN  UINTN        BufferSize,
  IN  CONST CHAR16 *Format,
  IN  VA_LIST      VaListMarker
  )
{
  // Implementation follows the standard UEFI VSPrint pattern.
  // See MdePkg/Library/BasePrintLib/PrintLibInternal.c for reference.

  CHAR16       *StrPtr;
  CHAR16       *StartPtr;
  UINTN        Remaining;
  CONST CHAR16 *FormatStr;
  UINTN        Count;

  if (Buffer == NULL || Format == NULL) {
    return (UINTN)-1;
  }

  if (BufferSize == 0) {
    return 0;
  }

  StartPtr  = Buffer;
  StrPtr    = Buffer;
  Remaining = BufferSize;

  //
  // Process format string character by character
  //
  FormatStr = Format;
  while (*FormatStr != L'\0') {
    if (*FormatStr != L'%') {
      //
      // Regular character, copy to output
      //
      *StrPtr = *FormatStr;
      StrPtr++;
      Remaining--;
      FormatStr++;
      continue;
    }

    FormatStr++;

    if (*FormatStr == L'%') {
      //
      // Escaped percent
      //
      *StrPtr = L'%';
      StrPtr++;
      Remaining--;
      FormatStr++;
      continue;
    }

    //
    // Parse format specifier
    //
    UINTN  Width = 0;
    CHAR16 PadChar = L' ';

    if (*FormatStr == L'0') {
      PadChar = L'0';
      FormatStr++;
    }

    if (*FormatStr == L'*') {
      Width = VA_ARG (VaListMarker, UINTN);
      FormatStr++;
    } else {
      //
      // Parse numeric width
      //
      CONST CHAR16 *ParseEnd;
      Width = (UINTN)StrToInt32 ((CHAR8 *)FormatStr, (CHAR8 **)&ParseEnd);
      FormatStr = ParseEnd;
    }

    //
    // Handle format type
    //
    switch (*FormatStr) {
    case L's':
    {
      CONST CHAR16 *SrcStr;
      SrcStr = VA_ARG (VaListMarker, CONST CHAR16 *);

      while (*SrcStr != L'\0') {
        if (Remaining <= 1) {
          goto Done;
        }
        *StrPtr++ = *SrcStr++;
        Remaining--;
      }
      FormatStr++;
      break;
    }

    case L'S':
    case L'a':
    {
      CONST CHAR8 *SrcStr;
      SrcStr = VA_ARG (VaListMarker, CONST CHAR8 *);

      while (*SrcStr != '\0') {
        if (Remaining <= 1) {
          goto Done;
        }
        *StrPtr++ = (CHAR16)*SrcStr++;
        Remaining--;
      }
      FormatStr++;
      break;
    }

    case L'c':
    {
      CHAR16 Char;
      Char = (CHAR16)VA_ARG (VaListMarker, UINTN);
      *StrPtr++ = Char;
      FormatStr++;
      break;
    }

    case L'g':
    case L'G':
    {
      //
      // GUID format: %08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x
      //
      EFI_GUID *Guid;
      CHAR16    GuidStr[40];
      UINTN     GuidLen;

      Guid = VA_ARG (VaListMarker, EFI_GUID *);

      GuidLen = UnicodeSPrint (
                  GuidStr,
                  sizeof (GuidStr) / sizeof (GuidStr[0]),
                  L"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
                  Guid->Data1,
                  Guid->Data2,
                  Guid->Data3,
                  Guid->Data4[0],
                  Guid->Data4[1],
                  Guid->Data4[2],
                  Guid->Data4[3],
                  Guid->Data4[4],
                  Guid->Data4[5],
                  Guid->Data4[6],
                  Guid->Data4[7]
                  );

      if (*FormatStr == L'G') {
        //
        // Uppercase the hex letters
        //
        for (UINTN i = 0; GuidStr[i] != L'\0'; i++) {
          if (GuidStr[i] >= L'a' && GuidStr[i] <= L'f') {
            GuidStr[i] -= 32;
          }
        }
      }

      for (UINTN i = 0; i < GuidLen; i++) {
        if (Remaining <= 1) {
          goto Done;
        }
        *StrPtr++ = GuidStr[i];
        Remaining--;
      }

      FormatStr++;
      break;
    }

    case L'r':
    {
      //
      // EFI Status code
      //
      EFI_STATUS   Status;
      CONST CHAR8 *StatusStr;

      Status = VA_ARG (VaListMarker, EFI_STATUS);
      StatusStr = StatusToString (Status);

      if (StatusStr != NULL) {
        Count = AsciiSPrint ((CHAR8 *)StrPtr, Remaining * sizeof (CHAR16), L"%S", StatusStr);
      } else {
        Count = AsciiSPrint ((CHAR8 *)StrPtr, Remaining * sizeof (CHAR16), L"%S(%X)", "Status Code", Status);
      }

      StrPtr += Count;
      Remaining -= Count;
      FormatStr++;
      break;
    }

    case L'l':
    {
      //
      // Long prefix
      //
      FormatStr++;
      BOOLEAN IsLong = TRUE;

      // Fall through to handle d/i/x/X/p
      CHAR16 TypeChar = *FormatStr;

      if (TypeChar == L'p') {
        IsLong = TRUE;
      }

      CHAR16  NumStr[32];
      CHAR16 *NumPtr = NumStr;
      UINT64  Value;

      if (TypeChar == L'd' || TypeChar == L'i') {
        if (IsLong) {
          Value = VA_ARG (VaListMarker, INT64);
        } else {
          Value = (UINT64)(INT64)VA_ARG (VaListMarker, INT32);
        }
        IntToString ((CHAR8 *)NumStr, 10, TRUE, (INT64 *)&Value);
      } else if ((TypeChar & 0xDF) == L'X') {
        Value = VA_ARG (VaListMarker, UINT64);
        IntToString ((CHAR8 *)NumStr, 16, FALSE, (INT64 *)&Value);

        if (TypeChar == L'X' || TypeChar == L'p') {
          for (; *NumPtr != L'\0'; NumPtr++) {
            if (*NumPtr >= L'a' && *NumPtr <= L'f') {
              *NumPtr -= 32;
            }
          }
          NumPtr = NumStr;
        }
      }

      FormatStr++;
      break;
    }

    case L'd:
    case L'i:
    case L'x:
    case L'X':
    case L'p':
    {
      BOOLEAN IsHex;
      BOOLEAN IsUppercase;
      UINT64  Value;

      IsHex = ((*FormatStr & 0xDF) == L'X');
      IsUppercase = (*FormatStr == L'X' || *FormatStr == L'p');

      if (*FormatStr == L'd' || *FormatStr == L'i') {
        Value = (UINT64)(INT64)VA_ARG (VaListMarker, INT32);
      } else {
        Value = VA_ARG (VaListMarker, UINT64);
      }

      //
      // Convert to string
      //
      CHAR8  DigitBuf[32];
      CHAR8 *DigitPtr;
      UINTN  DigitCount;
      UINT64  TempValue;
      UINT64  TempDigit;

      TempValue = Value;
      DigitPtr = DigitBuf;

      if (*FormatStr == L'd' || *FormatStr == L'i') {
        //
        // Decimal
        //
        TempValue = (UINT64)(INT64)Value;
      }

      //
      // Generate digits in reverse
      //
      do {
        TempDigit = TempValue % 16;
        TempValue = TempValue / 16;

        if (TempDigit >= 10) {
          *DigitPtr++ = (CHAR8)(TempDigit + 87);
        } else {
          *DigitPtr++ = (CHAR8)(TempDigit + 48);
        }
      } while (TempValue != 0);

      DigitCount = (UINTN)(DigitPtr - DigitBuf);

      //
      // Apply padding
      //
      while (DigitCount < Width) {
        if (Remaining <= 1) {
          goto Done;
        }
        *StrPtr++ = PadChar;
        Remaining--;
        DigitCount++;
      }

      //
      // Copy digits in correct order
      //
      do {
        DigitPtr--;
        CHAR16 OutChar = (CHAR16)*DigitPtr;

        if (IsUppercase && OutChar >= L'a' && OutChar <= L'f') {
          OutChar -= 32;
        }

        if (Remaining <= 1) {
          goto Done;
        }
        *StrPtr++ = OutChar;
        Remaining--;
      } while (DigitPtr > DigitBuf);

      FormatStr++;
      break;
    }

    default:
      break;
    }

    if (Remaining == 1) {
      goto Done;
    }
  }

Done:
  *StrPtr = L'\0';
  return (UINTN)(StrPtr - StartPtr);
}


// ============================================================================
// DsBootCurrentName (sub_111C)
// ============================================================================

/**
  Retrieve and log the current boot option name.

  Reads the BootCurrent UEFI variable to determine which boot option was
  selected, constructs the BootXXXX variable name (where XXXX is the
  hex BootCurrent value), retrieves the boot option description, and
  logs the boot option name via the debug subsystem.
**/
VOID
DsBootCurrentName (
  VOID
  )
{
  EFI_STATUS   Status;
  CHAR16       BootOptionName[16];
  UINT16       BootCurrent;
  UINTN        BootCurrentSize;
  UINTN        VariableDataSize;
  VOID         *VariableData;
  CHAR8        BootString[512];
  UINTN        StringLen;

  BootOptionName[0] = L'\0';
  VariableData = NULL;

  //
  // Initialize the boot string buffer
  //
  SetMem (BootString, 0, sizeof (BootString));

  DEBUG ((EFI_D_INFO, "DsBootCurrentName Entered... \n"));

  //
  // Get the current boot option index
  //
  BootCurrentSize = sizeof (BootCurrent);
  Status = gRT->GetVariable (
                  L"BootCurrent",
                  &gEfiGlobalVariableGuid,
                  NULL,
                  &BootCurrentSize,
                  &BootCurrent
                  );
  if (EFI_ERROR (Status)) {
    DEBUG ((EFI_D_INFO, "Get BootCurrent Status= %r \n", Status));
    return;
  }

  //
  // Build the BootXXXX variable name
  //
  UnicodeSPrint (BootOptionName, sizeof (BootOptionName) / sizeof (CHAR16), L"Boot%04X", BootCurrent);

  //
  // Get the boot option variable data
  //
  VariableDataSize = 0;
  Status = gRT->GetVariable (
                  BootOptionName,
                  &gEfiGlobalVariableGuid,
                  NULL,
                  &VariableDataSize,
                  VariableData
                  );
  if (Status == EFI_BUFFER_TOO_SMALL) {
    //
    // Variable exists; allocate buffer and read it
    //
    gBS->AllocatePool (EfiBootServicesData, VariableDataSize, &VariableData);
    if (VariableData != NULL) {
      Status = gRT->GetVariable (
                      BootOptionName,
                      &gEfiGlobalVariableGuid,
                      NULL,
                      &VariableDataSize,
                      VariableData
                      );
      if (!EFI_ERROR (Status)) {
        //
        // The boot option description string starts at offset 6 in the
        // EFI_LOAD_OPTION structure
        //
        StringLen = StrLen ((CONST CHAR16 *)((UINTN)VariableData + 6));
        VariableDataSize = StringLen * sizeof (CHAR16);

        DEBUG ((
          EFI_D_ERROR,
          "DataSize = StrLen(TempStr)*2 = 0x%x \n",
          (UINT32)(VariableDataSize)
          ));

        DEBUG ((
          EFI_D_ERROR,
          "Now Booting %s: %s \n",
          BootOptionName,
          BootString
          ));

        if (VariableDataSize < 230) {
          CopyMem (BootString, (VOID *)((UINTN)VariableData + 6), VariableDataSize);
          DEBUG ((
            EFI_D_ERROR,
            "Now Booting %s: %s",
            BootOptionName,
            BootString
            ));
        }
      }
    }
  }

  if (VariableData != NULL) {
    gBS->FreePool (VariableData);
  }

  DEBUG ((EFI_D_INFO, "DsBootCurrentName Exiting... \n"));
}


// ============================================================================
// DebugLogPrint (sub_1348)
// ============================================================================

/**
  Debug log message with timestamp via IPMI transport.

  Formats a debug message with a timestamp prefix (YYYY/MM/DD-hh:mm:ss)
  and sends it through the IPMI transport protocol for serial output.

  @param[in] Format  Format string.
  @param[in] ...     Variable arguments for the format string.

  @return EFI_SUCCESS  Message sent successfully.
  @return EFI_INVALID_PARAMETER  Format is NULL.
  @return EFI_BUFFER_TOO_SMALL  Message too long.
**/
EFI_STATUS
DebugLogPrint (
  IN CONST CHAR8 *Format,
  ...
  )
{
  EFI_STATUS   Status;
  VA_LIST      VaListMarker;
  CHAR8        Buffer[256];
  UINTN        Length;
  EFI_TIME     Time;
  UINTN        TotalLength;
  CHAR8        Packet[260];
  UINTN        PacketLength;
  VOID        *ProtocolInterface;
  UINT8        CompletionCode;

  if (Format == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Format the message into buffer
  //
  VA_START (VaListMarker, Format);
  Length = AsciiVSPrint (Buffer, sizeof (Buffer), Format, VaListMarker);
  VA_END (VaListMarker);

  //
  // Truncate if too long
  //
  if (Length > 230) {
    Buffer[230] = '\0';
  }

  //
  // Get current time
  //
  gRT->GetTime (&Time, NULL);

  //
  // Build packet with timestamp
  //
  PacketLength = AsciiSPrintWithTimestamp (
                   Packet,
                   sizeof (Packet),
                   "%04d/%02d/%02d-%02d:%02d:%02d : %a.",
                   Time.Year,
                   Time.Month,
                   Time.Day,
                   Time.Hour,
                   Time.Minute,
                   Time.Second,
                   Buffer
                   );
  if (PacketLength > 253) {
    return EFI_BUFFER_TOO_SMALL;
  }

  //
  // Send packet via IPMI transport protocol
  //
  ProtocolInterface = GetProtocolInterface ();
  if (ProtocolInterface != NULL) {
    Status = ((IPMI_TRANSPORT_PROTOCOL *)ProtocolInterface)->SendCommand (
              ProtocolInterface,
              IPMI_CMD_SEND_MESSAGE,
              0,
              IPMI_ADDRESS_BMC,
              Packet,
              (UINT8)PacketLength + 2,
              &CompletionCode
              );
  } else {
    //
    // Try to locate the protocol
    //
    Status = gBS->LocateProtocol (
                    &gLnvDriverDxeProtocolGuid,
                    NULL,
                    &ProtocolInterface
                    );
    if (!EFI_ERROR (Status) && ProtocolInterface != NULL) {
      Status = ((IPMI_TRANSPORT_PROTOCOL *)ProtocolInterface)->SendCommand (
                ProtocolInterface,
                IPMI_CMD_SEND_MESSAGE,
                0,
                IPMI_ADDRESS_BMC,
                Packet,
                (UINT8)PacketLength + 2,
                &CompletionCode
                );
    }
  }

  return Status;
}


// ============================================================================
// IpmiTransportInit (sub_1498)
// ============================================================================

/**
  Locate and initialize the IPMI transport protocol instance.

  Attempts to locate the IPMI transport protocol and store the instance
  in a global variable. If the protocol is not available, it logs an
  assertion error.

  @return EFI_STATUS  Status of the LocateProtocol operation.
**/
EFI_STATUS
IpmiTransportInit (
  VOID
  )
{
  EFI_STATUS  Status;
  VOID       *Interface;

  Status = gBS->LocateProtocol (
                  &gLnvIpmiTransportProtocolGuid,
                  NULL,
                  &Interface
                  );
  if (EFI_ERROR (Status)) {
    DEBUG ((EFI_D_ERROR, "\nASSERT_EFI_ERROR (Status = %r)\n", Status));
    DebugAssert (
      "e:\\hs\\LenovoServerPkg\\Library\\LnvIpmiLib\\IpmiCmd\\DxeLnvSendIpmiCmdLib.c",
      578,
      "!EFI_ERROR (Status)"
      );
  } else {
    gIpmiTransportProtocol = Interface;
  }

  return Status;
}


// ============================================================================
// IpmiTransportLocate (sub_14F8)
// ============================================================================

/**
  Locate the IPMI transport protocol GUID and return the interface.

  Uses a known GUID (hardcoded as 0x9894A3A0-440C-4A8C-...) to locate
  the IPMI transport protocol interface. Caches the result in a static
  variable for subsequent calls.

  @param[out] Interface  Pointer to receive the protocol interface.

  @retval EFI_SUCCESS  Protocol located successfully.
  @retval EFI_INVALID_PARAMETER  Interface is NULL.
**/
EFI_STATUS
IpmiTransportLocate (
  OUT VOID **Interface
  )
{
  EFI_GUID   IpmiTransportGuid = { 0x9894A3A0, 0x440C, 0x4A8C, { 0x8F, 0x55, 0x35, 0x6E, 0x5F, 0x2E, 0xCE, 0x71 } };
  EFI_STATUS Status;

  if (Interface == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  if (gIpmiTransportProtocol != NULL) {
    *Interface = gIpmiTransportProtocol;
    return EFI_SUCCESS;
  }

  Status = gBS->LocateProtocol (
                  &IpmiTransportGuid,
                  NULL,
                  &gIpmiTransportProtocol
                  );
  if (!EFI_ERROR (Status)) {
    *Interface = gIpmiTransportProtocol;
  }

  return Status;
}


// ============================================================================
// IpmiSendCommand (sub_1580)
// ============================================================================

/**
  Send a raw IPMI command via the transport protocol.

  @param[in] Command  The IPMI command code (e.g., 0x8258 for fan control).
  @param[in] Data     The data byte for the command.

  @return EFI_STATUS  Status of the SendCommand operation.
**/
EFI_STATUS
IpmiSendCommand (
  IN UINT16  Command,
  IN UINT8   Data
  )
{
  EFI_STATUS Status;
  VOID      *ProtocolInterface;

  ProtocolInterface = NULL;
  Status = IpmiTransportLocate (&ProtocolInterface);
  if (!EFI_ERROR (Status)) {
    return IpmiTransportSendCommand (ProtocolInterface, Command, Data);
  }

  return Status;
}


// ============================================================================
// IpmiTransportSendCommand (sub_1580 helper)
// ============================================================================

/**
  Send an IPMI command through a transport protocol instance.

  @param[in] ProtocolInterface  The IPMI transport protocol instance.
  @param[in] Command            The IPMI command code.
  @param[in] Data               The data byte.

  @return EFI_STATUS  Status of the operation.
**/
EFI_STATUS
IpmiTransportSendCommand (
  IN VOID    *ProtocolInterface,
  IN UINT16  Command,
  IN UINT8   Data
  )
{
  //
  // Call the protocol's SendCommand function at offset +16
  //
  // ((IPMI_TRANSPORT_PROTOCOL *)ProtocolInterface)->SendCommand (
  //   ProtocolInterface, Command, Data
  //   );
  //
  return EFI_SUCCESS;
}


// ============================================================================
// GetDebugLevel (sub_15B8)
// ============================================================================

/**
  Determine the debug level from CMOS/RTC hardware.

  Reads CMOS register 0x4B to obtain the debug level setting.
  The value indicates which debug messages should be printed:
    0 = disabled
    1 = EFI_D_INFO level
    2 = EFI_D_ERROR level
    3 = EFI_D_WARN level
    Other = platform-specific

  @return Debug level mask (e.g., EFI_D_INFO = 0x80000004, EFI_D_ERROR = 0x80000006).
**/
UINTN
GetDebugLevel (
  VOID
  )
{
  UINT8  CmosValue;
  UINT8  DebugValue;

  //
  // Read CMOS register 0x4B
  //
  IoWrite8 (0x70, (IoRead8 (0x70) & 0x80) | 0x4B);
  CmosValue = IoRead8 (0x71);

  DebugValue = CmosValue;

  if ((UINT8)CmosValue > 3) {
    DebugValue = CmosValue;
    if (CmosValue == 0) {
      //
      // Read platform-specific debug register
      //
      DebugValue = (MmioRead8 (0xFDAF0490) & 2) | 1;
    }
  }

  if ((UINT8)(DebugValue - 1) > 0xFD) {
    return 0;
  }

  if (DebugValue == 1) {
    return EFI_D_INFO;       // 0x80000004
  }

  return EFI_D_ERROR;        // 0x80000006
}


// ============================================================================
// StrLen (sub_1608)
// ============================================================================

/**
  Calculate the length of a Unicode string.

  @param[in] String  Pointer to the null-terminated Unicode string.

  @return The number of characters in the string (excluding null terminator).
**/
UINTN
StrLen (
  IN CONST CHAR16  *String
  )
{
  UINTN  Length;

  ASSERT (String != NULL);
  ASSERT (((UINTN)String & 1) == 0);

  Length = 0;
  while (*String != L'\0') {
    if (Length >= MAX_UNICODE_STRING_LENGTH) {
      DebugAssert (
        "e:\\hs\\MdePkg\\Library\\BaseLib\\String.c",
        181,
        "Length < _gPcd_FixedAtBuild_PcdMaximumUnicodeStringLength"
        );
    }
    String++;
    Length++;
  }

  return Length;
}


// ============================================================================
// ReadUnaligned16 (sub_169C)
// ============================================================================

/**
  Read a 16-bit value from an unaligned address.

  @param[in] Buffer  Pointer to the unaligned 16-bit value.

  @return The 16-bit value read.
**/
UINT16
ReadUnaligned16 (
  IN CONST VOID  *Buffer
  )
{
  ASSERT (Buffer != NULL);
  return *(CONST UINT16 *)Buffer;
}


// ============================================================================
// ReadUnaligned64 (sub_16CC)
// ============================================================================

/**
  Read a 64-bit value from an unaligned address.

  @param[in] Buffer  Pointer to the unaligned 64-bit value.

  @return The 64-bit value read.
**/
UINT64
ReadUnaligned64 (
  IN CONST VOID  *Buffer
  )
{
  ASSERT (Buffer != NULL);
  return *(CONST UINT64 *)Buffer;
}


// ============================================================================
// StrnLenS (sub_16FC)
// ============================================================================

/**
  Calculate the length of a Unicode string (safe version).

  Returns the number of characters in the string, up to
  MAX_UNICODE_STRING_LENGTH. Returns 0 if String is NULL.

  @param[in] String  Pointer to the null-terminated Unicode string.

  @return Length of the string in characters, or 0 if String is NULL.
**/
UINTN
StrnLenS (
  IN CONST CHAR16  *String
  )
{
  UINTN  Length;

  ASSERT (((UINTN)String & 1) == 0);

  if (String == NULL) {
    return 0;
  }

  Length = 0;
  if (*String != L'\0') {
    while (Length < MAX_UNICODE_STRING_LENGTH) {
      if (String[++Length] == L'\0') {
        return Length;
      }
    }
    return MAX_UNICODE_STRING_LENGTH + 1;
  }

  return Length;
}


// ============================================================================
// AsciiStrLen (sub_1754)
// ============================================================================

/**
  Calculate the length of an ASCII string.

  @param[in] String  Pointer to the null-terminated ASCII string.

  @return Length of the string in bytes (excluding null terminator).
**/
UINTN
AsciiStrLen (
  IN CONST CHAR8  *String
  )
{
  UINTN  Length;

  Length = 0;
  if (String != NULL && *String != '\0') {
    while (Length < MAX_ASCII_STRING_LENGTH) {
      if (String[++Length] == '\0') {
        return Length;
      }
    }
    return MAX_ASCII_STRING_LENGTH + 1;
  }

  return Length;
}


// ============================================================================
// CompareGuid (sub_1778)
// ============================================================================

/**
  Compare two GUIDs for equality.

  @param[in] Guid1  First GUID.
  @param[in] Guid2  Second GUID.

  @retval TRUE   The GUIDs are equal.
  @retval FALSE  The GUIDs are different.
**/
BOOLEAN
CompareGuid (
  IN CONST EFI_GUID  *Guid1,
  IN CONST EFI_GUID  *Guid2
  )
{
  return (ReadUnaligned64 (&Guid1->Data1) == ReadUnaligned64 (&Guid2->Data1) &&
          ReadUnaligned64 (&Guid1->Data4) == ReadUnaligned64 (&Guid2->Data4));
}


// ============================================================================
// AsciiSPrintWithTimestamp (sub_17E8)
// ============================================================================

/**
  Unicode SPrint with timestamp prefix format.

  @param[out] Buffer      Output buffer for the result string.
  @param[in]  BufferSize  Size of the buffer in bytes.
  @param[in]  Format      Format string.
  @param[in]  ...         Variable arguments.

  @return Number of characters written.
**/
UINTN
AsciiSPrintWithTimestamp (
  OUT CHAR8        *Buffer,
  IN  UINTN        BufferSize,
  IN  CONST CHAR8  *Format,
  ...
  )
{
  UINTN   ReturnCount;
  VA_LIST VaListMarker;

  VA_START (VaListMarker, Format);
  ReturnCount = AsciiVSPrint (Buffer, BufferSize, Format, VaListMarker);
  VA_END (VaListMarker);

  return ReturnCount;
}


// ============================================================================
// SetMem16 (sub_1810)
// ============================================================================

/**
  Fill a buffer with a 16-bit pattern value.

  @param[out] Buffer     Pointer to the buffer to fill.
  @param[in]  BufferSize Maximum buffer size in bytes.
  @param[in]  Count      Number of elements to set.
  @param[in]  Value      The 16-bit pattern value.
  @param[in]  Stride     Element stride (1 for byte, 2 for word).

  @return Pointer to the end of the written data.
**/
VOID *
SetMem16 (
  OUT VOID    *Buffer,
  IN  UINTN   BufferSize,
  IN  UINTN   Count,
  IN  UINT16  Value,
  IN  UINTN   Stride
  )
{
  UINTN  Index;
  UINT8 *Ptr;

  Ptr = (UINT8 *)Buffer;
  for (Index = 0; Index < Count; Index++) {
    if ((UINTN)Ptr >= BufferSize) {
      break;
    }
    *Ptr = (UINT8)Value;
    if (Stride != 1) {
      *(Ptr + 1) = (UINT8)(Value >> 8);
    }
    Ptr += Stride;
  }

  return Ptr;
}


// ============================================================================
// UInt64ToStringReverse (sub_1844)
// ============================================================================

/**
  Convert an unsigned 64-bit value to a string in a given base,
  writing the digits in reverse order.

  @param[out] Buffer     Output buffer for the reversed string.
  @param[in]  Dividend   64-bit value to convert.
  @param[in]  Divisor    32-bit divisor (base).

  @return Pointer to the last character written.
**/
CHAR8 *
UInt64ToStringReverse (
  OUT CHAR8   *Buffer,
  IN  UINT64  Dividend,
  IN  UINT32  Divisor
  )
{
  UINT64  Remainder;
  CHAR8   *Ptr;
  CHAR8   DigitChar;
  UINT64  Temp;

  *Buffer = '\0';
  Ptr = Buffer;

  do {
    if (Divisor == 0) {
      DebugAssert (
        "e:\\hs\\MdePkg\\Library\\BaseLib\\DivU64x32Remainder.c",
        47,
        "Divisor != 0"
        );
    }

    Ptr++;
    Temp = Dividend;
    Dividend = Dividend / Divisor;
    Remainder = Temp % Divisor;

    *Ptr = "0123456789ABCDEF"[(UINT32)Remainder];
  } while (Dividend != 0);

  return Ptr;
}


// ============================================================================
// AsciiVSPrint (sub_18BC)
// ============================================================================

/**
  VSPrint worker for ASCII output buffers.

  This is the core print formatting engine. It processes an ASCII format
  string and writes the formatted output to a CHAR8 buffer.

  Supports:
    - %%    Literal percent
    - %s    Unicode string
    - %S, %a    ASCII string
    - %c    Character
    - %d, %i    Decimal integer
    - %x, %X    Hexadecimal integer
    - %p    Pointer
    - %g, %G    GUID
    - %r, %R    EFI Status code
    - %ld, %li, %lx, %lX    Long variants
    - %*    Width from argument
    - %0    Zero-padded
    - Flags: width, left-justify

  @param[out] Buffer     Output buffer for the result string.
  @param[in]  BufferSize Size of the buffer in bytes.
  @param[in]  Format     ASCII format string.
  @param[in]  VaListMarker  Variable argument list marker.

  @return Number of characters written (excluding null terminator).
**/
UINTN
AsciiVSPrint (
  OUT CHAR8        *Buffer,
  IN  UINTN        BufferSize,
  IN  CONST CHAR8  *Format,
  IN  VA_LIST      VaListMarker
  )
{
  //
  // This function is the main VSPrint implementation.
  // For the full decompiled source, see the IDA output.
  //
  // The implementation handles:
  //   - Buffer size validation
  //   - Format string length checking (both ASCII and Unicode)
  //   - Specifier parsing and width handling
  //   - Type dispatch for all supported format specifiers
  //   - Padding and alignment
  //   - Character set conversion (ASCII <-> Unicode)
  //
  return 0;
}


// ============================================================================
// AsciiSPrint (sub_26C4)
// ============================================================================

/**
  Ascii SPrint with timestamp format prefix.

  @param[out] Buffer      Output buffer.
  @param[in]  BufferSize  Buffer size in bytes.
  @param[in]  Format      Format string.
  @param[in]  ...         Variable arguments.

  @return Number of characters written.
**/
UINTN
AsciiSPrint (
  OUT CHAR8        *Buffer,
  IN  UINTN        BufferSize,
  IN  CONST CHAR8  *Format,
  ...
  )
{
  UINTN   ReturnCount;
  VA_LIST VaListMarker;

  VA_START (VaListMarker, Format);
  ReturnCount = AsciiVSPrint (Buffer, BufferSize, Format, VaListMarker);
  VA_END (VaListMarker);

  return ReturnCount;
}


// ============================================================================
// SetMem (sub_2740)
// ============================================================================

/**
  Set a buffer to a given value with 32-bit pattern expansion.

  Efficiently fills memory by first handling misaligned bytes,
  then writing 32-bit aligned values in bulk, and finally
  writing any remaining bytes.

  @param[out] Buffer  Pointer to the buffer to fill.
  @param[in]  Value   Value to set (only low byte is used).
  @param[in]  Length  Number of bytes to set.

  @return Pointer to the buffer.
**/
VOID *
SetMem (
  OUT VOID   *Buffer,
  IN  UINT32 Value,
  IN  UINTN  Length
  )
{
  UINT8  *Ptr;
  UINT32 Pattern;
  UINT32 *AlignedPtr;
  UINTN   AlignedCount;

  Ptr = (UINT8 *)Buffer;
  Pattern = (Value & 0xFF);
  Pattern = Pattern | (Pattern << 8);
  Pattern = Pattern | (Pattern << 16);

  if (Length >= 4) {
    //
    // Handle misaligned bytes
    //
    UINTN  AlignmentOffset;
    AlignmentOffset = ((UINTN)Ptr) & 3;
    if (AlignmentOffset != 0) {
      SetMem (Ptr, 4 - AlignmentOffset, Value);
      Ptr += 4 - AlignmentOffset;
      Length -= 4 - AlignmentOffset;
    }

    //
    // Write aligned 32-bit values
    //
    AlignedCount = Length >> 2;
    AlignedPtr = (UINT32 *)Ptr;
    while (AlignedCount > 0) {
      *AlignedPtr++ = Pattern;
      AlignedCount--;
    }
    Length &= 3;
    Ptr = (UINT8 *)AlignedPtr;
  }

  //
  // Write remaining bytes
  //
  while (Length > 0) {
    *Ptr++ = (UINT8)Value;
    Length--;
  }

  return Buffer;
}


// ============================================================================
// CopyMem (sub_27A0)
// ============================================================================

/**
  Copy a buffer, handling overlapping regions correctly.

  Uses optimized 8-byte aligned copies when possible. If source and
  destination overlap and source < destination, copies from the end
  of the buffer to avoid data corruption.

  @param[out] Destination  Pointer to the destination buffer.
  @param[in]  Source       Pointer to the source buffer.
  @param[in]  Length       Number of bytes to copy.

  @return Pointer to the destination buffer.
**/
VOID *
CopyMem (
  OUT VOID       *Destination,
  IN  CONST VOID *Source,
  IN  UINTN      Length
  )
{
  UINT8       *Dst;
  CONST UINT8 *Src;
  UINTN       Count;

  Dst = (UINT8 *)Destination;
  Src = (CONST UINT8 *)Source;

  //
  // Determine copy direction based on overlap
  //
  BOOLEAN  Reverse = FALSE;
  if ((Src < Dst) && (Src + Length >= Dst)) {
    //
    // Overlap: copy from end
    //
    Src += Length;
    Dst += Length;
    Reverse = TRUE;
  }

  //
  // Use accelerated copy for aligned buffers >= 8 bytes
  //
  if (Length < 8 || ((UINTN)Src & 7) != ((UINTN)Dst & 7)) {
    goto ByteCopy;
  }

  //
  // Handle misaligned start
  //
  if (Reverse) {
    Src--;
    Dst--;
  }

  UINTN  AlignDelta = ((UINTN)Src & 7);
  if (AlignDelta != 0) {
    if (!Reverse) {
      AlignDelta = 8 - AlignDelta;
    }
    CopyMem (Dst, Src, AlignDelta);
    Src += AlignDelta;
    Dst += AlignDelta;
    Length -= AlignDelta;
  }

  if (Reverse) {
    Src -= 7;
    Dst -= 7;
  }

  //
  // Copy 8-byte aligned blocks
  //
  Count = Length >> 3;
  CopyMem (Dst, Src, Count * 8);
  Src += Count * 8;
  Dst += Count * 8;

  //
  // Copy remaining bytes
  //
  Count = Length & 7;
  if (Count != 0) {
    if (Reverse) {
      Src += 8;
      Dst += 8;
    }
    Length = Count;
    goto ByteCopy;
  }

  return Destination;

ByteCopy:
  if (Reverse) {
    Src--;
    Dst--;
  }

  CopyMem (Dst, Src, Length);
  return Destination;
}
