/** @file
  SlotDataUpdateDxeLightningRidgeEXECB3.h - Header for SlotDataUpdate DXE driver

  This DXE driver is part of the UBA (Universal BIOS Agent) framework for
  the Lightning Ridge EX EC B3 platform. It reads Platform Slot Table (PSLT)
  data from the UEFI Configuration Table and HOB database, initializing
  PCIe slot configuration for the platform.

  The driver performs the following:
    1. Locates the UBA HOB database protocol from BootServices
    2. Finds the PSLT (Platform Slot Table) HOB entries in the configuration table
    3. Copies slot configuration data into global data structures

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

#ifndef SLOT_DATA_UPDATE_DXE_LIGHTNING_RIDGE_EX_EC_B3_H_
#define SLOT_DATA_UPDATE_DXE_LIGHTNING_RIDGE_EX_EC_B3_H_

#include "../uefi_headers/Uefi.h"

// ============================================================================
// GUID Definitions
// ============================================================================

///
/// GUID for the UBA HOB Database Protocol.
/// This protocol wraps HOB list access and is located via gBS->LocateProtocol().
/// The protocol interface provides functions at offsets:
///   [+0]  - Unknown / QueryInterface
///   [+8]  - DebugPrint / log function
///   [+16] - GetNextGuidHob(EFI_GUID *Guid, VOID *Buffer, UINTN BufferSize)
///
/// {E03E0D46-5263-4845-B0A4-58D57B3177E2}
///
#define UBA_HOB_DATABASE_PROTOCOL_GUID \
  { 0xE03E0D46, 0x5263, 0x4845, \
    { 0xB0, 0xA4, 0x58, 0xD5, 0x7B, 0x31, 0x77, 0xE2 } }

///
/// GUID for the LightningRidge EXECB3 Platform Slot Table (PSLT) HOB entry.
/// This GUID identifies the HOB containing slot configuration data specific
/// to the Lightning Ridge EX EC B3 platform.
///
/// {226763AE-972C-4E3C-80D1-73B25E8CBBA3}
///
#define LIGHTNING_RIDGE_EXECB3_PSLT_HOB_GUID \
  { 0x226763AE, 0x972C, 0x4E3C, \
    { 0x80, 0xD1, 0x73, 0xB2, 0x5E, 0x8C, 0xBB, 0xA3 } }

///
/// GUID for the platform variant HOB entry (40-byte structure).
/// This GUID identifies the HOB containing additional platform variant
/// identification data.
///
/// {B93613E1-48F0-4B32-B3A8-4FEDFC7C1365}
///
#define LIGHTNING_RIDGE_EXECB3_VARIANT_HOB_GUID \
  { 0xB93613E1, 0x48F0, 0x4B32, \
    { 0xB3, 0xA8, 0x4F, 0xED, 0xFC, 0x7C, 0x13, 0x65 } }

///
/// GUID for the HOB List entry in the System Table Configuration Table.
/// Standard UEFI HOB List GUID (gEfiHobListGuid).
/// {7739F24C-93D7-11D4-9A3A-0090273FC14D}
///
#define EFI_HOB_LIST_GUID \
  { 0x7739F24C, 0x93D7, 0x11D4, \
    { 0x9A, 0x3A, 0x00, 0x90, 0x27, 0x3F, 0xC1, 0x4D } }


// ============================================================================
// UBA HOB Database Protocol Structure
// ===========================================================================/

///
/// UBA HOB Database Protocol Interface.
/// Located via gBS->LocateProtocol() using UBA_HOB_DATABASE_PROTOCOL_GUID.
///
/// Function table layout (0-indexed, each entry 8 bytes on x64):
///   [0]  - Unknown / QueryInterface
///   [1]  - DebugPrint / Log function
///         Signature: VOID (*)(UINTN DebugLevel, CONST CHAR8 *Format, ...)
///   [2]  - GetNextGuidHob
///         Signature: EFI_STATUS (*)(VOID *This,
///                                    EFI_GUID *Guid,
///                                    VOID *Buffer,
///                                    UINTN BufferSize)
///
typedef struct {
  UINT64  Unknown;              ///< Offset +0x00: Reserved function pointer
  UINT64  DebugPrint;           ///< Offset +0x08: Debug print function
  UINT64  GetNextGuidHob;       ///< Offset +0x10: Get HOB entry by GUID
} UBA_HOB_DATABASE_PROTOCOL;


// ============================================================================
// Platform Slot Table (PSLT) Structure
// ===========================================================================/

#define PSLT_SIGNATURE   SIGNATURE_32('P', 'S', 'L', 'T')
#define PSLT_VERSION     1

///
/// Platform Slot Table Entry.
/// Describes a single PCIe slot on the platform.
///
typedef struct {
  UINT32  Signature;            ///< "PSLT" - Platform SLoT signature
  UINT32  Version;              ///< PSLT structure version (currently 1)
  UINT32  Reserved1;            ///< Reserved/padding
  UINT32  Reserved2;            ///< Reserved/padding
  UINT32  Reserved3;            ///< Reserved/padding
  UINT32  Count;                ///< Number of slot entries
} PLATFORM_SLOT_TABLE;


// ============================================================================
// UBA Debug/Logging Constants
// ============================================================================

#define UBA_DEBUG_LEVEL_INFO      0x80000000
#define UBA_DEBUG_LEVEL_STATUS    0x80000000


// ============================================================================
// Global Variable Declarations
// ============================================================================

extern EFI_HANDLE               gImageHandle;
extern EFI_SYSTEM_TABLE        *gSystemTable;
extern EFI_BOOT_SERVICES       *gBootServices;
extern EFI_RUNTIME_SERVICES    *gRuntimeServices;

///
/// Cached pointer to the HOB list from EFI Configuration Table.
/// Initialized by GetHobListFromConfigTable().
/// NULL until first successful lookup.
///
extern VOID                     *gHobList;

///
/// Cached pointer to the UBA HOB Database Protocol interface.
/// Initialized on first call to LocateProtocol().
/// NULL until protocol is found.
///
extern VOID                     *gUbaHobProtocol;

///
/// PSLT HOB output buffer (32 bytes).
/// Receives data from LIGHTNING_RIDGE_EXECB3_VARIANT_HOB_GUID query.
///
extern PLATFORM_SLOT_TABLE      gSlotTableData;

///
/// Extended PSLT HOB output buffer (40 bytes).
/// Receives data from LIGHTNING_RIDGE_EXECB3_PSLT_HOB_GUID query.
///
extern UINT8                    gSlotTableDataEx[40];


// ============================================================================
// Function Prototypes
// ============================================================================

/**
  Returns platform type code for this driver's target.
  Lightning Ridge EX EC B3 returns platform type 2.

  @return  Platform type code (2 = LightningRidge EXEC B3).
**/
UINT8
EFIAPI
GetPlatformType (
  VOID
  );

/**
  Passthrough function for platform callback.
  Returns the value passed in a2 unchanged.

  @param[in]  Context   Callback context (unused)
  @param[in]  Value     Input value to pass through

  @return  Value unchanged.
**/
UINT8
EFIAPI
PlatformPassthrough (
  IN VOID   *Context,
  IN UINT8  Value
  );

/**
  Locates and caches the UBA HOB Database Protocol.
  Uses gBS->LocateProtocol() with UBA_HOB_DATABASE_PROTOCOL_GUID.
  Also acts as a TPL guard - only locates if TPL <= TPL_NOTIFY (16).

  On first call, raises TPL to TPL_HIGH_LEVEL (31), checks old TPL,
  and if <= TPL_NOTIFY, performs LocateProtocol. Results cached in
  gUbaHobProtocol global.

  @return  Pointer to the UBA_HOB_DATABASE_PROTOCOL interface,
           or NULL if not found / not safe to locate.
**/
UBA_HOB_DATABASE_PROTOCOL *
EFIAPI
GetUbaHobDatabaseProtocol (
  VOID
  );

/**
  Uses the UBA HOB Database Protocol to log a debug message.

  @param[in]  DebugLevel  Debug message severity level.
  @param[in]  Format      Format string.
  @param[in]  ...         Variable arguments.

  @return  Status code from the debug print function.
**/
UINT8
EFIAPI
UbaDebugPrint (
  IN UINTN       DebugLevel,
  IN CONST CHAR8 *Format,
  ...
  );

/**
  Assert and deadloop handler.
  Prints assert information and enters deadloop.
  Used by ASSERT_EFI_ERROR and ASSERT macros.

  @param[in]  FileName    Source file name string
  @param[in]  LineNumber  Line number in source file
  @param[in]  AssertText  Assert condition text
**/
VOID
EFIAPI
UbaAssert (
  IN CHAR8  *FileName,
  IN UINTN  LineNumber,
  IN CHAR8  *AssertText
  );

/**
  Scans the EFI System Table ConfigurationTable for an entry whose
  GUID matches gEfiHobListGuid, and caches the HOB list pointer.

  Steps:
    1. Check gHobList cache - return immediately if already found
    2. Walk SystemTable->ConfigurationTable entries (24 bytes each)
    3. Compare each entry's GUID fields against EFI_HOB_LIST_GUID
    4. If matched, cache the Interface pointer in gHobList
    5. On failure or empty table: ASSERT_EFI_ERROR and ASSERT

  This is the DXE-phase mechanism for accessing the HOB list,
  equivalent to DxeHobLib's GetHobList() but inlined.

  @return  Pointer to the cached HOB list (gHobList)
**/
VOID *
EFIAPI
GetHobListFromConfigTable (
  VOID
  );

/**
  Compares two GUIDs by matching their first and second 8-byte halves.
  Used to match a ConfigurationTable entry GUID against a target GUID.

  @param[in]  EntryAddr   Address of the ConfigurationTable entry
  @param[in]  Guid1       Address of first GUID qword in template
  @param[in]  Guid2       Address of second GUID qword in template

  @retval TRUE   GUID at EntryAddr matches {Guid1, Guid2}
  @retval FALSE  GUID does not match
**/
BOOLEAN
EFIAPI
CompareGuidQwords (
  IN VOID   *EntryAddr,
  IN VOID   *Guid1,
  IN VOID   *Guid2
  );

/**
  Reads an unaligned 64-bit value from memory with NULL pointer check.
  Asserts if Buffer is NULL.

  @param[in]  Buffer  Pointer to the 8-byte value to read (must not be NULL)

  @return  64-bit value at the given address, read unaligned.
**/
UINT64
EFIAPI
ReadUnaligned64 (
  IN CONST VOID *Buffer
  );

/**
  Main entry point for the SlotDataUpdateDxeLightningRidgeEXECB3 driver.

  Initializes UEFI globals, locates the HOB list, identifies the platform
  via debug string, queries the UBA HOB protocol for PSLT data, and
  copies slot configuration data into global buffers.

  Driver registration flow:
    1. Save ImageHandle and SystemTable to module globals
    2. Cache BootServices and RuntimeServices pointers
    3. Call GetHobListFromConfigTable() to locate HOB list
    4. Debug print "UBA:SlotDataUpdate-TypeLightningRidgeEXECB3"
    5. Locate the UBA HOB Database Protocol
    6. Query LIGHTNING_RIDGE_EXECB3_VARIANT_HOB_GUID (32-byte output)
    7. Query LIGHTNING_RIDGE_EXECB3_PSLT_HOB_GUID (40-byte output)

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

  @return  EFI_SUCCESS           The driver initialized successfully.
  @return  EFI_INVALID_PARAMETER One of the HOB queries failed.
**/
EFI_STATUS
EFIAPI
SlotDataUpdateEntryPoint (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  );

#endif /* SLOT_DATA_UPDATE_DXE_LIGHTNING_RIDGE_EX_EC_B3_H_ */