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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
According to INF specification, UEFI_DRIVER and UEFI_APPLICATION
cannot have Depex section. So remove it.
Signed-off-by: Qihang Gao <gaoqihang@loongson.cn>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>