Commit graph

1232 commits

Author SHA1 Message Date
Aaron Pop
0f0515f71b MdeModulePkg: Fix unchecked return status
https://github.com/github/codeql/blob/codeql-cli-2.7.3/csharp/ql/src/API%20Abuse/UncheckedReturnValue.qhelp

When a function has a return status, it should
be checked to verify the function completed successfully.

Failing to check the return status can result in null pointer
dereferences or use of uninitialized variables.

Signed-off-by: Aaron Pop <aaronpop@microsoft.com>
2026-08-05 02:13:24 +00:00
Aaron Pop
0bc1db4adf MdeModulePkg: Fix missing NULL tests
https://github.com/github/codeql/blob/codeql-cli-2.7.3/cpp/ql/src/Critical/MissingNullTest.qhelp

For items which allocate memory, or get a pointer from another
structure, it is important to validate that the pointers
are not null before they are dereferenced.

Signed-off-by: Aaron Pop <aaronpop@microsoft.com>
2026-08-05 02:13:24 +00:00
Aaron Pop
bf0dc7d787 MdeModulePkg: Fix comparison with wider widths
https://codeql.github.com/codeql-query-help/cpp/cpp-comparison-with-wider-type

If the narrow type (smaller range) is compared against a wide type
(larger range), the narrow value may overflow before reaching the wide
value. This can cause unexpected behavior, such as:

Infinite loops (loop condition never becomes false).
Incorrect logic (comparison results are misleading).

Signed-off-by: Aaron Pop <aaronpop@microsoft.com>
2026-08-05 02:13:24 +00:00
Theo
bc71cc972d MdeModulePkg/NvmExpressHci.c: Save time when BIOS reset with NVMes
Dispatch Shutdown Notification to every NVMe first, then polling
every NVMe t omaake sure all NVMe's shutdown processing is
completed.This will help to save a lot time when BIOS trigger
reset for Servers whose have many NVMes. Tested on a platform
with AMD EPYC cpu with 26 NVMes, this method reduce reset time
from 3 minutes to 10 seconds.

Signed-off-by: Theo <theo.tao@foxmail.com>
2026-08-01 03:58:29 +00:00
Jared Pan
7c2ec06a93 MdeModulePkg/UsbBusDxe: Fix UsbPortReset might run into recursive loop
UsbSelectConfig will introduce the UsbConnectDriver call.
If this UsbPortReset is happened in the Usb device driver Start() routine and the device FW can not be recovered by PortReset, the UsbSelectConfig will introduce the recursive loop.

[Suggested solution]
Since UsbPortReset should not change the Bus Topology, the Reset flow should only SetAddress and reconfigure the device.

Signed-off-by: Marlboro Chuang <marlboro.chuang@dell.com>
Signed-off-by: Jared Pan <jared.pan@dell.com>
2026-07-31 10:54:54 +00:00
Jared Pan
4d5f8e68a1 MdeModulePkg/UsbBusDxe: BOS Descriptor Check for SS Devices
Some SuperSpeed-capable devices may fall back to High-Speed
mode and cause subsequent commands to fail.

[Suggested Solution]
Check the BOS descriptor to verify SuperSpeed support and
trigger a port reset if needed to re-enumerate the device
properly.

Signed-off-by: Marlboro Chuang <marlboro.chuang@dell.com>
Signed-off-by: Jared Pan <jared.pan@dell.com>
2026-07-22 07:25:57 +00:00
DC-Damien
6a9c048ba5 MdeModulePkg/UsbBusPei: Use dynamic buffer for USB configuration data
USB devices whose configuration descriptor TotalLength exceeds 1024
bytes (e.g. IR cameras with large descriptor tables) previously hit
an EFI_DEVICE_ERROR hard-limit and failed to enumerate in PEI.

Replace the fixed array with a UINT8 * pointer and dynamically
allocate the exact amount of memory required via
PeiServicesAllocatePool() after the TotalLength is learned from the
initial 4-byte descriptor probe.

Signed-off-by: Damien Chen <damien.chen@dell.com>
2026-07-21 03:50:20 +00:00
Phil Noh
c70637de12 MdeModulePkg/PciBusDxe: Honor SpecificFlag for PMem64 in UpdatePciInfo
When UpdatePciInfo() downgrades a PciBarTypePMem64 BAR to a 32-bit type
via EFI_INCOMPATIBLE_PCI_DEVICE_SUPPORT_PROTOCOL, it unconditionally
assigns PciBarTypePMem32 regardless of SpecificFlag, placing the BAR in
the prefetchable bridge window even when the platform intended the
non-prefetchable window.

The ACPI resource descriptor's SpecificFlag field encodes the intended
prefetchability of the constrained resource, using the bit:
EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE.

Fix this by checking the bit in SpecificFlag to select PciBarTypePMem32 or
PciBarTypeMem32, consistent with DumpPpbPaddingResource() in
PciEnumeratorSupport.c that uses the bit as the sole discriminator
between the two 32-bit BAR types.

Signed-off-by: Phil Noh <Phil.Noh@amd.com>
2026-07-17 09:03:00 +00:00
Mingjie Shen
049dc848c4 MdeModulePkg: Fix incorrect EfiPciWidth* enum literals
In arguments of EFI_PCI_IO_PROTOCOL member functions, replace the
EfiPciWidth* enum literals from
EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH with the matching
EfiPciIoWidth* values from EFI_PCI_IO_PROTOCOL_WIDTH.

This keeps the call sites aligned with the protocol they actually use.
The old values were copied from EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL code,
so they obscured the intent of the calls and relied on an explicit
cast.

This mimics commit 8ba64a9a94 ("UefiPayloadPkg: Fix build failure with
CLANGPDB").

Generated by coccinelle script.

``` smpl
@initialize:python@
@@

def to_pci_io_width(name):
    return name.replace("EfiPciWidth", "EfiPciIoWidth", 1)

@normalize@
typedef EFI_PCI_IO_PROTOCOL;
typedef EDKII_PCI_DEVICE_PPI;
type T =~ "^EFI_PCI_IO_PROTOCOL_WIDTH$";
EFI_PCI_IO_PROTOCOL *x;
EDKII_PCI_DEVICE_PPI *y;
identifier bad =~ "EfiPciWidth(Uint|FifoUint|FillUint)(8|16|32|64)";
identifier top_op =~ "^(PollMem|PollIo|CopyMem)$";
identifier space =~ "^(Mem|Io|Pci)$";
identifier rw =~ "^(Read|Write)$";
fresh identifier good = script:python(bad) { to_pci_io_width(bad) };
expression first;
expression list rest;
@@
(
  x->top_op
|
  y->PciIo.top_op
|
  x->space.rw
|
  y->PciIo.space.rw
) (
  first,
- (T)bad
+ good
  ,
  rest
  )
```

Verified with:
- `build -p MdeModulePkg/MdeModulePkg.dsc -m MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxe.inf -a IA32 -b DEBUG -t GCC`
- `build -p MdeModulePkg/MdeModulePkg.dsc -m MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxe.inf -a X64 -b DEBUG -t GCC`

Signed-off-by: Mingjie Shen <shen497@purdue.edu>
2026-07-14 00:06:22 +00:00
Jared Pan
8c0dea946f MdeModulePkg/UsbBusDxe: Manufacturer String Descriptor Caching
Certain devices require immediate follow-up commands
after reading the LANGID string to fetch Manufacturer,
Product, or SerialNumber strings.

[Suggested Solution]
These strings are now cached after initial retrieval
to allow UsbIoGetStringDescriptor() to return them
directly, improving efficiency and stability.

Signed-off-by: Marlboro Chuang <marlboro.chuang@dell.com>
Signed-off-by: Jared Pan <jared.pan@dell.com>
2026-06-30 11:47:34 +00:00
Jared Pan
23ebccb46c MdeModulePkg/UsbBusDxe: Improve USB enumerating process
The patch enhances the USB enumeration process in EDK2 to improve compatibility with non-standards-compliant devices that may fail during standard enumeration sequences.
The suggested solution is based on USB specifications and references implementations from both Linux and Windows environments.

[Suggested solution]
- Integrated a retry mechanism to sequentially execute enumeration scripts, inspired by the enumeration flows of Windows, Linux, and EDK2. This improves robustness when handling corner-case devices.
- Do sanity check while the device report the device descriptor.
- AMD XHCI might need to wait for more time while sending the CLEAR_FEATURE reuqest.

Signed-off-by: Marlboro Chuang <marlboro.chuang@dell.com>
Signed-off-by: Jared Pan <jared.pan@dell.com>
2026-06-30 10:35:12 +00:00
Jiaqing Zhao
e3e93cf092 MdeModulePkg/PciBusDxe: Fix Mem64 BAR handling in IsPciDeviceRejected()
IsPciDeviceRejected() masks BAR value with 0xFFFFFFF0 before testing
the type bits (2:1) that mark a 64-bit memory BAR, essentially clears
them, making the 64-bit BAR code path unreachable and treated as if
it were 32-bit.

The function rejects a device when BAR looks unprogrammed by comparing
if its size mask equals its value. When a 64-bit BAR is mistaken for a
32-bit one, only its lower part is compared, possibly leading a valid
BAR being falsely rejected. For example, a 2G BAR with size mask
0x80000000 at 0x180000000 matches and the device is dropped.

This code runs during light enumeration (PciEnumeratorLight), used when
PCI resources are already assigned by the platform (e.g. Xen HVM, where
hvmloader programs the BARs). The rejected device never receives a
PciIo handle, so no driver can bind to it. For example, a virtio-vga
with a 64-bit BAR vanishes under OVMF on Xen, leaving the guest with
no graphics output.

Fix by testing the type bits on the raw BAR value before masking.

Signed-off-by: Jiaqing Zhao <Zhao.Jiaqing@amd.com>
2026-06-29 02:25:40 +00:00
Michael Kubacki
16b41f7d02 MdeModulePkg: Follow pragma once coding convention
Update recent changes in MdeModulePkg to follow the latest EDK II
C Coding Standards Specification (5.3) to use '#pragma once' instead
of traditional macro-based include guards in header files.

https://tianocore-docs.github.io/edk2-CCodingStandardsSpecification/draft/5_source_files/53_include_files.html#53-include-files

Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
2026-06-25 19:40:31 +00:00
Oliver Smith-Denny
a5fcc0a6ac MdeModulePkg: CxlDxe: Fix IA32 Build Break
CxlDxe is currently compiled as part of the MdeModulePkg
IA32 CI. When running CI with VS2022 version 14.44.35228.0,
the CI build fails with:

CxlDxe.lib(CxlDxe.obj) : unresolved external symbol __allmul
CxlDxe(CxlDxe.obj) : unresolved external symbol __allshl

CxlDxe is not intended to run on IA32 DXE systems, as such
systems are legacy, but until edk2 drops build support for
IA32 DXE (or at least CI for it), the build needs to work.

This fixes the 64 bit multiplication/shifting that occurs
in CxlDxe to use the BaseLib functions that avoid the
compiler intrinsics.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-25 15:15:38 +00:00
Dongyan Qian
5ac1b95b3e MdeModulePkg/PciBusDxe: Scan funcs when func 0 is absent
The PCI specification normally requires function 0 to be present
before functions 1 through 7 are used. PciBusDxe therefore stops
scanning a slot when probing function 0 fails.

Some virtualized PCI topologies may expose selected non-zero functions
to a guest while function 0 is hidden. Add an opt-in Feature PCD so a
platform can continue collecting device information for functions 1
through 7 when function 0 is absent.

The default remains FALSE, so existing platform behavior is unchanged
unless the platform explicitly enables the PCD.

Signed-off-by: Dongyan Qian <qiandongyan@loongson.cn>
2026-06-25 13:09:52 +00:00
Tuan Phan
42b690316c MdeModulePkg: CxlDxe: Fix uninitialized variable warnings
In CxlWriteRegblockRegisters() and PciUefiMemReadUInt32Array(),
Status is only assigned inside the for loop but is returned after
the loop exits, causing an uninitialized variable warning. Return
immediately on error to fix this.

Signed-off-by: Tuan Phan <tuan.phan@oss.qualcomm.com>
2026-06-24 14:49:50 +00:00
Tuan Phan
9044d2b33d MdeModulePkg: SdBlockIoPei: Fix uninitialized variable warnings
In SdPeimIdentification(), the compiler may inline SdPeimHcRwMmio()
because it only performs simple MMIO reads and writes. When inlined, the
fourth argument can appear to follow multiple control-flow paths
(MMIO read versus MMIO write), which may cause the compiler to report
a potential uninitialized variable warning when the value is used
later if it was not initialized up front.

Add an explicit Status check, consistent with other code in this file,
to make the control flow explicit and eliminate the compiler warning.

Signed-off-by: Tuan Phan <tuan.phan@oss.qualcomm.com>
2026-06-24 14:49:50 +00:00
Tuan Phan
55834be5d1 MdeModulePkg: UsbNetwork: Fix uninitialized variable warnings
In NetworkCommonDriverStart(), if gPxe is not NULL, TmpPxePointer should
be initialized as it is referenced later in the clean up code.

Signed-off-by: Tuan Phan <tuan.phan@oss.qualcomm.com>
2026-06-24 14:49:50 +00:00
Tuan Phan
1a86701fc0 MdeModulePkg: SpiNorFlashJedecSfdp: Fix uninitialized variable warnings
In GetEraseTypeRecord(), ensure ValueToCompare is initialized on all
code paths to prevent uninitialized variable warnings.

In SpiReadSfdpPtp(), return an error code immediately if any
iteration of the for loop fails, otherwise return EFI_SUCCESS
on success at the end of function.

Signed-off-by: Tuan Phan <tuan.phan@oss.qualcomm.com>
2026-06-24 14:49:50 +00:00
Qihang Gao
174573b3a7 MdeModulePkg: Display VID and DID using 4-digit hexadecimal number
No functional change.

Signed-off-by: Qihang Gao <gaoqihang@loongson.cn>
2026-06-15 02:25:50 +00:00
Mingjie Shen
45d477b22c MdeModulePkg: Replace manual alignment checks with helper macros
Replace manual alignment checks with IS_ALIGNED() and
ADDRESS_IS_ALIGNED().

Convert the following bitmask and modulo forms:

- ((E & ((PowOf2Expr) - ONE)) == ZERO)
- ((E & ((PowOf2Expr) - ONE)) != ZERO)
- ((E % (PowOf2Expr)) == ZERO)
- ((E % (PowOf2Expr)) != ZERO)

to the corresponding helper macro forms:

+ IS_ALIGNED (E, PowOf2Expr)
+ !IS_ALIGNED (E, PowOf2Expr)

PowOf2Expr is limited to known power-of-two expressions, including
SIZE_* and BASE_* macros, EFI_PAGE_SIZE, CPU_STACK_ALIGNMENT,
RUNTIME_PAGE_ALLOCATION_GRANULARITY, sizeof() of UEFI integer types
(e.g. BOOLEAN, CHAR16, UINT32, UINTN) and pointer types, and 1 << E1
expressions.

Address checks that cast the checked value to UINTN are written with
ADDRESS_IS_ALIGNED().

The change was generated with the Coccinelle semantic patch below.

```smpl
@power_of_2_expr@
expression PowOf2Expr;
expression E1;
typedef BOOLEAN, CHAR8, CHAR16, INT8, UINT8, INT16, UINT16, INT32, UINT32, INT64, UINT64, INTN, UINTN;
type ScalarType = { BOOLEAN, CHAR8, CHAR16, INT8, UINT8, INT16, UINT16, INT32, UINT32, INT64, UINT64, INTN, UINTN };
type AnyType;
type PointerType = AnyType *;
idexpression ScalarType ScalarValue;
idexpression PointerType PointerValue;
constant SizeBase =~ "^(SIZE|BASE)_(1|2|4|8|16|32|64|128|256|512)[KMGTPE]B$";
constant NamedPowerOf2 =~ "^(EFI_PAGE_SIZE|CPU_STACK_ALIGNMENT|RUNTIME_PAGE_ALLOCATION_GRANULARITY)$";
constant ONE = {1, 1U, 1u};
@@
(
(
  SizeBase
|
  NamedPowerOf2
|
  ONE << E1
|
  sizeof (ScalarType)
|
  sizeof (PointerType)
|
  sizeof (ScalarValue)
|
  sizeof (PointerValue)
)
&
PowOf2Expr
)

@aligned depends on power_of_2_expr disable is_zero,isnt_zero@
expression E;
expression power_of_2_expr.PowOf2Expr;
constant ONE = {1, 1U, 1u};
constant ZERO = {0, 0U, 0u};
@@
(
  ((E & (E - ONE)) == ZERO)
|
- ((E & ((PowOf2Expr) - ONE)) == ZERO)
+ IS_ALIGNED (E, PowOf2Expr)
|
  ((E & (E - ONE)) != ZERO)
|
- ((E & ((PowOf2Expr) - ONE)) != ZERO)
+ !IS_ALIGNED (E, PowOf2Expr)
|
- ((E % (PowOf2Expr)) == ZERO)
+ IS_ALIGNED (E, PowOf2Expr)
|
- ((E % (PowOf2Expr)) != ZERO)
+ !IS_ALIGNED (E, PowOf2Expr)
)

@address_is_aligned@
typedef UINTN;
expression *Address;
expression Alignment;
@@
- IS_ALIGNED ((UINTN) Address, Alignment)
+ ADDRESS_IS_ALIGNED (Address, Alignment)

@normalize_aligned disable paren expression@
expression E, SZ;
@@
(
- (IS_ALIGNED (E, SZ))
+ IS_ALIGNED (E, SZ)
|
- (!IS_ALIGNED (E, SZ))
+ !IS_ALIGNED (E, SZ)
)

@normalize_macro_args disable paren expression@
expression E, SZ;
@@
(
- IS_ALIGNED ((E), SZ)
+ IS_ALIGNED (E, SZ)
|
- IS_ALIGNED (E, (SZ))
+ IS_ALIGNED (E, SZ)
)
```

Signed-off-by: Mingjie Shen <shen497@purdue.edu>
2026-06-09 07:20:10 +00:00
Qihang Gao
84a180f8aa MdeModulePkg: Remove Depex section in UEFI_DRIVER and UEFI_APPLICATION
According to INF specification, UEFI_DRIVER and UEFI_APPLICATION
cannot have Depex section. So remove it.

Signed-off-by: Qihang Gao <gaoqihang@loongson.cn>
2026-06-09 05:51:07 +00:00
Sean Brogan
86e285dd21 MdeModulePkg:Last LBA missed on NvmExpressMediaClear
Off by one error in the code of NvmExpressMediaClear() causes the last
LBA to be missed when clearing the media.

This patch fixes the issue by adjusting the loop condition to ensure
that all LBAs are cleared properly.

Signed-off-by: Sean Brogan <sebrogan@microsoft.com>
2026-06-08 22:56:03 +00:00
Sean Brogan
c3a037c993 MdeModulePkg: NvmExpressDriverBindingStart - early return path leaks
After allocating Private via AllocateZeroPool and successfully opening
both gEfiDevicePathProtocolGuid and gEfiPciIoProtocolGuid BY_DRIVER,
the function attempts PciIo->Attributes(EfiPciIoAttributeOperationGet)
If this call fails, the code executes return Status instead of goto Exit.

Trigger path:

NvmExpressDriverBindingStart is called.
OpenProtocol for DevicePath succeeds (opens BY_DRIVER).
OpenProtocol for PciIo succeeds (opens BY_DRIVER).
AllocateZeroPool for Private succeeds.
PciIo->Attributes(Get) returns an error.
return Status bypasses the Exit: label.

Consequence:
Memory leak of NVME_CONTROLLER_PRIVATE_DATA. Two protocols remain opened
BY_DRIVER on the controller handle, preventing other drivers from binding.

Signed-off-by: Sean Brogan <sebrogan@microsoft.com>
2026-06-02 22:23:59 +00:00
Sean Brogan
ebb314b12d MdeModulePkg: NvmExpressMediaClear - Fix BufferSize value in writeblocks
NvmExpressMediaClear requires that the overwrite buffer be
the same size as the block size of the media but then
WriteBlocks expects BufferSize in bytes. NvmExpressMediaClear was
hardcoded to call using 1.  This causes the WriteBlocks to fail.

Signed-off-by: Sean Brogan <sebrogan@microsoft.com>
2026-05-26 04:14:33 +00:00
Oliver Smith-Denny
bf5ed9cc55 Global: Fix Spelling Errors in PCI/PCIe Definitions
Fix spelling errors in definitions in Pci22.h.
Update consumers in MdeModulePkg, OvmfPkg, ShellPkg,
and SourceLevelDebugPkg.

Continuous-integration-options: PatchCheck.ignore-multi-package

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-05-08 02:15:34 +00:00
Oliver Smith-Denny
7c440a7a2b MdePkg,MdeModulePkg: Fix Spelling Errors in Atapi Definitions
Fix spelling errors in definitions in Atapi.h.
Update consumers in MdeModulePkg.

Continuous-integration-options: PatchCheck.ignore-multi-package

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-05-08 02:15:34 +00:00
Benjamin Doron
8add400a8b MdeModulePkg: Cleanup debug print readability
All debug prints should end in a newline character.

Signed-off-by: Benjamin Doron <benjamin.doron00@gmail.com>
2026-05-06 10:43:05 +00:00
Annie Li
5caf4c6aeb MdeModulePkg,MdePkg: Send I/O without FUA if necessary
Commit 8c654bb3ec sets FUA bit forcefully in SCSI sync I/O to
avoid possible data loss. However, it may cause issues for the
storage without the support FUA and WCE.

For example, Windows Server 2025 guest fails to boot from
vhost-scsi block device in such scenario. The booting Error
code is 0xc0000185, the SCSI command fails with the following,

Mode Sense Key: EFI_SCSI_SK_ILLEGAL_REQUEST
Additional Sense Code: EFI_SCSI_ASC_INVALID_FIELD

This patch gets the FUA and WCE support of the storage and sets
FUA conditionally.

Continuous-integration-options: PatchCheck.ignore-multi-package

Signed-off-by: Annie Li <annie.li@oracle.com>
2026-05-06 08:04:12 +00:00
Annie Li
ee58614bbb MdeModulePkg/ScsiDiskDxe: Check Write Caching and FUA support
Check Write Caching and FUA support of the storage, then save
the result if both are disabled.

Signed-off-by: Annie Li <annie.li@oracle.com>
2026-05-06 08:04:12 +00:00
Oleksandr Tymoshenko
a87c9f0621 MdeModulePkg: Add CxlDxe driver
Add CxlDxe driver that provides CxlIo protocol.

Co-authored-by: Abhishek Narvaria <abhi.n@samsung.com>
Co-authored-by: Alok Rathore <alok.rathore@samsung.com>
Co-authored-by: Nick Graves <nicholasgraves@google.com>
Co-authored-by: Ryan Heise <heiserya@google.com>
Co-authored-by: Sayanta Pattanayak <sayanta.pattanayak@arm.com>
Co-authored-by: Sweta Kumari <s5.kumari@samsung.com>

Signed-off-by: Oleksandr Tymoshenko <ovt@google.com>
2026-05-01 08:48:04 +02:00
Qihang Gao
351dfdb383 MdeModulePkg: Remove duplicate procotols guid in INF files
In PciSioSerialDxe driver, gEfiDevicePathProtocolGuid appears twice in
[Procotols] section. In PiSmmCore driver, gEfiSmmSxDispatch2ProtocolGuid
appears twice in [Procotols] section. In PiSmmIpl driver,
gEfiEventReadyToBootGuid appears twice in [Procotols] section. In
DxeCapsuleLib driver, gEfiCapsuleVendorGuid appears twice in [Guids]
section. The duplicate ones should be removed.

Signed-off-by: Qihang Gao <gaoqihang@loongson.cn>
2026-04-29 11:18:10 +02:00
“Shabab
c8833afa7a MdeModulePkg/NvmExpressDxe: Mark CDW10/CDW11 valid for Format and Sanitize
NVMe Format and Sanitize admin commands correctly populate CDW10
(and CDW11 for Sanitize), but these codewords are not marked as valid
in the passthru command packet. As a result, the passthru layer does
not include the populated codewords in the command payload, causing
the commands to fail.

Set the appropriate CDW validity flags in the passthru command packet:
- Format NVM: CDW10_VALID
- Sanitize: CDW10_VALID | CDW11_VALID

This ensures the populated codewords are included in the passthru
command payload and the commands are issued correctly.

Signed-off-by: Shabab Alam <shabalam@qti.qualcomm.com>
2026-04-29 06:33:41 +00:00
Abdul Lateef Attar
c31b880bd2 MdeModulePkg/NetworkCommon: Add PCD for USB network periodic timer
Replace the hardcoded NETWORK_COMMON_POLLING_INTERVAL (0x10 = 16ms)
with a new PCD PcdUsbNetworkPeriodicalTimer, allowing platforms to
configure the asynchronous transfer interval for USB network devices.

The default value of 16ms preserves existing behaviour.

EFI_USB_IO_PROTOCOL.UsbAsyncInterruptTransfer(), the PollingInterval
parameter must be between 1 and 255 milliseconds; a value of 0
returns EFI_INVALID_PARAMETER. The PCD is declared with a
@ValidRange of 1-255 and an ASSERT guards against a zero value at
runtime.

Co-authored-by: Abner Chang <abner.chang@amd.com>
Signed-off-by: Abdul Lateef Attar <AbdulLateef.Attar@amd.com>
2026-04-21 13:29:12 +00:00
Shabab Alam
3971a4dba9 MdeModulePkg/NvmExpressDxe: Clear NSID to 0 for sanitize command
A purge erase operation on NVMe devices using the MediaSanitize
(MediaPurge) protocol fails with Status Code 02h (Invalid Field
in Command).

According to NVMe specification revision 1.4c, the Sanitize
command (OpCode 84h) does not use the NSID field (Section 5,
Figure 142). For commands that do not use NSID, the field must
be cleared to 0 as defined in Section 4.2, Figure 106.

Clear NSID to 0 before issuing the Sanitize command to ensure
spec compliance and prevent command failure.

Signed-off-by: Shabab Alam <shabalam@qti.qualcomm.com>
2026-04-15 02:50:05 +00:00
Michael D Kinney
defbd14d63 Revert "MdeModulePkg/PciBusDxe: Degrade MEM64 to PMEM64..."
This reverts commit f6489621b8.

MdeModulePkg/PciBusDxe: Degrade MEM64 to PMEM64 when bridge lacks MEM64

A number of compatibility issues have been reported with this change
to the PciBusDxe behavior. Revert this change at this time to give
time for all the issues to be reviewed and options for supporting
this new behavior to be evaluated and fully validated.

Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com>
2026-03-24 02:11:23 +00:00
Abdul Lateef Attar
1bd61a9409 MdeModulePkg/SpiNorFlashJedecSfdp: Limit debug output
Change debug print level from DEBUG_INFO to
DEBUG_VERBOSE to limit excessive output.
Since Spinor Sfdp operations can generate a large number of
debug messages due to frequent read/write/erase actions,
this change reduces log verbosity at the INFO level.

Signed-off-by: Abdul Lateef Attar <AbdulLateef.Attar@amd.com>
2026-03-23 16:30:18 +00:00
Ashish Singhal
b074eb78b4 MdeModulePkg/PciBusDxe: Add optional CRS retry for enumeration
The current PciDevicePresent() implementation skips PCIe devices that
return Configuration Request Retry Status (CRS) during enumeration.
This causes devices that are slow to initialize (e.g., after power-on
or reset) to be missed entirely.

Per PCIe Base Specification Rev 3.1 Section 2.3.1, when CRS Software
Visibility is enabled and a device returns CRS, the Root Complex
reports Vendor ID as 0x0001. The specification recommends software
retry the configuration read until the device becomes ready.

This patch adds optional CRS retry support controlled by PCDs:

- PcdPciCrsRetryIntervalUs: Retry interval in microseconds (default 10000)
- PcdPciCrsTimeoutSeconds: Total timeout in seconds (default 0)

By default (PcdPciCrsTimeoutSeconds=0), CRS retry is disabled and
devices returning CRS are skipped during enumeration. Platforms
requiring CRS retry support should set PcdPciCrsTimeoutSeconds to
a non-zero value.

Additional improvements:
- Add PCI_VENDOR_ID_NONE and PCI_VENDOR_ID_CRS macros for readability
- Handle invalid PCD configurations (e.g., zero retry interval)
- Add DEBUG output for CRS detection, successful retry, and timeout

Signed-off-by: Ashish Singhal <ashishsingha@nvidia.com>
2026-03-17 02:03:32 +00:00
Jacek Kolakowski
2e92a908e7 MdeModulePkg: Mark PcdMrIovSupport obsolete - deprecated in PCIe 6.0
MR-IOV was actually not used in MdeModulePkg and it has been
deprecated in PCIe 6.0 specification. Remove code references,
but keep PcdMrIovSupport with just a comment that it is deprecated.

Signed-off-by: Jacek Kolakowski <Jacek.Kolakowski@intel.com>
2026-02-25 05:03:02 +00:00
Jacek Kolakowski
24eddc65b3 MdeModulePkg: Add platform limit for size in Resizable BAR
Resizable BAR driver selects max available BAR size to configure for use.
It may happen that some PCIe device declare support for size that exceeds
processor address width. Platform needs a way to define the max size it
can accept. This change introduce PCD called PcdPcieResizableBarMaxSize.
It is dynamic PCD where platform can provide its limit for BAR size.
Such PCD can be also controlled with a configuration knob.

Signed-off-by: Jacek Kolakowski <Jacek.Kolakowski@intel.com>
2026-02-25 03:40:14 +00:00
Michael Kubacki
7a934d0bef MdeModulePkg: Replace include guards with #pragma once
Replace traditional `#ifndef`/`#define`/`#endif` include guards with
`#pragma` once.

`#pragma once` is a widely supported preprocessor directive that
prevents header files from being included multiple times. It is
supported by all toolchains used to build edk2: GCC, Clang/LLVM, and
MSVC.

Compared to macro-based include guards, `#pragma once`:

- Eliminates the risk of macro name collisions or copy/paste errors
  where two headers inadvertently use the same guard macro.
- Eliminate inconsistency in the way include guard macros are named
  (e.g., some files use `__FILE_H__`, others use `FILE_H_`, etc.).
- Reduces boilerplate (three lines replaced by one).
- Avoids polluting the macro namespace with guard symbols.
- Can improve build times as the preprocessor can skip re-opening the
  file entirely, rather than re-reading it to find the matching
  `#endif` ("multiple-include optimization").
  - Note that some compilers may already optimize traditional include
    guards, by recognzining the idiomatic pattern.

This change is made acknowledging that overall portability of the
code will technically be reduced, as `#pragma once` is not part of the
C/C++ standards.

However, this is considered acceptable given:

1. edk2 already defines a subset of supported compilers in
   BaseTools/Conf/tools_def.template, all of which have supported
   `#pragma once` for over two decades.
2. There have been concerns raised to the project about inconsistent
   include guard naming and potential macro collisions.

Approximate compiler support dates:

- MSVC: Supported since Visual C++ 4.2 (1996)
- GCC: Supported since 3.4 (2004)
  (http://gnu.ist.utl.pt/software/gcc/gcc-3.4/changes.html)
- Clang (LLVM based): Since initial release in 2007

Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
2026-02-23 21:01:28 +00:00
Paul Grimes
1a261da766 MdeModulePkg/UsbMassStorageDxe: Add retry mechanism to UsbMassReadBlocks
Add a retry mechanism to UsbMassReadBlocks() to improve robustness
when reading from USB mass storage devices. Some USB devices may
experience transient failures during read operations that can be
recovered by resetting the device and retrying.

The implementation:
- Saves original buffer parameters (Buffer, Lba, BufferSize)
- Attempts the read operation up to 4 times (initial + 3 retries)
- Resets the device via UsbMassReset() before each retry
- Restores buffer parameters before each retry attempt

This change is compliant with USB Mass Storage Class Bulk-Only
Transport Spec Rev 1.0:
- Section 5.3.4: Defines Reset Recovery procedure
- Section 3.1: States device is ready for next CBW after reset

Cc: Liming Gao <gaoliming@byosoft.com.cn>
Cc: Jacek Kolakowski <jacek.kolakowski@intel.com>
Signed-off-by: Paul Grimes <Paul.Grimes@amd.com>
2026-01-30 07:02:52 +00:00
Alok Kulkarni
f6489621b8 MdeModulePkg: PciBusDxe: Degrade MEM64 to PMEM64 when bridge lacks MEM64
P2P bridge Memory Base/Limit registers (0x20-0x22) only support 32-bit
addresses. Previously, MEM64 resources behind such bridges were always
degraded to MEM32, forcing allocation below 4GB. This can lead to
resource constraints when using massive storage (such as MPF drives)
as MEM32 space is limited on most platforms.

Based on PCIe Base Specification 6.3+, assigning 64-bit resources
irrespective of the prefetchable/non-prefetchable BAR bit is allowed.

In DegradeResource(), if an upstream bridge supports PMEM64, MEM64
resources are now degraded to PMEM64 first. This enables 64-bit BAR
allocation for devices like NVMe controllers that declare non-
prefetchable 64-bit BARs.

We still fall back to MEM32 degradation if the bridge lacks PMEM64
support as well.

Ref: PCI-SIG ECN "Removing Prefetchable Terminology" (2024-04-05)
Ref: PCIe Base Specification 6.3+

Signed-off-by: Kun Qin <kuqin12@gmail.com>
2026-01-30 04:53:05 +00:00
Dongyan Qian
8c3e181b79 MdeModulePkg/PciBusDxe: Fix typo in Buffer parameter description
The comment for the Buffer parameter incorrectly said
"then no the size" instead of "then the size".
This patch fixes the typo only; no functional changes.

Signed-off-by: Dongyan Qian <qiandongyan@loongson.cn>
2026-01-23 10:46:37 +00:00
Arkadiusz Filipowski
b220ba807e MdeModulePkg: Fix overflow in PciAllocateBusNumber
When StartBusNumber is 0xFF NextNumber would overflow and wrap back to 0.
This will be bypass check NextNumber > MaxNumberInRange as a result
PCI enumeration will continue instead of breaking due to lack of resources.

Signed-off-by: Arkadiusz Filipowski <arkadiusz.filipowski@intel.com>
2026-01-14 05:22:38 +00:00
Black.Li
7ca8b1b4c7 MdeModulePkg/UfsPassThruDxe:Fix Ufs DM Command issue
After Execute UFS SCSI Commands, the Trd->PRDTL is dirty. It will cause issue
when next UFS DM Command is executed.

According to UFSHCI Spec, for UFS DeviceManagement function Trd->PRDTL
must be set to Zero.

Signed-off-by: Black.Li <black.li@cixtech.com>
2025-12-24 06:41:24 +00:00
Khalid Ali
786de8636a MdeModulePkg/PciBusDxe: Fix boot hang introduced by ff3c1ad
The changes introduced by ff3c1ad which made two calls to
ProcessOpRomImage() resulted a platform where single OpRom present, the
same image to be loaded and started.

Prevent loading and starting same image twice.

Signed-off-by: Khalid Ali <khaliidcaliy@gmail.com>
Suggested-by: Ard Biesheuvel <ardb@kernel.org>
2025-12-15 08:11:30 +00:00
Qihang Gao
ff3c1adf20 MdeModulePkg: Load the native Option ROM image if the native one exists
Issue:https://github.com/tianocore/edk2/issues/11800

If there are multiple Option ROM images existed, current code will load
the first image that the emulator supports. Usually, x86 ROM image is
the first one and non-x86 ROM image is behind x86 ROM image. When the
emulator is introduced, x86 ROM image instead of native image is loaded
on non-x86 platforms.
This patch introduces a mechanism to prioritize the loading of native
images. Firstly, search the native image. If the native one is found,
just finish the process since the goal is reached. Otherwise, search
the foriegn images that the platform may support.

Signed-off-by: Qihang Gao <gaoqihang@loongson.cn>
Signed-off-by: Chao Li <lichao@loongson.cn>
Suggested-by: Ard Biesheuvel <ardb@kernel.org>
Tested-by: Chen Zhang <zhangchen@loongson.cn>
Cc: Dongyan Qian <qiandongyan@loongson.cn>
2025-12-10 09:53:49 +00:00
Aaron Pop
1aedb79e9b MdeModulePkg: SpiNorFlash update FillWriteBuffer headers.
The function headers for FillWriteBuffer have become out of
date with the implementation. Update the function headers
to more clearly define the interface for recent changes.

Signed-off-by: Aaron Pop <aaronpop@microsoft.com>
2025-11-24 10:07:21 +01:00
Gowtham M
18ac0c8e93 MdeModulePkg/Bus: Remove ScsiPassThruProtocolGuid
The legacy ScsiPassThruProtocol has been removed as per
the UEFI 2.10A specification.
This commit, removes references to ScsiPassThruProtocol and
transitions the implementation to only use ExtScsiPassThruProtocol,
which provides enhanced support for device enumeration,
target/LUN discovery, and broader SCSI compatibility.

Cc: Sachin Ganesh <sachinganesh@ami.com>
Signed-off-by: Gowtham M <gowthamm@ami.com>
2025-11-23 18:40:59 +00:00